// JavaScript Document
var phpsession = document.getElementById("phpsession");
var validURL;
var videoID;
var properFileName;
var firstHidden = false;
var fileNameTxt = phpsession + parseInt(new Date().getTime().toString().substring(0, 10));
var textFileResponse = '';
var startTime;
var continueTime;
var done = false;

var hasActiveSubscriptions = 0;

function start_conversion(){
    document.getElementById('pleasewait').className = "shownDiv";
    document.getElementById('service_start').className = "hiddenDiv";
}

function end_conversion(){
    document.getElementById('pleasewait').className = "hiddenDiv";
    document.getElementById('service_start').className = "shownDiv";
}

function convert(){
    var terms = document.getElementsByName("terms");
    if(!terms[0].checked){
        alert('You need to agree with the Terms please');
        return false;
    }

    var audio_format = document.getElementById("audio_format").value;	
	if(audio_format==0){
		alert("Please chose format to convert");
		return false;
	}

    start_conversion();
    $.ajax({
	   type: "GET",
	   url: "check_user_session.php",
	   data: 'check=subscription',
	   success: function(reply){
                if(reply==1){
                     if ( typeof(_CONVER_COUNT_COOKIE) != "undefined") {
                        if (getCookie(_CONVER_COUNT_COOKIE) == 1) { // already done 1 convert
                              startGateway('MTM2MDE%3D');
                              proceed_convert();
                              return false;
                        }
                        else { //no converts yet
                            setCookie(_CONVER_COUNT_COOKIE,1,365);
                            proceed_convert();
                        }
                    }
                }

                if(reply==0){
                     if ( typeof(_CONVER_COUNT_COOKIE) != "undefined") {
                        if (getCookie(_CONVER_COUNT_COOKIE) == 1) { // already done 1 convert
                              startGateway('OTg0OQ%3D%3D');
                              //proceed_convert();
                              return false;
                        }
                        else { //no converts yet
                            setCookie(_CONVER_COUNT_COOKIE,1,365);
                            proceed_convert();
                        }
                    }
                }

                if(reply==2){
                     proceed_convert();
                }
           }
    });
    return false;
}

function proceed_convert(){
	var url = document.getElementById('url').value;
	var valueNumber = document.getElementById('numberid').value;

	 $.ajax({
	   type: "GET",
	   url: "validate.php",
	   data: 'url=' + url +'&valuee=' + valueNumber,
	   success: function(reply){

		if(reply==1 || reply==2){
			alert('Invalid URL - Please use a correct Youtube URL');
		}
		else{
		reply;
		$("#labelinsert").hide("slow");
		$("#w_span_auto").hide("slow");
		$("#pleasewait").show("slow");
		$("#loading").show("slow");
		$("#done").html("&nbsp;&nbsp;Finding Video...");
		videoID = reply;
		getVideoDetails(videoID);
		}

	    }//function
	 });//ajax
}

function getVideoDetails(vid){

	   $.ajax({
	   type: "GET",
	   url: "getvideo.php",
	   data: 'videoid=' + vid,
	   success: function(found){

		if(found==0){
			alert('Youtube video not found - check URL');
			window.location.reload();
		}
		else{
		validURL = found;
		properFileName = found;
		//convertNow('http://www.youtube.com/watch?v='+videoID);

    $("#getaudiobutton").hide();
		$("#loading").hide("slow");
		$("#done").html("<input id='convertaudiobutton' name='convertaudiobutton' onclick='prepareConvertNow(videoID)' type='button' value='Convert' />");

		}

	    }//function

	 });//ajax


}

function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}


function prepareConvertNow(videoID){
    //set default value for audion format to download
    var audio_format = 'mp3';
    audio_format = document.getElementById("audio_format").value;
    convertNow("http://www.youtube.com/watch?v=" + videoID,audio_format);
}

function convertNow(validURL,audio_format){
    		$("#loading").show("slow");
		$("#done").html("&nbsp;&nbsp;Downloading & Converting Video...<br /><br />");

	   startTime = setTimeout('getStatus();', 6000);
       $.ajax({
	   type: "GET",
	   url: "main.php",
	   data: 'url=' + validURL + '&filename=' + fileNameTxt + '&format='+audio_format,
	   success: function(msg){
               if(msg==0){
                   alert("Convertion error occured.");
                   return false;
               }
                done = true;
		$("#loading").hide("slow");
                //return false;
                $("#done").html("<form id=\"formid\" class=\"clean-ok\" method=\"get\" action=\"download.php\"> <input type=\"hidden\" name=\"file\" value=\"" + msg + "\" /><input type=\"hidden\" name=\"format\" value=\"" + audio_format + "\" /><input type=\"hidden\" name=\"properFilename\" value=\"" + properFileName + "\" /> <input name=\"download\" type=\"submit\" value=\"Download Audio\" /></form><a href='index.php' style='color:white;'><b>Get Another Audio</b></a>");
	   }//function

	 });//ajax

}//function convertNow

function getStatus()
{
		if(done==false){
		$.ajax({
		type: "POST",
		url: "fileReader.php",
		data: 'textFile=' + fileNameTxt,
		success: function(respomse){
		if (done) return;
		textFileResponse = respomse.split(" ");
		$("#done").html("Downloading & Converting Video...<b style='font-size:19px;color:white;'>" + textFileResponse[0] + "</b><br /><b>" + properFileName + '</b>');
		continueTime = setTimeout('getStatus();', 3000);
		}
		});//ajax
		}
}

function empty( mixed_var ) {   // Determine whether a variable is empty
    return ( mixed_var === "" || mixed_var === 0   || mixed_var === "0" || mixed_var === null  || mixed_var === false);
}


function problem(){

	var value = document.getElementById('comments').value;
	var emailme = document.getElementById('email').value;
        var name = document.getElementById('name').value;
        if(!empty(value)&&!empty(emailme)&&!empty(name)){
             $.ajax({
               type: "GET",
               url: "feedback.php",
               data: 'feedback=' + value + '&email=' + emailme+'&name=' + name,
               success: function(responce){
                    if(responce==1){
                        $("#responce").html("<p style='color:black;'><b>Thank you for contacting us! We have received your message and will respond as soon as possible, thanks for your patience.</b></p>");
                        document.getElementById('form').setAttribute("style", "display:none;");
                    }else{
                        alert("An error occured. Please try again later.");
                    }
               }

             });
        }else{
            alert("Please fill in all fields to submit your message.");
        }
}

function highlight(el){
    var format = el.id;
    //alert(checked_format);
    switch (format) {
            case 'format_1': {
                  el.src = 'images/mp3_over.gif';
            }
            break;
            case 'format_2': {
                  el.src = 'images/mp4_over.gif';
            }
            break;
            case 'format_3': {
                  el.src = 'images/3gp_over.gif';
            }
            break;
    }

}

function unhighlight(el){
    var format = el.id;
    //alert(format);
    switch (format) {
            case 'format_1': {
                  el.src = 'images/mp3.gif';
            }
            break;
            case 'format_2': {
                  el.src = 'images/mp4.gif';
            }
            break;
            case 'format_3': {
                  el.src = 'images/3gp.gif';
            }
            break;
    }
}

function changeImg(el) {
        var format = el.id;
        var audio_format;
        var checked_format = document.getElementById("checked_format").value;
        var delimiter = ':';
        //alert(checked_format);
        var format_info = checked_format.toString().split ( delimiter.toString() );
         switch (format) {
            case 'format_1': {
                  if(el.src == 'images/mp3.gif'){
                      checked_format = format_info[0]+":"+"1";
                      el.src = 'images/mp3.gif';
                      reset_highlihts(false);
  //                    alert(document.getElementById('format_1').getAttribute('onmouseover'));
                  }else{
                      checked_format = format_info[0]+":"+"0";
                      el.src = 'images/mp3_over.gif';;
                      reset_highlihts(1);
//                      alert(document.getElementById('format_1').getAttribute('onmouseover'));
                  }
                  unset_formats(1);
                  audio_format = 'mp3';
            }
            break;
            case 'format_2': {

                  if(el.src == 'images/mp4.gif'){
                      checked_format = format_info[0]+":"+"1";
                      el.src = 'images/mp4.gif';
                      reset_highlihts(false);
                  }else{
                      checked_format = format_info[0]+":"+"0";

                      el.src = 'images/mp4_over.gif';
                       reset_highlihts(2);
                  }
                  unset_formats(2);
                  audio_format = 'mp4';
            }
            break;
            case 'format_3': {
                  if(el.src == 'images/3gp.gif'){
                      checked_format = format_info[0]+":"+"1";
                      el.src = 'images/3gp.gif';
                      reset_highlihts(false);
                  }else{
                      checked_format = format_info[0]+":"+"0";
                      el.src = 'images/3gp_over.gif';
                       reset_highlihts(3);
                  }
                  unset_formats(3);
                  audio_format = '3gp';
            }
            break;
            default: audio_format = 'mp3';
        }

        document.getElementById("checked_format").value = checked_format;
        document.getElementById("audio_format").value=audio_format;
    }

    function reset_highlihts(exception){
        for(var i=1;i<4;i++){
            document.getElementById('format_'+i).setAttribute("onmouseover", "highlight(this)");
            document.getElementById('format_'+i).setAttribute("onmouseout", "unhighlight(this)");
        }
        if(exception){
            document.getElementById('format_'+exception).setAttribute("onmouseover", "return true");
            document.getElementById('format_'+exception).setAttribute("onmouseout", "return true");
        }
    }

    function unset_formats(exception){
        var file;
        for(var i=1;i<4;i++){
            if(i!=exception){
                switch(i){
                    case(1):{
                        file = 'images/mp3.gif';
                        //file_over = 'images/mp3_over.gif';
                    }
                    break;
                    case(2):{
                        file = 'images/mp4.gif';
                        //file_over = 'images/mp4_over.gif';
                    }
                    break;
                    case(3):{
                        file = 'images/3gp.gif';
                        //file_over = 'images/3gp_over.gif';
                    }
                    break;
                }
                document.getElementById('format_'+i).src = file;
            }
        }
    }
