/*!
 * Script Adapted by Elehost Web Design Inc.
 * Date: 26-05-2010 
 */
 
/*!
* Focus to first form field
* Function : body_onload
* Param    : NA
* Return   : NA
*/ 
body_onload = function(){
   //set focus to first element
   var form_array = [];
   form_array = document.getElementsByTagName('form');               
   for(var i = 0 ;i<1 ; i++){
      if(form_array[i]){  
		for(var j = 0 ;j<form_array[i].elements.length ; j++){
			if(form_array[i].elements[j].disabled != true && form_array[i].elements[j].type != 'hidden' && form_array[i].elements[j].style.display != 'none'){
				form_array[i].elements[j].focus();
				break;
			}else{
				continue;
			}
		}
      }
   }
	$('body').append("<div class='none' id='jalert'></div>");
}
 
/*!
* Login validation 
* Function : validateLogin
* Param    : NA
* Return   : True/False (Boolean)
*/ 
validateLogin = function(){
	
	if(Trim($('#username').val()) == ''){
	
		alert('Please Enter Username!');
		$('#username').val('');
		$('#username').focus();
		return false;
	
	}
	
	if(Trim($('#password').val()) == ''){
	
		alert('Please Enter Password!');
		$('#password').val('');
		$('#password').focus();
		return false;
	
	}
	
	return true;
}

/*!
* Login validation 
* Function : validateLogin
* Param    : NA
* Return   : True/False (Boolean)
*/ 
validatePassword = function(){
	
	var oldpass = $('#oldpassword').val();
	var newpass = $('#password').val();
	var confpass = $('#confirmpassword').val();

	if( Trim(oldpass) == ''){
		alert('Please enter your old password. ');
		$('#oldpassword').val('');
		$('#oldpassword').focus();
		return false;
	}
	if(oldpass.length<4){
		alert('Password must have atleast four character.');
		$('#oldpassword').val('');
		$('#oldpassword').focus();		
		return false;
	}
	if(oldpass.length>25){
		alert('Password should maximum twenty five character !');
		$('#oldpassword').val('');
		$('#oldpassword').focus();		
		return false;
	}

	if($('#oldpassword').val() != ""){      
		var invalid = " "; // Invalid character is a space
      
		// check for spaces
		if ($('#oldpassword').val().indexOf(invalid) > -1) {
			alert("Sorry, spaces are not allowed for password.");
			$('#oldpassword').val('');
			$('#oldpassword').focus();		
			return false;
		}      
    }

	if(Trim(newpass) == ''){
		alert('Please enter your new password. ');
		$('#password').val('');
		$('#password').focus();		
		return false;
	}
	if(newpass.length<4){
		alert('Password must have atleast four character.');
		$('#password').val('');
		$('#password').focus();			
		return false;
	}
	if(newpass.length>25){
		alert('Password should maximum twenty five character !');
		$('#password').val('');
		$('#password').focus();			
		return false;
	}

	if($('#password').value!=""){      
		var invalid = " "; // Invalid character is a space
      
		// check for spaces
		if ($('#password').val().indexOf(invalid) > -1) {
			alert("Sorry, spaces are not allowed for password.");
			$('#password').val('');
			$('#password').focus();	
			return false;
		}      
    }


	if(Trim(confpass) == ''){
		alert('Please Re-enter your password.');
		$('#confirmpassword').val('');
		$('#confirmpassword').focus();	
		return false;
	}

	if(newpass != confpass){
		alert('Both New Password and Confirm New Password Fields should same!');
		$('#confirmpassword').val('');
		$('#confirmpassword').focus();			
		return false;
	}
	
	return true;

}

/*!
* Forget password email validation Functions
* Functions: validateEmail
* Param    : NA
* Return   : true/false (boolean)
*/ 
validateEmail = function(){

	if(Trim($('#username').val()) == ''){
		alert('Please Enter Username');
		$('#username').val('');
		$('#username').focus();	
		return false;
	}
	
	if(Trim($('#email').val()) == ''){
		alert('Please Enter Your Email');
		$('#email').val('');
		$('#email').focus();
		return false;
	}
	
	if(!isValidEmailFormat(document.getElementById('email'))){			
		$('#email').val('');
		$('#email').focus();
		return false;
	}
	
	if(Trim($('#confirmemail').val()) == ''){
		alert('Please Re-Enter Your Email');
		$('#confirmemail').val('');
		$('#confirmemail').focus();		
		return false;
	}
	
	if(!isValidEmailFormat(document.getElementById('confirmemail'))){			
		$('#confirmemail').val('');
		$('#confirmemail').focus();
		return false;
	}
	
	if($('#email').val() != $('#confirmemail').val()){
		alert('Email and Confirm Email should match!');
		$('#confirmemail').val('');
		$('#confirmemail').focus();
		return false;
	}
	
	
	return true;
}
checkDealer = function(){
	
	if($('#which_user').val() == 0 && Trim($('#Customer_Name').val()) == ''){
		alert('Please Select a dealer or Type in the Customer Name!');
		$('#which_user').focus();		
		return false;
	}
	
	return true;
}
getProvince = function(country_id){
	
	$('#country_pr').css('display','inline');
	$.ajax({
		type: "POST",
		url: "/action.php",	
		data:{'action':'list_province','country_id':country_id},
		success: function(html){							
			$('#province').html(html);
			$('#country_pr').css('display','none');
		}	
	});

}
product_search = function(){

	var prd_code = $('#prd_code').val();
	
	if(prd_code == ''){
		Jalert('Please Enter Product Code!');
		$('#prd_code').val('');
		$('#prd_code').focus();
		return false;
	}else{
		$('#search_progress').css('display','block');
		$.ajax({
			type: "POST",
			url: "/action.php",	
			data:{'action':'order','prd_code':prd_code},
			success: function(html){							
				$('#search_result').html(html);
				$('#search_progress').css('display','none');				
			}	
		});
	}

}

option_search = function(prd_code){
	$('#prd_code').val(prd_code);
	$('#search_progress').css('display','block');	
	$.ajax({
		type: "POST",
		url: "/action.php",	
		data:{'action':'order','prd_code':prd_code},
		success: function(html){							
			$('#search_result').html(html);
			$('#search_progress').css('display','none');				
		}	
	});	

}





var alert_status = false;
check_total = function(el,elem){

	if(Trim(elem.value) != ''){	
		if(!isInteger(elem.value) || elem.value <0){
			if(alert_status == false){
				alert_status = true;
				Jalert('Please enter a Positive Numeric value only!');
				elem.value = '';
				elem.focus();
				return false;
			}
		}		
	}
	
	var total = 0;		
	var field_name = '';
	for(var i = 1 ; i <= el; i++){
		if(isInteger(Trim($('#field_'+i).val()))){
			total = total + parseInt(Trim($('#field_'+i).val()));	
			field_name = $('#field_'+i).attr('name')+'_stk';
			if($('#'+field_name)){
				if($('#'+field_name).val() > parseInt(Trim($('#field_'+i).val())) && parseInt(Trim($('#field_'+i).val())) > 0){
					$('#field_'+i).css('border','2px solid green');
				}
			}
		}
	}			
	
	$('#total').val(total);
	
	var disc = 0.00;
	var early_disc = 0.00;
	var spl_disc = 0.00;
	var total_price = 0.00;
	
	var product_price = parseFloat($('#prd_price').val());
	var product_discount = parseInt($('#prd_discount').val())/100;
	var product_early_discount = parseInt($('#prd_early_discount').val())/100;	
	if($('#spl_discount')){
		var special_discount = parseInt($('#spl_discount').val())/100;
	}else{
		var special_discount = 0;
	}
	
	total_price = total * product_price ;
	$('#total_price').html('$'+formatNumber(total_price,2));
	
	if(product_discount > 0){
		disc = total_price * product_discount;	
	}	
	if(product_early_discount > 0){
		early_disc = total_price * product_early_discount;	
		disc = disc + early_disc;
	}
	if(special_discount > 0){
		spl_disc = total_price * special_discount;	
		disc = disc + spl_disc;
	}
	
	
	total_price = total_price - disc ;
	total_price = formatNumber(total_price,2);
	$('#pay').html('$'+total_price);		
	
}

check_order = function(el){
	
	var flag = false;
	var delv_date = $('#delv_date').val();
	
	for(var i = 1 ; i < el; i++){
		if(Trim($('#field_'+i).val()) != ''){
			flag = true;
		}	
	}	
	if(!flag){
		Jalert('Please Enter some quantity to order!');	
		$('#field_1').val('');
		$('#field_1').focus();
		return false;
	}
	
	var total = 0;			
	for(var i = 1 ; i <= el; i++){
		if(isInteger(Trim($('#field_'+i).val()))){
			total = total + parseInt(Trim($('#field_'+i).val()));	
		}
	}	
	if(total == 0){
		Jalert('Please enter a positive quantity to order!');	
		return false;
	}
	$('#total').val(total);
	
	
	if(Trim(delv_date) == ''){

		var dateMin = new Date();
        //var weekDays = AddWeekDays(2);
		// Added by Elehost on 11/25/2010 to track the next ordering day to be as follows
		// If the order is before 1pm then they can select the same day. If the order is after 1pm then it needs
		// to be the next day for ordering
		var curHours = dateMin.getHours();
		
		if(curHours>=13) {
			// This means it is after 1 pm so same day ordering is allowed
			var weekDays = 1;
		}else{
			// This means it is before 1 pm so same day ordering is allowed
			var weekDays = 0;
		}

        dateMin.setDate(dateMin.getDate() + weekDays);

		var html = "<div align='center'> Please Enter Expected Ship Date <br /><br /> <div id='cal'></div><div align='center' id='accept'></div></div>";
		jQuery.facebox(html);	
		$("#cal").datepicker({			
				beforeShowDay: noWeekendsOrHolidays,
				showOn: 'button',
				buttonImage: '/images/calendar1.gif',
				buttonImageOnly: true,
				dateFormat:'yy-mm-dd',
				minDate: dateMin,
				onSelect: function(dateText, inst){
					var msg = "<br />Ship Date: "+dateText+"<br /><br /><input type='button' value='Accept Date' class='blu_btn' style='float:none;' onclick='check_stock();'/><br /><br /><img class='none' id='stock_progress' title='processing' src='/images/loading.gif'>";
					var delv_date_msg = "Expected Order Ship Date : "+dateText+" <a href='javascript:void(0)' onclick='change_date();' style='color:brown;font-weight:bold;font-size:11px;text-decoration:none;'><img class='icons' src='/images/16px/edit.png'>(Change)</a>"
					$('#accept').html(msg);
					$('#delv_date').val(dateText);
					$('#exp_del_date').html(delv_date_msg);
					$('#exp_del_date').css('display','inline');
				}
			});		
	}else{
		$('#search_progress').css('display','block');
		check_stock();
	}
	
}
update_order = function (el,upcnt){
	
	var flag = false;
	var delv_date = $('#delv_date').val();
	
	for(var i = 1 ; i < el; i++){
		if(Trim($('#field_'+i).val()) != ''){
			flag = true;
		}	
	}	
	if(!flag){
		Jalert('Please Enter some quantity to order!');	
		$('#field_1').val('');
		$('#field_1').focus();
		return false;
	}
	
	var total = 0;			
	for(var i = 1 ; i <= el; i++){
		if(isInteger(Trim($('#field_'+i).val()))){
			total = total + parseInt(Trim($('#field_'+i).val()));	
		}
	}	
	if(total == 0 && upcnt != 1){
		Jalert('Please enter a positive quantity to order!');	
		return false;
	}
	$('#total').val(total);
	$('#update_progress').css('display','block');
		
	if(upcnt == 1){
		check_stock('updateafteredit');
	}else{
		check_stock('edit');

	}
}

check_stock = function(act){

	var prd_code = $('#prd_code').val();
	var delv_date = $('#delv_date').val();
	
	var fields = $("input[id^='field']");
	
	var options = [];
	var item ;	
	
	var values = [];
	var quantity;
	
	if(fields.length > 0){
	
		for (var i = 0; i < fields.length ; i++ ){
		
			if(fields[i].value != ''){
			
				options.push(fields[i].name);
				
				values.push(fields[i].value);
				
			}
			
		}
		
		if(options.length == values.length){
		
			item = options.join(',');
			quantity = values.join(',');
			
		}
		
	}
	
	/* Checking stock availability */
	$('#stock_progress').css('display','block');	
	$.ajax({
		type: "POST",
		url: "/action.php",	
		data:{'action':'stock','options':item,'values':quantity,'prd_code':prd_code,'delv_date':delv_date,'act':act},
		success: function(html){
			if(html != 'yes'){
				$('#search_result').html(html);
				$('#search_progress').css('display','none');
				$('#update_progress').css('display','none');
				jQuery(document).trigger('close.facebox');
			}else if(html == 'yes'){
				jQuery(document).trigger('close.facebox');
				window.location = '/dealers/view_cart.php'
			}
			
		}	
	});
	
}

change_date = function(){
	var delv_date = $('#delv_date').val();

	var html = "<div align='center'> Please Enter Expected Ship Date <br /><br /> <div id='cal'></div><div align='center' id='accept'></div></div>";
	jQuery.facebox(html);	

		var dateMin = new Date();

		//var weekDays = AddWeekDays(2);
		// Added by Elehost on 11/25/2010 to track the next ordering day to be as follows
		// If the order is before 1pm then they can select the same day. If the order is after 1pm then it needs
		// to be the next day for ordering
		var curHours = dateMin.getHours();
		
		if(curHours>=13) {
			// This means it is after 1 pm so same day ordering is allowed
			var weekDays = 1;
		}else{
			// This means it is before 1 pm so same day ordering is allowed
			var weekDays = 0;
		}

        dateMin.setDate(dateMin.getDate() + weekDays);

	$("#cal").datepicker({			
			beforeShowDay: noWeekendsOrHolidays,
			showOn: 'button',
			buttonImage: '/images/calendar1.gif',
			buttonImageOnly: true,
			dateFormat:'yy-mm-dd',
			minDate: dateMin,
			defaultDate:delv_date,
			onSelect: function(dateText, inst){
				var msg = "<br />Ship Date: "+dateText+"<br /><br /><input type='button' value='Accept Date' class='blu_btn' style='float:none;' onclick=\"check_stock('updelvdate');\"/><br /><br /><img class='none' id='stock_progress' title='processing' src='/images/loading.gif'>";
				var delv_date_msg = "Expected Order Ship Date : "+dateText+" <a href='javascript:void(0)' onclick='change_date();' style='color:brown;font-weight:bold;font-size:11px;text-decoration:none;'><img class='icons' src='/images/16px/edit.png'>(Change)</a>"
				$('#accept').html(msg);
				$('#delv_date').val(dateText);
				$('#exp_del_date').html(delv_date_msg);
				$('#exp_del_date').css('display','inline');
			}
		});	

}

fix_ship_date = function(delv_date){

	var html = "<div align='center'><h3>We're Sorry!</h3><p>The Expected Ship Date of <strong>"+delv_date+"</strong> is no longer valid.</p><p>Same day orders must be placed before 1:00pm EST.<br>Please revise your Expected Ship Date below.</p><br /><div id='cal'></div><div align='center' id='accept'></div></div>";
	jQuery.facebox(html);	

		var dateMin = new Date();

		//var weekDays = AddWeekDays(2);
		// Added by Elehost on 11/25/2010 to track the next ordering day to be as follows
		// If the order is before 1pm then they can select the same day. If the order is after 1pm then it needs
		// to be the next day for ordering
		var curHours = dateMin.getHours();
		
		if(curHours>=13) {
			// This means it is after 1 pm so same day ordering is allowed
			var weekDays = 1;
		}else{
			// This means it is before 1 pm so same day ordering is allowed
			var weekDays = 0;
		}

        dateMin.setDate(dateMin.getDate() + weekDays);

	$("#cal").datepicker({			
			beforeShowDay: noWeekendsOrHolidays,
			showOn: 'button',
			buttonImage: '/images/calendar1.gif',
			buttonImageOnly: true,
			dateFormat:'yy-mm-dd',
			minDate: dateMin,
			defaultDate:delv_date,
			onSelect: function(dateText, inst){
				var msg = "<br />Ship Date: "+dateText+"<br /><br /><input type='button' value='Accept Date' class='blu_btn' style='float:none;' onclick=\"check_stock('updelvdate');\"/><br /><br /><img class='none' id='stock_progress' title='processing' src='/images/loading.gif'>";
				var delv_date_msg = "Expected Order Ship Date : "+dateText+" <a href='javascript:void(0)' onclick='change_date();' style='color:brown;font-weight:bold;font-size:11px;text-decoration:none;'><img class='icons' src='/images/16px/edit.png'>(Change)</a>"
				$('#accept').html(msg);
				$('#delv_date').val(dateText);
				$('#exp_del_date').html(delv_date_msg);
				$('#exp_del_date').css('display','inline');
			}
		});	

}

remove_item = function(item_id,desc){
	var status;
	if(item_id != ''){	
		status = confirm('Are you sure you want to remove: '+desc);
		if(status){
			$('#item_id').val(item_id);
			$('#action').val('del');
			$('#viewcart').submit();			
		}else{
			return false;
		}		
	}
}
empty_cart = function(dealer_id){
	var msg = 'Are you sure you want to remove all items from cart!';
	if(dealer_id != ''){	
		$('#jalert').html(msg);
		$("#jalert").dialog({
			resizable: false,
			title:"<image src='/images/notice.png'/> Empty Alert",
			height:'auto',
			modal: true,
			closeOnEscape: false,
			buttons: {			
				'Cancel': function() {
					alert_status = false;
					$(this).dialog('close');
				},			
				'Ok': function() {
					$('#action').val('empty');
					$('#viewcart').submit();
				}
			}
		});		
	}
}
edit_item = function(order_id,master_code){

	window.location ="/dealers/edit_cart?order_id="+order_id+"&master_code="+master_code;

}
change_alert = function(dealer_id){
	var msg = "<p>We're Sorry! To change the date, we must clear the current cart. Are you sure you wish to do this?</p>";
	$('#jalert').html(msg);
	$("#jalert").dialog({
		resizable: false,
		title:"<image src='/images/notice.png'/> Alert",
		height:170,
		modal: true,
		closeOnEscape: false,
		buttons: {			
			'No': function() {
				$(this).dialog('close');
			},
			'Yes': function() {
				$('#action').val('empty');
				$('#viewcart').submit();
				$(this).dialog('close');
			}
		}
	});
}

order_alert = function(order_date,item_count){
	
	var msg = "<p>You have an open order started on '"+order_date+"', with "+item_count+" items in your cart that was not completed. Did you want to continue your order from where you left off or cancel the pending order and start over?</p>";
	$('#ord_alert').html(msg);
	$("#ord_alert").dialog({
		resizable: false,
		title:"<image src='/images/notice.png'/> Pending Order Notice",
		height:200,
		width:320,
		modal: true,
		closeOnEscape: false,
		buttons: {						
			'Cancel': function() {
				$('#action').val('empty');
				$('#viewcart').submit();
				$(this).dialog('close');
			},
			'Continue': function() {
				window.location ='/dealers/view_cart.php';
				$(this).dialog('close');				
			}
		}
	});
}

view_details = function(item_id){

	window.location = '/dealers/view_details?item_id='+item_id;

}

view_details_admin = function(item_id,dealer_id){

	window.open('/admin/view_details_admin?item_id='+item_id+'&dealer_id='+dealer_id,'_blank');

}

/*!
* For Alert Messages
* Functions: Jalert
* Param    : msg (string)
* Return   : NA
*/
function Jalert(msg){

	$('#jalert').html(msg);
	$("#jalert").dialog({
		resizable: false,
		title:"<image src='/images/notice.png'/> Alert",
		height:'auto',
		modal: true,
		closeOnEscape: false,
		buttons: {			
			'Ok': function() {
				alert_status = false;
				$(this).dialog('close');
			}			
		}
	});

}

/*!
* Integer validation Functions
* Functions: isInteger
* Param    : val (string)
* Return   : true/false (boolean)
*/
function isInteger(val){
    
    if(val==null){        
        return false;
    }
    if (val.length==0){       
        return false;
    }
    for (var i = 0; i < val.length; i++){
        var ch = val.charAt(i)
        if (i == 0 && ch == "-"){
            continue
        }
        if (ch < "0" || ch > "9"){
            return false
        }
    }
    return true
}
/*!
* Email validation Functions
* Functions: isValidEmailFormat
* Param    : email (string)
* Return   : true/false (boolean)
*/ 
function isValidEmailFormat(email){
    var status; 
    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email.value)){
	     status = true;
        return status;
    }
    alert('Enter valid e-mail ID.');
    return false;
}
/*!
* Trim Functions
* Functions: LTrim, RTrim, Trim 
* Param    : str (string)
* Return   : s (string)
*/ 
LTrim = function(str){
	var whitespace = new String(" \t\n\r");

	var s = new String(str);

	if (whitespace.indexOf(s.charAt(0)) != -1) {   
		var j=0, i = s.length;   
		while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
			j++;   
		s = s.substring(j, i);
	}
	return s;
}

RTrim = function(str){
    
    var whitespace = new String(" \t\n\r");
  
    var s = new String(str);
  
    if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
      
		var i = s.length - 1;    
    
		while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
			i--;  
		s = s.substring(0, i+1);
	}

    return s;
}

Trim = function(str){
    
    return RTrim(LTrim(str));
    
}
function formatNumber (obj, decimal) {
	 //decimal  - the number of decimals after the digit from 0 to 3
	 //-- Returns the passed number as a string in the xxx,xxx.xx format.
	   anynum=eval(obj);
	   divider =10;
	   switch(decimal){
			case 0:
			   divider =1;
				break;
		   case 1:
			   divider =10;
			   break;
		   case 2:
			  divider =100;
			 break;
			default:       //for 3 decimal places
				divider =1000;
		} 
 
	   workNum=Math.abs((Math.round(anynum*divider)/divider));
 
	   workStr=""+workNum
 
	   if (workStr.indexOf(".")==-1){workStr+="."}
 
	   dStr=workStr.substr(0,workStr.indexOf("."));dNum=dStr-0
	   pStr=workStr.substr(workStr.indexOf("."))
 
	  while (pStr.length-1< decimal){pStr+="0"}
 
	  if(pStr =='.') pStr ='';

	  //--- Adds a comma in the thousands place.   
	  if (dNum>=1000) {
		 dLen=dStr.length
		 dStr=parseInt(""+(dNum/1000))+","+dStr.substring(dLen-3,dLen)
	  } 

	  //-- Adds a comma in the millions place.
	  if (dNum>=1000000) {
		 dLen=dStr.length
		 dStr=parseInt(""+(dNum/1000000))+","+dStr.substring(dLen-7,dLen)
	  }
	  retval = dStr + pStr
	  //-- Put numbers in parentheses if negative.
	  if (anynum<0) {retval="("+retval+")";}

   //You could include a dollar sign in the return value.
	 //retval =  "$"+retval
	 return retval;
}

       function noWeekendsOrHolidays(date) {
            var noWeekend = $.datepicker.noWeekends(date);
            if (noWeekend[0]) {
                return nationalDays(date);
            } else {
                return noWeekend;
            }
        }
        function nationalDays(date) {

	        var natDays = [
    	    	[1, 1, 'ca'],
        		[7, 1, 'ca'],
				[12, 25, 'ca'],
          		[12, 26, 'ca']
	        ];

			for (i = 0; i < natDays.length; i++) {
                if (date.getMonth() == natDays[i][0] - 1 && date.getDate() == natDays[i][1]) {
                    return [false, natDays[i][2] + '_day'];
                }
            }
            return [true, ''];
        }
        function AddWeekDays(weekDaysToAdd) {
            var daysToAdd = 0
            var mydate = new Date()
            var day = mydate.getDay()
            weekDaysToAdd = weekDaysToAdd - (5 - day)
            if ((5 - day) < weekDaysToAdd || weekDaysToAdd == 1) {
                daysToAdd = (5 - day) + 2 + daysToAdd
            } else { // (5-day) >= weekDaysToAdd
                daysToAdd = (5 - day) + daysToAdd
            }
            while (weekDaysToAdd != 0) {
                var week = weekDaysToAdd - 5
                if (week > 0) {
                    daysToAdd = 7 + daysToAdd
                    weekDaysToAdd = weekDaysToAdd - 5
                } else { // week < 0
                    daysToAdd = (5 + week) + daysToAdd
                    weekDaysToAdd = weekDaysToAdd - (5 + week)
                }
            }

            return daysToAdd;
        }


