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 content_name = $('#content_name').val();
	var content_artist = $('#content_artist').val();
	var content_kind = $('#content_kind').val();
	var content_price = $('#content_price').val();
	
	
//	var session_access =  $("#sess_access").val();
	
//	if(session_access==1 && content_id.length > 0){
//	
//		submitPassword(content_id, true);
//		
//		return 0;
//	}
//	else{

	
// -------------------

			var opts = {
					url: commonconfig["baseUrlHttp"] + "/ajax/ppdload/",
					type: "POST",
					data: {content_id: content_id, purchase_type: currentType, content_name: content_name, content_artist: content_artist, content_kind: content_kind, content_price: content_price},
					async:false,
					complete: function(req) {
						if(req.status == 200) {
							if(req.responseText.length > 0) {	
									
								$('#popupContact').html(req.responseText);
								$('#popStep1').css('display', 'block');
								$('#popStep2').css('display', 'none');
								$('#numero').val('');
								$('#passw').val('');
								return false;
							}
						}
					}
				};
			$.ajax(opts);


// -------------------	

	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(' + commonconfig["imgPath"] + 'pop_up_ie6.gif)');
        } else {
          $("#popupContact").fadeIn("fast").css('background-image','url(' + commonconfig["imgPath"] + '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(type, content_id)
{
	var msisdn = parseInt($('#numero').val());
	var capId = $('#capId').val();
	var security_code = $('#security_code').val();
	var currentType = type;
	
	if (content_id < 1) {
		alert('System error!');
		return false;
	}
	if (msisdn > 1) {	
			phoneNo = msisdn;
			var opts = {
					url: commonconfig["baseUrlHttp"] + "/ajax/ppdnum/",
					type: "POST",
					data: {content_id: content_id, msisdn : msisdn, purchase_type: currentType, capId: capId, security_code: security_code},
					async:false,
					dataType: 'json',
					complete: function(req) {
						if(req.status == 200) {
							if(req.responseText.length > 0) {	
								if(req.responseText.length > 0) {
								var json = eval('(' + req.responseText+ ')');
								var errorCode = parseInt(json.errorCode);
								
								if (errorCode == 0) {
									$('#popStep1').css('display', 'none');
									$('#popStep2').css('display', 'block');
								}
								else if(errorCode == 1){
								//	$('#popStep1').css('display', 'none');
								//	$('#popStep2').css('display', 'none');
								//	$('#popupContact').css('display', 'none');
									disablePopup();	
								}
								else{
									loadPopup(type, content_id);
									$('#popStep1 span.error').text(error_msg[errorCode]);
								}
								
	//							return false;
								}
							}
						}
					}
				};
			$.ajax(opts);
	}else{
		loadPopup(type, content_id);
		$('#popStep1 span.error').text(error_msg[101]);
	}
	return false;
}

function submitPassword(type, content_id) 
{
	
	var password = $('#passw').val();
	$('#purchase-wrapper').empty();

	if (content_id < 1) {
		alert('System error!');
		return false;
	}
	if (password.length > 1) {	
			var opts = {
					url: commonconfig["baseUrlHttp"] + "/ajax/ppdpwd/",
					type: "POST",
					data: {content_id: content_id, msisdn : phoneNo, current_type: type, password: password},
					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 json = eval('(' + req.responseText+ ')');
								
								var errorCode = parseInt(json.errorCode);
							
								// Download is now done after redirection, on content page.
								
								try{
									var download_url = json.url + '?dwl=1';
								} catch (e) {
									var download_url = '';
								}
								
								try{
									var redirect_url = json.redirect_url;
								} catch (e) {
									var redirect_url = '';
								}
							
								if (errorCode == 0 || errorCode == 51) {
									// Download is now done after redirection, on content page.
									
									disablePopup();
									
									if (redirect_url!= 'undefined' && redirect_url != ''){
										window.location = redirect_url;
										return false;
									}
									
									if (type == 'web' || type == 'WEB') {
										if (download_url != '?dwl=1' && download_url != '') {
											ifrm = document.createElement("IFRAME");
											ifrm.setAttribute("src", download_url);
											ifrm.style.width = "0px";
											ifrm.style.height = "0px";
											
											document.getElementById('purchase-wrapper').appendChild(ifrm);
										//	$('#purchase_msg_web').css('display', 'block');
										}
									}
									else{
									//	$('#purchase_msg_wap').css('display', 'block');
									}
									
									return false;
//									
								} else if(errorCode == 50 || errorCode==901){
									disablePopup();
									alert(error_msg[errorCode]);
									return false;
									
								}else{
								
									$('#popStep2 span.error').text(error_msg[errorCode]);
									$('#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 ppdPurchase(download_url, type) {
	if (type == 'web' || type == 'WEB') {
		if (download_url != '?dwl=1' && download_url != '') {
			ifrm = document.createElement("IFRAME");
			ifrm.setAttribute("src", download_url);
			ifrm.style.width = "0px";
			ifrm.style.height = "0px";
			
			document.getElementById('purchase-wrapper').appendChild(ifrm);
		}
	}
}

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);
		
}
