// JavaScript Document
function explode (delimiter, string, limit) {
    // Splits a string on string separator and return array of components. If limit is positive only limit number of components is returned. If limit is negative all components except the last abs(limit) are returned.
    //
    // version: 909.322
    // discuss at: http://phpjs.org/functions/explode    // +     original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     improved by: kenneth
    // +     improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     improved by: d3x
    // +     bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)    // *     example 1: explode(' ', 'Kevin van Zonneveld');
    // *     returns 1: {0: 'Kevin', 1: 'van', 2: 'Zonneveld'}
    // *     example 2: explode('=', 'a=bc=d', 2);
    // *     returns 2: ['a', 'bc=d']
     var emptyArray = {0: ''};

    // third argument is not required
    if ( arguments.length < 2 ||
        typeof arguments[0] == 'undefined' ||        typeof arguments[1] == 'undefined' )
    {
        return null;
    }
     if ( delimiter === '' ||
        delimiter === false ||
        delimiter === null )
    {
        return false;}

    if ( typeof delimiter == 'function' ||
        typeof delimiter == 'object' ||
        typeof string == 'function' ||        typeof string == 'object' )
    {
        return emptyArray;
    }
     if ( delimiter === true ) {
        delimiter = '1';
    }

    if (!limit) {return string.toString().split(delimiter.toString());
    } else {
        // support for limit argument
        var splitted = string.toString().split(delimiter.toString());
        var partA = splitted.splice(0, limit - 1);var partB = splitted.join(delimiter.toString());
        partA.push(partB);
        return partA;
    }
}
function implode (glue, pieces) {
    // Joins array elements placing glue string between items and return one string
    //
    // version: 911.718
    // discuss at: http://phpjs.org/functions/implode    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Waldo Malqui Silva
    // +   improved by: Itsacon (http://www.itsacon.net/)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: implode(' ', ['Kevin', 'van', 'Zonneveld']);    // *     returns 1: 'Kevin van Zonneveld'
    // *     example 2: implode(' ', {first:'Kevin', last: 'van Zonneveld'});
    // *     returns 2: 'Kevin van Zonneveld'

    var i = '', retVal='', tGlue='';

    if (arguments.length === 1) {
        pieces = glue;
        glue = '';
    }
    if (typeof(pieces) === 'object') {
        if (pieces instanceof Array) {
            return pieces.join(glue);
        }
        else {
            for (i in pieces) {
                retVal += tGlue + pieces[i];
                tGlue = glue;
            }
            return retVal;
        }
    } else {
        return pieces;
    }
}

/***********************************************
* @Name: array_push
* @Description: Adds an element to an specific array at the end of it.
* @Params: arrayGroup: array stack
*          element: the new element to be added
* @Returns: The new Array
***********************************************/
function array_push ( arrayGroup, element ) {
    var size=arrayGroup.length;
    arrayGroup[size]=element;
    return arrayGroup;
}

/***********************************************
* @Name: setDefaultCalendar
* @Description: sets a datepicker for an specific date textBox, it also calls
*               formatDate() function that is used to control the insertion
*               of a correct date in the textBox.
* @Params:  object: textBox that is going to aply the datepicker and formatDate()
*           min: the min date that is going to accept the calendar
*           max: the max date that is going to accept the calendar
*           defDate: the default date used to initialize the calendar
***********************************************/
function setDefaultCalendar(object,min,max,defDate){
    object.datepicker({
        showOn: 'button',
        buttonImage: document_root+'img/calendar.gif',
        buttonImageOnly: true,
        dateFormat: 'dd/mm/yy'
    });
    object.datepicker('option', {
            dateFormat: 'dd/mm/yy',
            date: object.val(),
            current: object.val(),
            starts: 1,
            position: 'r',
            defaultDate: defDate,
            maxDate: max,
            minDate: min,
            changeMonth: true,
            changeYear: true,
            onBeforeShow: function(){
                    object.DatePickerSetDate(object.val(), true);
            },
            onChange: function(formated, dates){
                    object.val(formated);

            }
    });

    object.keyup(function(){$(this).val(formatDate($(this).val()))});
}

/***********************************************
* @Name: setDefaultCalendar
* @Description: checks if a value is numeric
* @Params:  value
* @Returns: false if it isn't numeric
*           true if it is numeric
***********************************************/
function IsNumeric(value){
    var log=value.length;
    var sw="S";
    for (x=0; x<log; x++) {
        v1=value.substr(x,1);
        v2 = parseInt(v1);
        if (isNaN(v2)) {
            sw= "N";
        }
    }
    if (sw=="S") {
        return true;
    } else {
        return false;
    }
}

/***********************************************
* @Name: setDefaultCalendar
* @Description: function used to control the insertion
*               of a correct date in the textBox in an specific format 'dd/mm/yyyy'.
* @Params:  date: String going to be checked and modified if necesary
* @Returns: date: The modified String
***********************************************/
function formatDate(date){
    var firstlap=false;
    var secondlap=false;
    var date_lng = date.length;
    var day;
    var month;
    var year;
    if ((date_lng>=2) && (firstlap==false)) {
        day=date.substr(0,2);
        if ((IsNumeric(day)==true) && (day<=31) && (day!="00")) {
            date=date.substr(0,2)+"/"+date.substr(3,7);firstlap=true;
        }
        else {
            date="";firstlap=false;
        }
    }else{
        day=date.substr(0,1);
        if (!IsNumeric(day)){
            date="";
        }
        if ((date_lng<=2) && (firstlap=true)) {
            date=date.substr(0,1);firstlap=false;
        }
    }
    if ((date_lng>=5) && (secondlap==false)){
        month=date.substr(3,2);
        if ((IsNumeric(month)==true) &&(month<=12) && (month!="00")) {
            date=date.substr(0,5)+"/"+date.substr(6,4);secondlap=true;
        }else {
            date=date.substr(0,3);;secondlap=false;
        }
    }
    else {
        if ((date_lng<=5) && (secondlap=true)) {
            date=date.substr(0,4);secondlap=false;
        }
    }
    if (date_lng>=7){
        year=date.substr(6,4);
        if (IsNumeric(year)==false) {
            date=date.substr(0,6);
        }
        else {
            if (date_lng==10){
                if ((year==0) || (year<1900) || (year>2100)) {
                    date=date.substr(0,6);
                }
            }
        }
    }
    if (date_lng>=10){
        date=date.substr(0,10);
        day=date.substr(0,2);
        month=date.substr(3,2);
        year=date.substr(6,4);
        if ( (year%4 != 0) && (month ==02) && (day > 28) ) {
            date=date.substr(0,2)+"/";
        }
        if ((month ==02) && (day > 29) ) {
            date=date.substr(0,2)+"/";
        }
    }
    return (date);
}
        /***********************************************
	* function parseDate
	@Name: parseDate
	@Description: Parses a string in format date dd/mm/YYYY to a date
	@Params:
         *       str:string to be parsed
	@Returns: Date object.
        used mostly on dayDiff function
	***********************************************/
function parseDate(str) {
    var mdy = str.split('/')
    return new Date(mdy[2], mdy[1]-1, mdy[0]);
}
        /***********************************************
	* function dayDiff
	@Name: dayDiff
	@Description: get the days between to dates
	@Params:
         *       first:lower date string format dd/mm/YYYY
         *       second: higher date string format dd/mm/YYYY
	@Returns: int: days between
	***********************************************/
function dayDiff(first, second) {
    var date1=parseDate(first);
    var date2=parseDate(second);
    return ((date2-date1)/(1000*60*60*24))+1;
}

/***********************************************
@Name: dateFormat
@Description: Sets date format from mm/dd/YYYY to dd/mm/YYYY
@Params: Date String
@Returns: Formated Date
***********************************************/
function dateFormat(date){
	var formatDate=date.charAt(3)+'';
	for(var i=4;i<6;i++){
		formatDate+=date.charAt(i);
	}
	for(var i=0;i<3;i++){
		formatDate+=date.charAt(i);
	}
	for(var i=6;i<date.length;i++){
		formatDate+=date.charAt(i);
	}
	return formatDate;
}

function strtolower (str) {
    // Makes a string lowercase
    //
    // version: 909.322
    // discuss at: http://phpjs.org/functions/strtolower    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Onno Marsman
    // *     example 1: strtolower('Kevin van Zonneveld');
    // *     returns 1: 'kevin van zonneveld'
    return (str+'').toLowerCase();
}

function ucwords(str) {
    // Uppercase the first character of every word in a string
    //
    // version: 1001.2911
    // discuss at: http://phpjs.org/functions/ucwords    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Waldo Malqui Silva
    // +   bugfixed by: Onno Marsman
    // +   improved by: Robin
    // *     example 1: ucwords('kevin van zonneveld');    // *     returns 1: 'Kevin Van Zonneveld'
    // *     example 2: ucwords('HELLO WORLD');
    // *     returns 2: 'HELLO WORLD'
    return (str + '').replace(/^(.)|\s(.)/g, function ($1) {
        return $1.toUpperCase();});
}

function evaluateAlerts(){
		$.ajax({
				url: document_root+"rpc/alerts/checkUserAlerts.rpc",
				type: "post",
				data: ({}),
				success: function(data) {
					if(data=='false'){
						$('#user_alerts_container').css('display','none');
					}else{
						text ='('+data+')';
						if(data>1)
							text+=' Alertas';
						else
							text+=' Alerta';
						$('#user_alerts_number').html(text);
						$('#user_alerts_container').css('display','block');
					}

				}
		});
}

function calcDaysBetween($startDate, $endDate,changeSource){
	$.ajax({
		url: document_root+ 'estimator/getDaysDiffAjax.php',
		type: "POST",
		async: false,
		data: { 'beginDate': $startDate,'endDate': $endDate},
		success: function(days){
			if(days<0){
				alert(getMessage('departureDateBeforeArrival'));
				$('#daysDiff').html('0');
				if(changeSource == 1){
					$('#txtBeginDate').val('');
				}else{
					$('#txtEndDate').val('');
				}
			}else{
				$('#daysDiff').html(days);
			}
		}
	});
}

function saveSessionVariable($name, $value){
	$.ajax({
		url: document_root+ 'saveSessionVariableAjax.php',
		type: "POST",
		async: false,
		data: { 'name': $name,'value': $value},
		success: function(okString){
			return okString;
		}
	});
}

function estimatorMasterRedirect(){
	$.ajax({
		url: document_root+ 'customer/pCheckCustomerLoggedAndCartEmptyAjax.php',
		type: "POST",
		success: function(information){
			information = jQuery.trim(information);
			parts = information.split("%S%");
			if(parts[1] == '1'){
				pageNum = 3;
			}else{
				pageNum = '';
			}
			if(parts[0] == '1'){
				window.location = document_root + 'customer/estimatorCustomer/0/'+pageNum;
			}else{
				window.location = document_root + 'estimatorFull/'+pageNum;
			}
		}
	});
}

/*
 * MOD10 'LUTH' ALGORITHM JAVASCRIPT VALIDATION FUNCTION
 * TAKEN AND MODIFIED FROM THE FOLLOWING URL:
 * https://www.internetsecure.com/merchants/Mod10.html
 */
function Mod10(ccNumb) { //v2.0
	var valid = "0123456789"
	var len = ccNumb.length;
	var bNum = true;
	var iCCN = ccNumb;
	var sCCN = ccNumb.toString();
	var iCCN;
	var iTotal = 0;
	var bResult = false;
	var digit;
	var temp;
	
	iCCN = sCCN.replace (/^\s+|\s+$/g,'');	// strip spaces
	for (var j=0; j<len; j++) {
		temp = "" + iCCN.substring(j, j+1);
	
	if (valid.indexOf(temp) == "-1") bNum = false;}
	if(!bNum){alert("Not a Number");}
	   
	iCCN = parseInt(iCCN);
		
	if(len == 0){ /* nothing, field is blank */ 
		bResult = true;
	}else{
		if(len >= 15){		//15 or 16 for Amex or V/MC
			for(var i=len;i>0;i--){
				digit = "digit" + i;
				calc = parseInt(iCCN) % 10;	//right most digit
				calc = parseInt(calc);
				iTotal += calc;		
				//parseInt(cardnum.charAt(count))i:\t" + calc.toString() + " x 2 = " + (calc *2) +" : " + calc2 + "\n";
				i--;
				digit = "digit" + i;
				iCCN = iCCN / 10; 	// subtracts right most digit from ccNum
				calc = parseInt(iCCN) % 10 ;	// step 1 double every other digit
				calc2 = calc *2;
				
				switch(calc2){
					case 10: calc2 = 1; break;	//5*2=10 & 1+0 = 1
					case 12: calc2 = 3; break;	//6*2=12 & 1+2 = 3
					case 14: calc2 = 5; break;	//7*2=14 & 1+4 = 5
					case 16: calc2 = 7; break;	//8*2=16 & 1+6 = 7
					case 18: calc2 = 9; break;	//9*2=18 & 1+8 = 9
					default: calc2 = calc2; 		//4*2= 8 &   8 = 8  -same for all lower numbers
				}
				iCCN = iCCN / 10; 	// subtracts right most digit from ccNum
				iTotal += calc2;
			}
			if ((iTotal%10)==0){
				//document.calculator.results.value = "Yes"; 
				bResult = true;
	 		}else{
				//document.calculator.results.value = "No"; 
				bResult = false;
			}
		}
	}
	return bResult;
}

function loadProductGNCFiles(prodId){
	redirectMe = false;
	redirectTo = '';
	$.ajax({
		url: document_root+ 'loadProductGNCFiles.php',
		type: "POST",
		data: { 'product_id': prodId},
		async: false,
		success: function(messageContent){
			information = jQuery.trim(messageContent);
			parts = information.split("%%%");
			if(parts[0] == '1'){
				redirectMe = true;
				redirectTo = parts[1];
			}else if(parts[0] > '1'){
				$("#generalConditionsListed").html(parts[1]);
				$("#dialogGeneralConditions").dialog('open');
				hide_ajax_loader();
			}else{
				alert(getMessage('noGenCondFound'));
			}
		}
	});
	if(redirectMe){
		window.open(redirectTo, 'open_window');
	}
}

//FUNCTION TO RETRIEVE LANGUAGE SPECIFIC MESSAGES:
function getMessage(id){
	if (typeof systemLanguage == "undefined"){
		$.ajax({
			url: document_root+ 'retrieveWebSystemLanguageCodeAjax.php',
			type: "POST",
			async: false,
			success: function(langCode){
				systemLanguage = langCode;
			}
		});
	}
	return MESSAGES[systemLanguage][id];
}

//USED ON VALIDATIONS FOR EXTRAS ON SALES AND PHONE SALES
function checkAgeValidations(valueId, valueComparator, type){
	checkThis = $(valueId).html();
	if(checkThis != valueComparator){
		return true;
	}
	isOld = true;
	isOld = checkAgeValidationsSub($('#txtBirthdayCustomer').val(), type);
	if(!isOld && valueComparator != 'ADULTS' && valueComparator != 'CHILDREN'){
		return false;
	}else{
		isOld = true;
	}
	$("[id^='birthdayExtra_']").each( function(e){
		myVal = $(this).val();
		isOld = checkAgeValidationsSub(myVal, type);
		if(!isOld){ 
			return false;
		}
	});
	return isOld;
}

function checkAgeValidationsSub(myVal, type){
	if(myVal == ''){
		return true;
	}
	isOld = true;
	$.ajax({
		  url: document_root+ checkProductValidatorURL,
		  type: "POST",
		  data: { 'birthDate': myVal, type: type},
		  async: false,
		  success: function(response){
			  if(response == 'true'){
				  isOld = true;
			  }else{
				  isOld = false;
			  }
		  }
	});
	return isOld;
}
