///////////////////////////////////////////////////////
/// Date: Jan, 2008
/// Script Created By: Evghenii Baboi  
///----------------------------------------------------
/// Copyright 2008 Digital Haiku Corporation
///          
///  
///////////////////////////////////////////////////////

////////////////////////// Browsers Detection //////////////////////////
var isIE = document.all?true:false; 
var isNS = document.layers?true:false;

////////////////////////// Layers Functions //////////////////////////
function hideLayer(layerName)
{
	$('#'+layerName).hide();
}
function showLayer(layerName)
{
	$('#'+layerName).show();
}

////////////////////////// Other Functions //////////////////////////

/*------------------------- START: used in price recalculating ------------------------------*/
	var err = 'false';
function check_zip(zip_value){
	if(typeof(orderfee) == "undefined"){orderfee=0;}
	var tax = 0;
	$('#zipcode_validator').val('false');
	$('#tax_price').html('$0.00');

		if (zip_value.length > 4){
//			alert("recalculate");
			$.ajax({
				url: '/sage/applications/tonermax/lib/shopping_cart_action.cfm',
				data: 'fv_action=check_zip&zip_code=' + zip_value,
				type: 'get',
				async: true,
				beforeSend:function() {
					$('#zip_code_ajax_working').show();
				},
				success: function(data) {

						if ( data == 'No state'){
							$('#zip_code_field').css({ "background-color":"yellow", "border":"solid 1px red" });
							err = 'true';
							$('#zipcode_validator').val('false');
						} else{

								if ( (tax = parseFloat(data)) != 'NaN'){
									var total = subtotal + tax + orderfee;
									$("#general-total-price").html(dollarFormat(total));
									$('#zip_code_field').css({ "border":"solid 1px", "border-color":"#C1CBCF #E7F5FA #E2F2F8 #D1DCDF" , "background":"#ECF8FC none repeat scroll 0 0"  });
									err = 'false';
									$('#zipcode_validator').val('true');
									$('#tax_price').html('$' + tax);
								} else{
									$('#zip_code_field').css({ "background-color":"yellow", "border":"solid 1px red" });
									err = 'true';
									$('#zipcode_validator').val('false');
									$("#general-total-price").html(dollarFormat(subtotal + orderfee));
								}
						}

					$('#zip_code_ajax_working').hide();
				}
			});

		}else{
			if (err == 'false'){
				$('#zip_code_field').css({"border":"solid 1px", "border-color":"#C1CBCF #E7F5FA #E2F2F8 #D1DCDF" , "background":"#ECF8FC none repeat scroll 0 0" });
			}
			$("#general-total-price").html(dollarFormat(subtotal + orderfee));
		}

//					alert($('#zipcode_validator').val());
}
/*------------------------- END: used in price recalculating ------------------------------*/



/*------------------------- START: used in autocmpleter ------------------------------*/
function selectItem(li, obj_name) {    
   if( !!li.extra ) var sValue = li.extra[0];
   else var sValue = li.selectValue; 
   $("#"+obj_name).val( sValue);   
}

function formatItem(row) {
   return row[0] + ((row[1] != "") ? " (" + row[1] + ")" : "");
}

function changeClassName(id, classname1, classname2)
{
		$('#'+id).removeClass(classname1);
		$('#'+id).addClass(classname2);
}
/*------------------------- END: used in autocmpleter ------------------------------*/

function loadSettingsDivContent(url)
{
		$('.dhSettings').showSettingsDiv();
		$.get(
			url + Math.random(),
			{},
			function(resp) {// alert(resp);
				$('.dhSettings .dhsInnerCell').html(resp);
			}
		);
}

function loadSuggestionDivContent(url)
{
		$('.dhSuggestion').showSettingsDiv();
		
		$.get(
			url + Math.random(),
			{},
			function(resp) {// alert(resp);
				$('.dhSettings .dhsInnerCell').html(resp);
			}
		);
}

function getAbsoluteLeftObj(object) {
		// Get an object left position from the upper left viewport corner
		o =  object;
		oLeft = o.offsetLeft;            // Get left position from the parent object
		while(o.offsetParent!=null) {   // Parse the parent hierarchy up to the document element
			oParent = o.offsetParent;    // Get parent object reference
			oLeft += oParent.offsetLeft; // Add parent left position
			o = oParent;
		}
		return oLeft
}
				
function getAbsoluteTopObj(object) {
			// Get an object top position from the upper left viewport corner
			o = object;
			oTop = o.offsetTop;            // Get top position from the parent object
			while(o.offsetParent!=null) { // Parse the parent hierarchy up to the document element
				oParent = o.offsetParent;  // Get parent object reference
				oTop += oParent.offsetTop; // Add parent top position
				o = oParent;
			}
			return oTop;
}
	 
	 
function swap (id) {
		  if( $("#"+id).css('display')=='none')		   
		    $("#"+id).show(); 
		  else 
		   $("#"+id).hide();
	   }; 	

function IsEmpty(v) {
    return  ((v == null) || (v.length == 0) || /^\s+$/.test(v));
};
function IsDigits(v) {
    return !IsEmpty(v) && !/[^\d]/.test(v);
}

function onlyDigits(e, decReq) {
	if (decReq == null) decReq = 'noDec';
	var key = (isIE) ? window.event.keyCode : e.which;
	var obj = (isIE) ? event.srcElement : e.target;
	var isNum = (key > 47 && key < 58) ? true:false;
	var dotOK = (key == 46 && decReq == 'decOK' && (obj.value.indexOf(".") < 0));
	if(key < 32)return true;
	return (isNum || dotOK);
}

function formatMoney_old (n, c, d, t){
	var c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
	return parseFloat(s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ""));
}
 
function isNumeric(form_value) 
{ 
   try{
	if (form_value.match(/^\d+$/) == null) 
        return false; 
    else 
        return true; 
   }
   catch(er) 
   {   return false;
   }   
} 

//--- if threre is no PopUp window div inserts it
function addPopUpWindowDiv(id_name, content, onClose)
{
	$(document).pngFix();
	var html = '';
	if(!onClose) onClose='';
	if(!content) content='';
	if($('#' + id_name).length == 0)
	{
		html = 		 '<div id="'+id_name+'" class="box2" style="display: none; left:30%; top:36%;">';
		html = html +'	<div style="height: 65px;" id="box-top"><div class="box-top-l"></div><div class="box-top"></div><div class="box-top-r"></div></div>';
		html = html +'	<div class="box2-content" style="height: 70px;">';
		html = html +'	<div class="windowControls" style="margin-top: -50px;"><a href="javascript: void(0);" onclick="'+onClose+' $(\'#'+id_name+'\').hide(\'fast\');" class="controlClose">Close</a></div>';
		html = html +'		<div class="box2_content" style="position: absolute; padding-top: 10px;">'+content+'</div>';
		html = html +'	</div>';
		html = html +'	<div style="height: 20px;"><div class="box-bottom-l"></div><div class="box-bottom"></div><div class="box-bottom-r"></div></div>';
		html = html +'</div>';
		if($("#mainBox > div.inside").val() == undefined){
			$("#mainBox > div.middleInside").prepend(html); //for GBS
		}else{
			$("#mainBox > div.inside").prepend(html);
		}		
	}else{
		$("#"+id_name+" > div.box-content > div.box_content").html(content);
		$("#"+id_name+" > div.box-content > div > a").attr('onclick',"$('#"+id_name+"').hide('fast');"+onClose);		
	}
}


function ajaxSaveMyModel(url)
{	
		var model_id = $('#addToMyModelForm_model_id').val()
		$('#add_to_mm_' + model_id).hide();		
		$('#remove_mm_' + model_id).show();
		
	$.post(url,
	  { 
	    model_id: $('#addToMyModelForm_model_id').val(),
	    name: $('#addToMyModelForm_name').val(),
	    qty: $('#addToMyModelForm_qty').val()
	  },
	  function(data){
	    addToMyModelForm_action(data, $('#addToMyModelForm_model_id').val());	    
	  }
	);
}

function ajaxForgotPassword(url)
{
	if ( $('#forgotPasswordForm_email').val() != '' ) 
	{
			
		$.ajax({
			   type: "POST",
			   url: url,
			   data: "email=" + $('#forgotPasswordForm_email').val(),
			   beforeSend: function() { 	
					
					$('#passMessage').html('<center style="color:#006699;">Working</center>');
				},
			   success: function(data){
					forgotPasswordForm_action(data);
				  }
			 });
	}
}

function URLEncode (clearString) {
  var output = '';
  var x = 0;
  clearString = clearString.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < clearString.length) {
    var match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '') {
    	output += match[1];
      x += match[1].length;
    } else {
      if (clearString[x] == ' ')
        output += '+';
      else {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      }
      x++;
    }
  }
  return output;
}


function URLDecode (encodedString) {
  var output = encodedString;
  var binVal, thisString;
  var myregexp = /(%[^%]{2})/;
  while ((match = myregexp.exec(output)) != null
             && match.length > 1
             && match[1] != '') {
    binVal = parseInt(match[1].substr(1),16);
    thisString = String.fromCharCode(binVal);
    output = output.replace(match[1], thisString);
  }
  return output;
}

function formatMoney(num, currency) {
    num = num.toString().replace(/\$|\,/g,'');

    if(isNaN(num)) num = "0";

    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    dec = num%100;
    num = Math.floor(num/100).toString();

    if(dec<10) dec = "0" + dec;

    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++) {
        num = num.substring(0,num.length-(4*i+3)) + ',' + num.substring(num.length-(4*i+3));
    }

    return currency + (((sign)?'':'-') + num + '.' + dec);
} 

function dollarFormat(amount) {
    return formatMoney(amount, '$');
}

function isDefined(val_name){
	if(eval('typeof '+val_name) == "undefined") return false;
	return true;
}


//---------------- Format Postal Code ------------------
    function getFormatedPostalCode(postal_code) {
        postal_code = postal_code.replace(/[ -]/,'');

        switch(postal_code.length) {
            case 9: postal_code = postal_code.substring(0,5) + '-' + postal_code.substring(5);
        }

        return postal_code;
    }
//------------------------------------------------------

function removeMyModel(model_id, model_name) 
{ 
	if(confirm('Are you sure you want to remove this model?'))
	{
		$.get("/sage/index.cfm", { page_id: 676, theme: 'ajax', frm_action: 'delMyModels', model_id: model_id } );
		$('#remove_mm_' + model_id).hide();
		$('#add_to_mm_' + model_id).show();
		
	}  
} 



function reOpenTicket(so_id,ticket_id,page_id, status)
{
	if (status == 1)
		{var status = 'anonymous';}
	else
		{var status = '';}
	$.ajax({
			url: '/sage/index.cfm',
			data: 'page_id=' + page_id + '&phase=re_open_ticket&customer_care_ticket_id=' + ticket_id +'&sales_order_id='+ so_id + '&theme=ajax&status=' + status + '&safari=true&rnd='+Math.random(),
			type: 'get',
			beforeSend: function() {
				$('#custom_care_request').html('<center><img src="/sage/themes/intranet/images/bigrotation2_new.gif" border="0" /></center>');
		            },
			success: function(data) {
				$("#custom_care_request").html(data);
				HideDivStatusInfo('_customer_care');
			}
			});	
}

function getByModel(sel_model_id,id){
			
			var sel_val = $(id).parent().parent().parent().html().replace(/(onclick="(.*?)")|(onclick=(.*?)[\s])/gi,'');

			$("#selected_model").html(sel_val);
			
			$("#img_border_" + sel_model_id).css("border","1px #FFFFFF solid");
			$("#selected_model").find("center").removeAttr("id");
			
			if($.browser.msie && $.browser_please_do_not_use_this_shit.version.number() <= 7){ 				
				$("#selected_model").css("margin-top","-42px");
			}	

			//$("#selected_model").find("img").css("border","1px #e4e4e5 solid");			
			$("#selected_model").find("img").css("margin-right","0px"); 
			$("#selected_model").find("img").addClass("related_img"); 			
			$("#selected_model").find("div").remove();
			$("#selected_model").find("b").css("color","white");
			$("#selected_model").addClass("IE6_adjustment"); 
			$("#selected_model").addClass("IE7_adjustment");			

			doSearchItems(sel_model_id);	
	}

function highlightSelected(id, model_id){
	//$(id).find("img").css("border","1px #4C91CC solid");
	//$(id).find("center").css("border","1px #4C91CC solid");
	$("#img_border_" + model_id).css("border","1px #4C91CC solid");
	$(id).find("div").addClass("no_opacity");
	//$(id).find("div").css("opacity","1"); 
	//$(id).find("div").css("filter","alpha(opacity=100)");
	$(id).find("b").css("color","#386699");
	//$(id).find("div").stop().animate({ opacity: 1.0 }, 5); 
	

} 	
	
function leaveSelected(id, model_id){
	//$(id).find("img").css("border","1px #e4e4e5 solid");
	//$(id).find("center").css("border","none");
	$("#img_border_" + model_id).css("border","1px #FFFFFF solid");
	//$(id).find("div").css("opacity","0.4");
	$(id).find("div").removeClass("no_opacity");
	//$(id).find("div").css("filter","alpha(opacity=40)");
	$(id).find("b").css("color","black");
}

function doHtmlspecialchars(string){
    return string.replace('&', '&amp;').replace('>', '&gt;').replace('<', '&lt;').replace('"', '&quot;');
}

function doHtmlspecialchars_decode(string){
    return string.replace('&gt;', '>').replace('&lt;', '<').replace('&quot;', '"').replace('&amp;', '&');
}