var popupStatus = 0;
var phoneNo		= null;
var currentType = null;
var disableDownlaod = false;

$(document).ready(function(){
   
    $(".popup").click(function(){
      	 loadPopup();
     	
     /* 
      $('<div id="backgroundPopup"/>').load("_common/popup-form.txt #popupContact", function(results){
        
        console.log(results);
        
        }); 
     */
        return false;   
    });
    
    $("#popupContactClose").click(function(){
        disablePopup();
    });
  
    $("#backgroundPopup").click(function(){  
        disablePopup();  
    });
    
    $(document).keypress(function(e){
    	if(e.keyCode == 27 && popupStatus == 1) {
    		disablePopup();
    	}
    }); 
})

function showCaptcha(use_ajax,use_var){
	if(use_ajax){
		var opts = {
						url: "./",
						type: "POST",
						data: {ajxreq:1, action: 'show_captcha'},
						datatype:'xml',
						async:true,
						complete: function(req) {
							if(req.status == 200) {
								if(req.responseText.length > 0) {	
									var show_captcha = $(req.responseXML).find("response").find('show_captcha').text();
									if (show_captcha == 1) {
											var rand = Math.floor(Math.random()*100000000);
											$('#captcha-img').attr('src', '/modules/Captcha/index.php?w=125&h=40&r='+rand);
											$('#captcha_user').attr('value', '');
											$('#showCaptcha').show();
										return true;
									}
									else{
											$('#showCaptcha').hide();	
											$('#captcha-img').attr('src', '');
											return false;	
									}
								}
							}
						}
					};
		$.ajax(opts);
	}
	else{
		if(use_var){
			var rand = Math.floor(Math.random()*100000000);
			$('#captcha-img').attr('src', '/modules/Captcha/index.php?w=125&h=40&r='+rand);
			$('#captcha_user').attr('value', '');
			$('#showCaptcha').show();
		}
		else{
			$('#showCaptcha').hide();	
			$('#captcha-img').attr('src', '');
		}	
	}
}


function loadPopup(type, content_id)
{
	checkAccessSessionData();
	currentType = type;
	var session_access =  $("#sess_access").val();
	
	if(session_access==1 && content_id.length > 0){
	
		submitPassword(content_id, true);
		
		return 0;
	}
	else{
	
	$('#popStep1').css('display', 'block');
	$('#popStep2').css('display', 'none');
	$('#popStep1 span.error').text('');
	$('#popStep2 span.error').text('');
	$('#numero').val('');
	$('#captcha_user').val('');
	$('#passw').val('');
	
	showCaptcha(true, false);	
//	var rand = Math.floor(Math.random()*100000000);
//	
//	$('#captcha-img').attr('src', '/modules/Captcha/index.php?w=125&h=40&r='+rand);
//	

	if (popupStatus == 0) {
    	$('#backgroundPopup').css({
    			"opacity":"0.7"
    			});
    $("#backgroundPopup").fadeIn("fast");
    
    jQuery.each(jQuery.browser, function(i) {
        if($.browser.msie && jQuery.browser.version.substr(0,3)=="6.0"){
          $("#popupContact").fadeIn("fast").css('background-image','url(/img/it/h3g/html/pop_up_ie6.gif)');
        } else {
          $("#popupContact").fadeIn("fast").css('background-image','url(/img/it/h3g/html/pop_up.png)');
        }
    });
    centerPopup();
    popupStatus = 1;
  };
}
}
    
function disablePopup()
{
    if(popupStatus == 1) {
    	$("#backgroundPopup").fadeOut("normal");
        $("#popupContact").fadeOut("normal");
        currentType = null;
        popupStatus = 0;
    };
}


function centerPopup() 
{    
    var windowWidth = document.documentElement.clientWidth;
    var windowHeight = document.documentElement.clientHeight;
    var popupWidth = $("#popupContact").width();
    var popupHeight = $("#popupContact").height();
    
    $('#popupContact').css({
    		"position":"absolute",
    		"top" : windowHeight/2-popupHeight/2,
    		"left" : windowWidth/2-popupWidth/2
    });
    
    $("#backgroundPopup").css({ "height": windowHeight, "width": windowWidth });  
}
 
function submitPhoneNo(content_id)
{
	var msisdn = parseInt($('#numero').val());
	var captchaCode = parseInt($('#captcha_user').val());
	if (content_id < 1) {
		alert('System error!');
		return false;
	}
	if (msisdn > 1) {	
			phoneNo = msisdn;
			var opts = {
					url: "./",
					type: "POST",
					data: {ajxreq:1, action: 'submitPhoneNo', content_id: content_id, msisdn : msisdn, current_type: currentType, captcha_user:captchaCode},
					datatype:'xml',
					async:true,
					complete: function(req) {
						if(req.status == 200) {
							if(req.responseText.length > 0) {	
								var error_code = $(req.responseXML).find("response").find('error_code').text();
								if (error_code == 0) {
									var sub = $(req.responseXML).find("response").find('subscribed').text();
									$('#popStep1').css('display', 'none');
									$('#popStep2').css('display', 'block');
									$("#subscribed").get(0).value = sub;
								}else{
									$('#popStep1 span.error').text(error_msg[error_code]);
								}
								var use_captcha = $(req.responseXML).find("response").find('show_captcha').text();
								showCaptcha(false, use_captcha);
								
								return false;
							}
						}
					}
				};
			$.ajax(opts);
	}else{
		$('#popStep1 span.error').text(error_msg[101]);
	}
	return false;
}

function submitPassword(content_id,use_access_session_data) 
{
	if(use_access_session_data){
		var ajax_action='ppd_with_session_data';
	}
	else
		var ajax_action='submitpass';	
	
	var password = $('#passw').val();
	var subscribed = $('#subscribed').val();
	if (content_id < 1) {
		alert('System error!');
		return false;
	}
	if (ajax_action=='ppd_with_session_data' || (ajax_action=='submitpass' && password.length > 1)) {	
			var opts = {
					url: "./",
					type: "POST",
					data: {ajxreq:1, action: ajax_action, content_id: content_id, msisdn : phoneNo, current_type: currentType, password: password, subscribed: subscribed},
					datatype:'xml',
					async:false,
					beforeSend:function(){
						if(use_access_session_data){
							$('#laodwap').each(function(){$(this).unbind('click');});
							$('#laodweb').each(function(){$(this).unbind('click');});
						}
						else{
							$("#formtopurchase :button").attr('disabled', 'disabled');
						}
					},
					complete: function(req) {
						if(req.status == 200) {
							if(req.responseText.length > 0) {	
								var error_code = $(req.responseXML).find("response").find('error_code').text();
								try{
									var download_url = $(req.responseXML).find("response").find('download_url').text() + '?dwl';
								} catch (e) {
									var download_url = '';
								}
								try{
									var redirect_url = $(req.responseXML).find("response").find('redirectUrl').text();
								} catch (e) {
									var redirect_url = '';
								}
								if (error_code == 0) {
									if (download_url != '?dwl' && download_url != '') {
										ifrm = document.createElement("IFRAME");
										ifrm.setAttribute("src", download_url);
										ifrm.style.width = "0px";
										ifrm.style.height = "0px";	   
										document.getElementById('current_con').appendChild(ifrm);
									}
									disablePopup();
									if (redirect_url != ''){
										window.location.reload();
									}
								} else {
									$('#popStep2 span.error').text(error_msg[error_code]);
									$('#passw').val('');
								}
								if(use_access_session_data){
									$('#laodwap').click(function(){loadPopup(content_id, use_access_session_data)});
									$('#laodweb').click(function(){loadPopup(content_id, use_access_session_data)});
								}
								else{
									$("#formtopurchase :button").removeAttr('disabled');
								}
								
								return false;
							}
						}
					}
				};
			$.ajax(opts);
	}else{
		$('#popStep2 span.error').text(error_msg[102]);
	}
	return false;
}

function reloadCaptcha()
{
	var rand = Math.floor(Math.random()*100000000);
	$('#captcha-img').attr('src', '/modules/Captcha/index.php?w=125&h=40&r='+rand);
	$('#captcha_user').val('');
	
}

function checkAccessSessionData(){
	
//	var response = 0;
//	alert('check session');
	var opts = {
						url: "/access/",
						type: "POST",
						data: {ajxreq:1, action: 'check_sess'},
						datatype:'xml',
						async:false,
						complete: function(req) {
							 var response = $(req.responseXML).find("response").find('sess_access').text();
							 $("#sess_access").val(response);
						}
					};
		$.ajax(opts);
		
}