/**
main.js (1.1)
*/

var id	= 0;
var contact = 0;
var winecount = 0;
var winecountid = 1;
var pe;
var rand = Math.random(9999);

/*
----------------------------------
Core Functions
----------------------------------
*/

// Show AJAX loader
function showLoader(t) {
	$('#'+t).html('<img class="ajax-loader" src="views/ajax-loader.gif" />');
}

// Load HTML data
function getData(iAction, iTarget, iValue, iurl) {
	showLoader(iTarget);
	var pars = {
		'iAction': iAction,
		'iTarget': iTarget,
		'iValue': iValue,
		'rand': rand
	}
	
	// Do data req
	var resp;
	if(iTarget!='growl') {
		resp = $('#'+iTarget).load(iurl, pars);
	} else {
		resp = $.post(iurl, pars, function(d) { 
			if(d!='') $.jGrowl(d);
		});
	}
}

// Submit form, echo response
function submitform(iValue, iAction, iForm, iTarget, iurl, c, dType) {
	var resp;
	var pars = { 'iValue' : iValue, 'iAction' : iAction, 'rand' : rand }
	$('#'+iForm).ajaxSubmit({
		beforeSubmit: before_process('#'+iForm),
		clearForm: c,
		data: pars,
		dataType: dType,
		success: function(d) {
			if(dType=='json') {
				after_process_json(d, iForm, iTarget);
			} else {
				after_process(d, iForm, iTarget);
			}
		},
		url:	iurl,
		type: 	'post'
	});
	
}

// Process AJAX forms (form, extra parameters, clearForm [true/false])
function ajax_form(f, p, c) {
	var pars = (p!='') ? p : {}
	$(f).ajaxSubmit({
		beforeSubmit: before_process(f),
		clearForm: c,
		data: p,
		dataType: 	'json',
		success: function(d) {
			after_process(d,f);
		}
	});
	return false;
}

// Pre-process
function before_process(f) {
	var $theform = $(f);
	$theform.animate({ opacity: 0.5 }, 300);
}

// Post-process, HTML
function after_process(d, f, t) {
	var $theform 	= $('#'+f);
	var $thetarget 	= $('#'+t);
	
	// If no error, run script, else alert error
	if(t!='growl') {
		$thetarget.html(d);
	} else {
		$.jGrowl(d);
	}
	$theform.animate({ opacity: 1 }, 300);
	
}

// Post-process, JSON
function after_process_json(d, f, t) {
	var $theform 	= $('#'+f);
	var $thetarget 	= $('#'+t);
		
	// If no error, run script, else alert error
	if(!d.error) {
		$theform.find('#errors').empty();
		if(d.code!='') {
			eval(d.code);
		} else {
			$.jGrowl(d.msg);
		}
	} else {
		if(t!='growl') {
			$theform.find('#errors').html(d.error_msg);
		} else {
			$.jGrowl(d.error_msg);
		}
	}	
	$theform.animate({ opacity: 1 }, 300);
	
}

/*
----------------------------------
Language / Cookies
----------------------------------
*/

function createCookie(name, value, days) {
	$.cookie(name, value, { expires: days, path: '/' });
}

function readCookie(name) {
	return $.cookie(name);
}

function eraseCookie(name) {
	$.cookie(name, null, { expires: -1, path: '/' });
}
/*
----------------------------------
EDITOR SIDE
----------------------------------
*/

function initialize_editor() {
	getData('get_system_messages', 'ContactSummary', 0, 'views/editor_contact_holder.php');
	getData('get_system_messages', 'WineSummary', 0, 'views/editor_wine_holder.php');
	getData('get_system_messages', 'CostSummary', 0, 'views/editor_cost_summary.php');
}
function Load_Editor_Contact() {
	submitform(0, "profile", "vAll", "leftContent", "views/editor_contact_editor.php", false, 'html');
}
function submit_profile_update(){
	submitform(0, "profile_update", "vContact", "growl", "scripts/script_runner.php", false, 'json');
	
};
function update_profile_success(){
	submitform(0, "profile", "vContact", "ContactSummary", "views/editor_contact_holder.php", false, 'html');
};
function editor_wine(id){
 	submitform(id, "wine", "vAll", "leftContent", "views/editor_wine_editor.php", false, 'html');
};
function editor_submit_wine(id){
	submitform(id, "wine_update", "vWine", "growl", "scripts/script_runner.php", false, 'json');
};
function update_wine_success(id){
	getData('get_system_messages', 'WineSummary', 0, 'views/editor_wine_holder.php');
};

/*
----------------------------------
Sign Up / Profile
----------------------------------
*/

// initialize profile page
function initialize_profile() {
	getData('get_system_messages', 'leftContent', 0, 'views/contact_editor.php');
	
};


function submit_profile(){
	submitform(0, "profile", "vContact", "growl", "scripts/script_runner.php", false, 'json');
	
};
function submit_profile_success(){
	submitform(0, "profile", "vContact", "ContactSummary", "views/contact_holder.php", false, 'html');
	contact=1;
	Add_Wine();
};
function Load_Contact(){
	submitform(0, "profile", "vAll", "leftContent", "views/contact_editor.php", false, 'html');
};
function Add_Wine(){
		//ADD WINE PRESSED GET WINE FORM WITH ZERO ID
 		getData('get_system_messages', 'leftContent', 0, 'views/wine_editor.php');
 		//$('#WineSummary').append('<div id="wine_'+winecount+'" class="wine">hellow'+winecount+'</div>');
		//winecount++;
};
function edit_wine(id){
 	submitform(id, "wine", "vAll", "leftContent", "views/wine_editor.php", false, 'html');
};
function remove_wine(id){
 	$('#wine_'+id).remove();
	winecount--;
	getData('get_system_messages', 'CostSummary', winecount, 'views/cost_summary.php');
};
function submit_wine(id){
	submitform(id, "wine", "vWine", "growl", "scripts/script_runner.php", false, 'json');
};
function submit_wine_success(id){
	//NEW WINE
	if(id==0){
		$('#WineSummary').append('<div id="wine_'+winecountid+'" class="wine">wine</div>');
		submitform(winecountid, "wine", "vWine", "wine_"+winecountid, "views/wine_holder.php", false, 'html');
		winecountid++;
		winecount++;
		getData('get_system_messages', 'CostSummary', winecount, 'views/cost_summary.php');
	}else{
		submitform(id, "wine", "vWine", "wine_"+id, "views/wine_holder.php", false, 'html');
	}
	Add_Wine();
};

function login(){
	//alert("yo");
	submitform(0, "login", "vLogin", "growl", "scripts/script_runner.php", false, 'json');
};



function save_all(){
	//check if contact
	if(contact==0){
		$.jGrowl('<p>You must enter Contact Information</p>');
		return false;
	}
	if(winecount==0){
		$.jGrowl('<p>You must enter at least 1 wine</p>');
		return false;
	}
	nme=$('#contact').val();
	getData('get_system_messages', 'leftContent', nme, 'views/payment_editor.php');
}
function save_after_payment(){
	//MIGHT AS WELL CHECK AGAIN
	if(contact==0){
		$.jGrowl('<p>You must enter Contact Information</p>');
		return false;
	}
	if(winecount==0){
		$.jGrowl('<p>You must enter at least 1 wine</p>');
		return false;
	}
	submitform(0, "payment", "vPayment", "growl", "scripts/script_runner.php", false, 'json');
}
function submit_payment_success(){
	//transfer to right side
	submitform(0, "payment", "vPayment", "PaymentSummary", "views/payment_holder.php", false, 'html');
}
function finish_off_save(){
	submitform(0, "save_all", "vAll", "growl", "scripts/script_runner.php", false, 'json');
};
function thank_you(iValue){
	$('#rightContent').html('');
	getData('get_system_messages', 'leftContent', iValue, 'views/thank_you.php');
};
function send_email(email){
	emval=$('#emailreceipt').html();
	iVal=email+'@@@!!!'+emval;
	//alert(emval);
	getData('process_receipt', 'growl', iVal, 'scripts/script_runner.php');
	
};

function toggle_payments(iValue){
	if(iValue==0){
		//CREDIT CARD
		$('#chequeinfo').hide();
		$('#ccinfo').show();
	}else{
		$('#chequeinfo').show();
		$('#ccinfo').hide();
	}
};

/*
----------------------------------
Main Sections
----------------------------------
*/
function formatPhone(inputControl){
	var re= /\D/;

	// test for this format: (xxx)xxx-xxxx

	//var re2 = /^\({1}\d{3}\)\d{3}-\d{4}/; 

	// test for this format: xxx-xxx-xxxx

	var re2 = /^\d{3}-\d{3}-\d{4}/;



	var num=inputControl.value;



	var newNum;

 	if (num != "" && re2.test(num)!=true){

   		if (num != ""){

     		while (re.test(num)){

     			num = num.replace(re,"");

     		}

   		}

		if (num.length != 10){

    		alert('Please enter a 10 digit phone number');

    		return;

  		}else{

     		// for format (xxx)xxx-xxxx

     		//newNum = '(' + num.substring(0,3) + ')' + num.substring(3,6) + '-' + num.substring(6,10);

     		// for format xxx-xxx-xxxx

     		 newNum = num.substring(0,3) + '-' + num.substring(3,6) + '-' + num.substring(6,10);

     		inputControl.value=newNum;

     		return;

	 	}

   	}



}
 function IamWorth(inputControl) {

	 var iVal=inputControl.value;

	 var inputVal = iVal.replace("$","");

     inputControl.value=formatCurrency(inputVal,0);

 }

 function formatCurrency(strValue,cents)

 {

	strValue = strValue.toString().replace(/\$|\,/g,'');

	if (isNaN(parseFloat(strValue))) {

		strValue=0;

    }

	dblValue = parseFloat(strValue);



	blnSign = (dblValue == (dblValue = Math.abs(dblValue)));

	dblValue = Math.floor(dblValue*100+0.50000000001);

	intCents = dblValue%100;

	strCents = intCents.toString();

	dblValue = Math.floor(dblValue/100).toString();

	if(intCents<10)

		strCents = "0" + strCents;

	for (var i = 0; i < Math.floor((dblValue.length-(1+i))/3); i++)

		dblValue = dblValue.substring(0,dblValue.length-(4*i+3))+','+

		dblValue.substring(dblValue.length-(4*i+3));

	//return (((blnSign)?'':'-') + '$' + dblValue + '.' + strCents);

	strCents='.' + strCents;

	if(cents>0){

		strCents='';

	}

	return (((blnSign)?'':'-') + dblValue + strCents);

}

		
/*============================================================================*/



/*



This routine checks the credit card number. The following checks are made:



1. A number has been provided

2. The number is a right length for the card

3. The number has an appropriate prefix for the card

4. The number has a valid modulus 10 number check digit if required



If the validation fails an error is reported.



The structure of credit card formats was gleaned from a variety of sources on 

the web, although the best is probably on Wikepedia ("Credit card number"):



  http://en.wikipedia.org/wiki/Credit_card_number



Parameters:

            cardnumber           number on the card

            cardname             name of card as defined in the card list below



Author:     John Gardner

Date:       1st November 2003

Updated:    26th Feb. 2005      Additional cards added by request

Updated:    27th Nov. 2006      Additional cards added from Wikipedia

Updated:    18th Jan. 2008      Additional cards added from Wikipedia

Updated:    26th Nov. 2008      Maestro cards extended



*/



/*

   If a credit card number is invalid, an error reason is loaded into the 

   global ccErrorNo variable. This can be be used to index into the global error  

   string array to report the reason to the user if required:

   

   e.g. if (!checkCreditCard (number, name) alert (ccErrors(ccErrorNo);

*/



var ccErrorNo = 0;

var ccErrors = new Array ()



ccErrors [0] = "Unknown card type";

ccErrors [1] = "No card number provided";

ccErrors [2] = "Credit card number is in invalid format";

ccErrors [3] = "Credit card number is invalid";

ccErrors [4] = "Credit card number has an inappropriate number of digits";

function validateCreditCard(inputControl){
		cardnumber=$('#ccnum').val();
		cardnam=$('#cardtype').val();
		//alert (cardnumber+'-'+cardnam);
		if(cardnumber!=''&&cardnam!=''){
			if (!checkCreditCard (cardnumber, cardnam)){
				 $.jGrowl(ccErrors[ccErrorNo]);
			}
		}
}

function checkCreditCard (cardnumber, cardname) {

     

  // Array to hold the permitted card characteristics

  var cards = new Array();



  // Define the cards we support. You may add addtional card types.

  

  //  Name:      As in the selection box of the form - must be same as user's

  //  Length:    List of possible valid lengths of the card number for the card

  //  prefixes:  List of possible prefixes for the card

  //  checkdigit Boolean to say whether there is a check digit

  

  cards [0] = {name: "Visa", 

               length: "13,16", 

               prefixes: "4",

               checkdigit: true};

  cards [1] = {name: "MasterCard", 

               length: "16", 

               prefixes: "51,52,53,54,55",

               checkdigit: true};

  cards [2] = {name: "DinersClub", 

               length: "14,16", 

               prefixes: "36,54,55",

               checkdigit: true};

  cards [3] = {name: "CarteBlanche", 

               length: "14", 

               prefixes: "300,301,302,303,304,305",

               checkdigit: true};

  cards [4] = {name: "AmEx", 

               length: "15", 

               prefixes: "34,37",

               checkdigit: true};

  cards [5] = {name: "Discover", 

               length: "16", 

               prefixes: "6011,622,64,65",

               checkdigit: true};

  cards [6] = {name: "JCB", 

               length: "16", 

               prefixes: "35",

               checkdigit: true};

  cards [7] = {name: "enRoute", 

               length: "15", 

               prefixes: "2014,2149",

               checkdigit: true};

  cards [8] = {name: "Solo", 

               length: "16,18,19", 

               prefixes: "6334, 6767",

               checkdigit: true};

  cards [9] = {name: "Switch", 

               length: "16,18,19", 

               prefixes: "4903,4905,4911,4936,564182,633110,6333,6759",

               checkdigit: true};

  cards [10] = {name: "Maestro", 

               length: "12,13,14,15,16,18,19", 

               prefixes: "5018,5020,5038,6304,6759,6761",

               checkdigit: true};

  cards [11] = {name: "VisaElectron", 

               length: "16", 

               prefixes: "417500,4917,4913,4508,4844",

               checkdigit: true};

               

  // Establish card type

  var cardType = -1;

  for (var i=0; i<cards.length; i++) {



    // See if it is this card (ignoring the case of the string)

    if (cardname.toLowerCase () == cards[i].name.toLowerCase()) {

      cardType = i;

      break;

    }

  }

  

  // If card type not found, report an error

  if (cardType == -1) {

     ccErrorNo = 0;

     return false; 

  }

   

  // Ensure that the user has provided a credit card number

  if (cardnumber.length == 0)  {

     ccErrorNo = 1;

     return false; 

  }

    

  // Now remove any spaces from the credit card number

  cardnumber = cardnumber.replace (/\s/g, "");

  

  // Check that the number is numeric

  var cardNo = cardnumber

  var cardexp = /^[0-9]{13,19}$/;

  if (!cardexp.exec(cardNo))  {

     ccErrorNo = 2;

     return false; 

  }

       

  // Now check the modulus 10 check digit - if required

  if (cards[cardType].checkdigit) {

    var checksum = 0;                                  // running checksum total

    var mychar = "";                                   // next char to process

    var j = 1;                                         // takes value of 1 or 2

  

    // Process each digit one by one starting at the right

    var calc;

    for (i = cardNo.length - 1; i >= 0; i--) {

    

      // Extract the next digit and multiply by 1 or 2 on alternative digits.

      calc = Number(cardNo.charAt(i)) * j;

    

      // If the result is in two digits add 1 to the checksum total

      if (calc > 9) {

        checksum = checksum + 1;

        calc = calc - 10;

      }

    

      // Add the units element to the checksum total

      checksum = checksum + calc;

    

      // Switch the value of j

      if (j ==1) {j = 2} else {j = 1};

    } 

  

    // All done - if checksum is divisible by 10, it is a valid modulus 10.

    // If not, report an error.

    if (checksum % 10 != 0)  {

     ccErrorNo = 3;

     return false; 

    }

  }  



  // The following are the card-specific checks we undertake.

  var LengthValid = false;

  var PrefixValid = false; 

  var undefined; 



  // We use these for holding the valid lengths and prefixes of a card type

  var prefix = new Array ();

  var lengths = new Array ();

    

  // Load an array with the valid prefixes for this card

  prefix = cards[cardType].prefixes.split(",");

      

  // Now see if any of them match what we have in the card number

  for (i=0; i<prefix.length; i++) {

    var exp = new RegExp ("^" + prefix[i]);

    if (exp.test (cardNo)) PrefixValid = true;

  }

      

  // If it isn't a valid prefix there's no point at looking at the length

  if (!PrefixValid) {

     ccErrorNo = 3;

     return false; 

  }

    

  // See if the length is valid for this card

  lengths = cards[cardType].length.split(",");

  for (j=0; j<lengths.length; j++) {

    if (cardNo.length == lengths[j]) LengthValid = true;

  }

  

  // See if all is OK by seeing if the length was valid. We only check the 

  // length if all else was hunky dory.

  if (!LengthValid) {

     ccErrorNo = 4;

     return false; 

  };   

  

  // The credit card is in the required format.

  return true;

}



/*============================================================================*/
