// JavaScript Document
$(document).ready(function(){
	$("#JSWarning").css('display','none');
	$("#buyCart").click(buy);
	$("#flag1").click(showCountrySelectDialog);
	$('#changeCountry').click(showCountrySelectDialog);
	$('#country_').click(showCountrySelectDialog);
	$('#see_cart').click(buy);
	$("#lostPass").click(lostPass);
	
	$("#goChangePass").bind("click", function(e){
		$("#goChangePass").css( 'display', 'none' );
		$("#goChangeStdBy").css( 'display', 'block' );
		email = $("#cpMail").val();
		$.ajax({
			url: document_root+ 'customer/pForgotPasswordAjax.php',
			type: "POST",
			data: { 'email': email},
			success: function(success){
				if(success == 'ok'){
					alert(getMessage('checkMail'));
					$("#dialogChangePass").dialog('close');
				}else{
					$("#registerText").css( 'display', 'block' );
				}
				$("#goChangePass").css( 'display', 'block' );
				$("#goChangeStdBy").css( 'display', 'none' );
			}
		});
	});
	
	$("#dialogCountry").dialog({
		bgiframe: true,
		autoOpen: false,
		width: 900,
		height: 300,
		modal: true,
		buttons: {
			'cancelButton' : function() {
				$('#alerts_dialog').css('display','none');
				$(this).dialog('close');
			}
		  }
	});
	
	$("#dialogChangePass").dialog({
		bgiframe: true,
		autoOpen: false,
		width: 600,
		height: 250,
		modal: true,
		buttons: {
			'cancelButton': function() {
				$('#alerts_dialog').css('display','none');
				$(this).dialog('close');
			}
		  }
	});
	
	$("#dialogHeaderLogin").dialog({
		bgiframe: true,
		autoOpen: false,
		width: 900,
		height: 300,
		modal: true,
		buttons: {
			'cancelButton': function() {
				$('#alerts_dialog').css('display','none');
				$(this).dialog('close');
			}
		  }
	});
	
	$("#dialogLoginRenew").dialog({
		bgiframe: true,
		autoOpen: false,
		width: 900,
		height: 350,
		modal: true,
		buttons: {
			'cancelButton': function() {
				$('#alerts_dialog').css('display','none');
				$(this).dialog('close');
			}
		  }
	});
	
	$("#dialogGeneralConditions").dialog({
		bgiframe: true,
		autoOpen: false,
		width: 900,
		height: 300,
		modal: true,
		buttons: {
			'cancelButton': function() {
				$('#alerts_dialog').css('display','none');
				$(this).dialog('close');
			}
		  }
	});
	
	/*VALIDATION SECTION*/
    $("#frmHeaderLogin").validate({
    	errorLabelContainer: "#headerErrorsContainer",
    	wrapper: "li",
    	onfocusout: false,
		onkeyup: false,
		rules: {
    		txtUsername: {
				required: true
			},
			txtPassword: {
				required: true
			}
		},
    	submitHandler: function(form) {
			show_ajax_loader();
			var email = form.txtUsername.value;
			var password = form.txtPassword.value;
			$.ajax({
				url: document_root+ 'pLoginUserOrCustomer.php',
				type: "POST",
				data: { 'email': email, 'password': password},
				success: function(actionToDo){
					actionToDo = jQuery.trim(actionToDo);
					parts = actionToDo.split("%%%");
					actionCommand = parts[0];
					
					$("#txtUsername").val('');
					$("#txtPassword").val('');
					
					switch(actionCommand){
						case 'error'://LOGIN DATA INCORRECT
							errorName = parts[1];
							switch(errorName){
								case 'badCustomerPassword':
								case 'badUserPassword':
									errorMsg = getMessage('incorrectPassword');
									break;
								case 'badLogin':
									errorMsg = getMessage('incorrectUsername');
									break;
							}
							$("#headerErrorsContainerAjaxed").html(errorMsg);
							$("#dialogHeaderLogin").dialog('open');
							hide_ajax_loader();
							break;
						case 'renew'://LOGIN DATA OK - RENEW PASSWORD BEFORE SIGNING IN
							$("#customerSerial").val(parts[1]);
							$("#dialogLoginRenew").dialog('open');
							hide_ajax_loader();
							break;
						case 'gofwd'://GO FORWARD TO THE SYSTEM AND AUTO LOGIN
							$("#txtSystemUser").val(email);
							$("#txtSystemPassword").val(parts[1]);//MD5
							$("#systemToken").val(parts[2]);
							$("#externalSystemLogin").submit();
							break;
						case 'success'://USER LOGIN CORRECT - GO TO CUSTOMER MAIN PAGE
							window.location = parts[1];
							break;
						default://ERROR PROCESSING DATA - UNKNOWN ANSWER
							alert(getMessage('genericError'));
							hide_ajax_loader();
							break;
					}
				}
			});
		}
	});
    
    $("#frmLoginRenew").validate({
    	errorLabelContainer: "#headerErrorsContainerLoginRenew",
    	wrapper: "li",
    	onfocusout: false,
		onkeyup: false,
		rules: {
    	txtOldPassword: {
				required: true,
				remote: {
					url: document_root+"rpc/remoteValidation/checkOldCustomerPassword.rpc",
					type: "POST",
					data: {
    				  txtOldPassword: function() {
						return $("#txtOldPassword").val();
					  },
					  customerSerial: function() {
						  return $("#customerSerial").val();
					  }
					}
                }
			},
			txtPasswordRenew: {
				required: true,
				minlength: {
					param:6
				},
				notEqualTo: "#txtOldPassword",
				remote: {
					url: document_root+"rpc/remoteValidation/checkAlphanumericPassword.rpc",
					type: "POST"
                }
			},
			txtRePasswordRenew: {
				required: true,
				equalTo:  {
					param:"#txtPasswordRenew"
				}
			}
		},
		messages: {
			txtOldPassword: {
				remote: getMessage('currentPasswordWrong')
			},
			txtPasswordRenew: {
				minlength: getMessage('passwordMinLength'),
				notEqualTo: getMessage('passwordNotEqual'),
				remote: getMessage('passwordAlphanumeric')
			},
			txtRePasswordRenew: {
                equalTo: getMessage('passwordConfirmationFailed')
			}
   		}
	});
    
    $("#btnSendLoginRenew").bind("click", function(e){
    	$("#frmLoginRenew").submit();
    });
    /*END VALIDATION*/
    
    $("#txtPassword").keypress(function(e){
    	if (e.keyCode == 13) {
    		if($("#frmHeaderLogin").valid()){
        		$("#frmHeaderLogin").submit();
            }else{
            	$("#dialogHeaderLogin").dialog('open');
            }
  	  	}
    });
    
    $("#buttonEnter").bind("click", function(e){
    	if($("#frmHeaderLogin").valid()){
    		$("#frmHeaderLogin").submit();
        }else{
        	$("#dialogHeaderLogin").dialog('open');
        }
    });
    
    //DIALOG MODAL PANEL TEXTS:
    $(".cancelButton").each(function(e){
    	$(this).html(getMessage('cancelButton'));
    });
});

function showCountrySelectDialog(){
	if(!confirm(getMessage('changeLangConfirm'))){
		return false;
	}
	show_ajax_loader();
	$.ajax({
		url: document_root+ 'pLoadCountries.php',
		type: "POST",
		success: function(webCountries){
			$("#mainCountryBox").html(webCountries);
			$(".[id^='selection_country_']").each( function(e){
				$(this).bind("click", function(e){
					show_ajax_loader();
					countryCode = $(this).attr('id').replace("selection_country_","");
					$.ajax({
						url: document_root+ 'pChangeCountry.php',
						type: "POST",
						data: { 'countryCode': countryCode},
						success: function(language){
							systemLanguage = language;//Update global language var
							$("#dialogCountry").dialog('close');
							temporal = window.location;
							window.location = document_root + 'index';
						}
					});
				});
			});
			$("#dialogCountry").dialog('open');
			hide_ajax_loader();
		}
	});
}

function buy(){
	window.location = 'http://www.planet-assist.net/estimatorFull';
	//estimatorMasterRedirect();
}

function lostPass(){
	show_ajax_loader();
	$("#cpMail").val('');
	$("#registerText").css( 'display', 'none' );
	$("#dialogChangePass").dialog('open');
	hide_ajax_loader();
}

function show_ajax_loader(){
	$("#loader").css( 'display', 'block' );
}

function hide_ajax_loader(){
	$("#loader").css( 'display', 'none' );
}
