﻿function Utils()
{}

Utils.Init = function(setup) {
	if (setup && typeof (setup) == 'function') {
		$j(document).ready(function() { setup(); });
		Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function(sender, args) { setup(); });
	}
}

Utils.scrollToAnchorInElement = function(containerId, anchorName)
{
	var divOffset = $j('#' + containerId).offset().top;
  var pOffset = $j('#' + anchorName).offset().top;
  var pScroll = pOffset - divOffset;
  $j('#' + containerId).animate({scrollTop: pScroll}, 1500);   
  return false;
}

Utils.ShowCenteredPopup = function(url, width, height, scrollbars) 
{
 var left   = (screen.width  - width)/2;
 var top    = (screen.height - height)/2;
 var params = 'width='+width+', height='+height;
 params += ', top='+top+', left='+left;
 params += ', directories=no';
 params += ', location=no';
 params += ', menubar=no';
 params += ', resizable=no';
 params += ', scrollbars='+scrollbars;
 params += ', status=no';
 params += ', toolbar=no';
 newwin=window.open(url,'centeredPopupWindowname', params);
 if (window.focus) {newwin.focus()}
 return false;
}

Utils.scrollToAnchor = function(anchorName)
{
    var anchor = $j("#" + anchorName); 
    if(anchor.length != 0) 
    {
        var targetOffset = anchor.offset().top;
        $j('html,body').animate( {scrollTop: targetOffset}, 1500);    
    }
    return false;
}

Utils.scrollToPosition = function(elementWithScroll, top, left)
{
	elementWithScroll.animate( {scrollTop: top}, 500);
	elementWithScroll.animate( {scrollLeft: left}, 500);
	return false;
}

Utils.highlightTotal = function(totalLabel)
{
	$j('#' + totalLabel).animate({ backgroundColor:'yellow'}, 3000);
}

Utils.SpecEffect = function(elementToAnimate)
{
  $j('#' + elementToAnimate).animate( { opacity: 'toggle' }, 500 );
} 

Utils.Focus = function(element)
{
	var focusedElement = $j('#' + element);
					
	setTimeout(function() {
		var value = focusedElement.val();
		focusedElement.focus().val(value);
		}, 1000);
}

Utils.FocusByTab = function(e, element)
{
	var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
	if(key == 9)
	{
		Utils.Focus(element);
	}
}

Utils.ShowBrowserNotSupportedMessage = function()
{	
	if($j.browser.msie && $j.browser.version.substr(0,1) <= 6 && typeof(document.body.style.maxHeight) == "undefined")	
	{		
		var msg = '<div>'; 		
		msg += '<p><b>We’re sorry however Adorama’s new shopping cart requires Internet Explorer 7 or higher.</b></p>';		
		msg += '<p>Click <a  style="color:white;" href="http://www.microsoft.com/Downloads/details.aspx?familyid=9AE91EBE-3385-447C-8A30-081805B2F90B&displaylang=en">here</a> to download the latest version of Internet Explorer.</p>';		
		msg += '<p>To continue to use older versions of Internet Explorer without interruption, ';		
		msg += '<a style="color:white;" href="#" onclick="return Utils.UseOldCart();">click to here</a> to use Adorama’s classic shopping cart.</p>';		
		msg += '</div>';				
		$j('.error-message:eq(0)').empty();		
		$j('.error-message:eq(0)').append(msg);		
		$j('.error-message:eq(0)').show();	
	}
}

Utils.BlockSubmit = function() {
    window.backgroundRequest = (window.backgroundRequest == undefined) ? 1 : window.backgroundRequest + 1;              
	if(window.backgroundRequest == 1) {
	    $j('.jqsubmit').find('input:submit').attr('disabled', 'true');
	    $j('.jqsubmit').show();
    }
};
Utils.UnblockSubmit = function() {
    if(window.backgroundRequest != undefined) {
        window.backgroundRequest--;
        if(window.backgroundRequest == 0) {
	        $j('.jqsubmit').hide();
	        $j('.jqsubmit').find('input:submit').attr('disabled', 'false');
	    }
    }
};


Utils.Setup = function(setup) {
	if (setup && typeof (setup) == 'function') {
		$j(document).ready(function() { setup(); });
		if (typeof (Sys) != 'undefined') {
			Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function(sender, args) { setup(); });
		}
	}

	if (setup && typeof (setup) == 'string') {
		$j(document).ready(function() {
			try { eval(setup); } finally { }

		});
		if (typeof (Sys) != 'undefined') {
			Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function(sender, args) {
				try { eval(setup); } finally { }
			});
		}
	}
}

Utils.CheckClientTimeZone = function()
{
    Utils.Setup(function() {
	    var timeZoneValue = -((new Date()).getTimezoneOffset() / 60);
		$j('.timeZone').find('input:hidden').val(timeZoneValue);
	});
}

Utils.UseOldCart = function()
{
	document.cookie = 'UseAls=F; path=/';
	window.location.replace(window.location.href);
	return false;
}

Utils.GetFloatPrice = function(stringPrice) {
	stringPrice = String(stringPrice);
	if (stringPrice.toLowerCase().indexOf('free') > -1) {
		return 0.0;
	}
	else if (stringPrice.toLowerCase().indexOf('--.--') > -1) {
		return 0.0;
	}
	return parseFloat(stringPrice.replace('$', '').replace(',', ''));
}

Utils.GetFormatedPrice = function(floatPrice) {
	if (isNaN(floatPrice)) {
		return floatPrice.substr(0, 1).toUpperCase() + floatPrice.substr(1);
	}
	else {
		return Utils.FormatCurrency(floatPrice);
	}
}

Utils.IsNeedAjaxPostback = function()  {
	var needAjaxPostback = $j('.jq-hidden').find('input:hidden').val();
    return (needAjaxPostback == '1') ? true : false;
}

Utils.ShowBlockElements = function() {
    $j('.jq-block').show();
    for (var i = 0; i < $j('.jq-block').length; i++) {
      var parent = $j('.jq-block').eq(i).parent();
      var height = $j(parent).innerHeight();
      $j('.jq-block').eq(i).height(height);
    }
}

Utils.FormatCurrency = function(num) {
	if (isNaN(num))
		num = "0";
	if (num == null)
		num = "0";
	num = num.toString().replace(/\$|\,/g, '');
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num * 100 + 0.50000000001);
	cents = num % 100;
	num = Math.floor(num / 100).toString();
	if (cents < 10)
		cents = "0" + cents;
	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 (((sign) ? '' : '-') + '$' + num + '.' + cents);
}



function S4() {
   return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
function guid() {
   return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
  }
  function guidNoDashes() {
  	return (S4() + S4() + S4() + S4() + S4() + S4() + S4() + S4());
  }

function ArrowClick(textBox, errorPanel, valueToAdd) {

    if (!textBox)
		return true;
	
	var value = parseInt($j(textBox).val());
	if (isNaN(value) || value <= 0 || value > 9999 || value.toString().length != textBox.value.length) {
		if (errorPanel) $j(errorPanel).css( {'display': 'inline'} );
	}
	else {
		if (value + valueToAdd >= 1 && value + valueToAdd <= 9999) {
			$j(textBox).val(value + valueToAdd);
		}
		if (errorPanel) $j(errorPanel).css( {'display': 'none'} );
	}
}

function CheckQuantityValue(textBox, errorPanel) {

	if (!textBox)
		return true;
	var inputValue = $j(textBox).val();

	

	var value = parseInt(inputValue);
	if (isNaN(value) || value <= 0 || value > 9999 || value.toString().length != inputValue.length) {
	  if (errorPanel) {
	    $j(errorPanel).css({ 'display': 'inline' });
	    $j(textBox).css({ 'background-color': 'red' });
	  }
		return false;
	}
	else {
	  if (errorPanel) {
	    $j(errorPanel).css({ 'display': 'none' });
	  }
	  $j(textBox).css({ 'background': 'none' });
		$j(textBox).val(value);
		return true;
	}
}

function disableTabsFor(popupContainer)
{
	$j("a,  button, frame, iframe, img, input, isIndex, object, select, textArea").attr("tabIndex", "-1");
	$j('#' + popupContainer)
		.children().find("a,  button, frame, iframe, img, input, isIndex, object, select, textArea").attr("tabIndex", "0");
}

String.prototype.replaceAll = function(search, replace) {
	return this.split(search).join(replace);
}

/* string utils */

StringUtil = function() {}

StringUtil.trim = function(str, chars) { 
    str = StringUtil.rtrim(str, chars);
    return StringUtil.ltrim(str, chars); 
}
StringUtil.ltrim = function(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
StringUtil.rtrim = function(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
StringUtil.replaceAll = function(str, target, string){
    var intIndexOfMatch = str.indexOf(target);
    while (intIndexOfMatch != -1){
        str = str.replace(target, string)
        intIndexOfMatch = str.indexOf(target);
    }
    return str;
}
