
/*--- AddToCard.js ---*//*-------- AddToCard -------*/
AddToCard = function() {}

AddToCard.Add = function(it, skuNumber, redirectAfterAdded) {
    var fullUrl = Config.AddToCardHandler();


    if (skuNumber.substring(0, 4) == 'GIFT') {
        window.location.href = Config.SendGiftCertUrl();
        $j('body').html('');
        return false;
    }

    var quantity = 1;
    var quantityTextBox = $j(it).parents('.jq_AddToCart_' + skuNumber + ':first')
                                .find('.jq_QuantityTextBox:first');

    var errorPanel = $j(it).parents('.jq_AddToCart_' + skuNumber + ':first')
                           .find('.jq_ErrorPanel:first');

    if (quantityTextBox != null && quantityTextBox.length > 0) {
    	if (AddToCard.CheckQuantityValue(quantityTextBox[0]))
            quantity = parseInt(quantityTextBox[0].value);
        else
            return false;
    }

    emailPriceInQuwery = (window.location.href.indexOf("emailprice=t") > 0);


    $j(".AddToCard_WaitBlock_" + skuNumber).css("display", "block");
    $j.ajax({
        type: "POST",
        url: fullUrl,
        async: true,
        data: { SkuNumber: skuNumber, Quantity: quantity, EmailPriceInQuwery: emailPriceInQuwery },
        success: function(answer) {
            if (window.AddToCardLockObject == null) {
                $j(".AddToCard_WaitBlock_" + skuNumber).css("display", "none");
                if (answer.Error != null) {
                    $j(".AddToCard_QuantityPanel_Label_" + skuNumber).html(answer.Error);
                    return;
                }
                if (answer.Exception != null) {
                    $j(".AddToCard_AddToCartPanel_" + skuNumber).css("display", "none");
                    AddToCard.ShowUsedPopup(answer.Exception);
                    return;
                }

                $j(".AddToCard_AddToCartPanel_" + skuNumber).css("display", "none");
                if (redirectAfterAdded) {
                    window.AddToCardLockObject = new Object();
                    var sku = StringUtil.replaceAll(skuNumber, '_', ' ');
                    window.location.href = Config.CartViewUrlWithSkuParam() + sku;
                    $j('body').html('');
                }
                else {
                    $j(".AddToCard_QuantityPanel_" + skuNumber).css("display", "block");

                    var isUsed = skuNumber.indexOf('_') != -1;
                    var msg = isUsed ? "Added to Cart" : "Added to Cart (" + answer.Quantity + ")";
                    $j(".AddToCard_QuantityPanel_Label_" + skuNumber).html(msg);

                    var editButtonDisplay = isUsed ? "none" : "block";

                    $j('.jq_AddToCart_' + skuNumber + ' .edit_quantity_btn')
                        .css("display", editButtonDisplay);

                    AddToCard.GetQuantityTextBox(skuNumber).val(answer.Quantity);

                    $j(".AddToCard_Cart_Total").html("(" + answer.CartQuantity + "  items, $" + answer.CartTotal + ")");
                }
            }
        },
        error: function(answer) {
            if (window.AddToCardLockObject == null) {
                $j(".AddToCard_WaitBlock_" + skuNumber).css("display", "none");
                $j(".AddToCard_QuantityPanel_Label_" + skuNumber).html($j(".jq_PopupHttpError").html());
            }
        },
        dataType: "json"
    });

    return false;
}

AddToCard.GetQuantityTextBox = function(skuNumber) {
    return $j(".jq_AddToCart_" + skuNumber + " .jq_QuantityTextBox");
}
AddToCard.GetErrorPanel = function(skuNumber) {
    return $j(".jq_AddToCart_" + skuNumber + " .jq_ErrorPanel");
}

AddToCard.Edit = function(skuNumber) {
	$j(".AddToCard_AddToCartPanel_" + skuNumber).css("display", "block");
	$j(".AddToCard_QuantityPanel_" + skuNumber).css("display", "none");
	return false;
}


AddToCard.ShowUsedPopup = function(data) {
	
	
var UsedPopupTemplate = 
'<div class="popupPosition closeClass">' +
'<div class="modalBackground" style="visibility: visible; display: block;"/>' +
	'<div id="popup" class="UsedPopupInformation" style="top:50%;">' + 
	   '<div class="popup-cont brand forms fixed hight-win"><div class="top-line top-shade"><span class="c-l"></span><span class="c-r"></span></div>'+
     '<div class="rgt-shade">' + 
				'<div class="lft-shade">'+ 
					'<div class="content">' + 
						'<div class="b-header">'+
							'<span>How do I use my cart?</span>'+
							'<a ID="CloseButton" >Close</a>' +
							'<div class="clr"></div>' +
						'</div>' +
						'<div class="clr hgt10" />' +
						'<div class="up-cont">' +
						'<p class="notif-n">{Message}</p>'+
						'</div>' +
						'<div class="b-footer">'+
						'<a ID="OkLinkButton" class="btn blue-small" ><span><span>Ok</span></span></a>' +
						'</div>'+
					'</div>' +
				'</div>' +
			'</div>' +
		'<div class="bot-line bot-shade"><span class="c-l"></span><span class="c-r"></span></div>' +
		'</div>'+
		'</div>'+
		'</div>'+
		'</div>'+
	'</div>';	
	
	UsedPopupTemplate = UsedPopupTemplate.replace('{Message}', data);

$j('body').append(UsedPopupTemplate);
$j('.closeClass #CloseButton').click(function() { $j('.closeClass').remove(); } );
$j('.closeClass #OkLinkButton').click(function() { $j('.closeClass').remove(); } );
}

AddToCard.OnFocusQuantity = function(tb) {
	tb.className = 'jq_QuantityTextBox dd-cart-focus';
}

AddToCard.OnBlurQuantity = function(tb) {
	tb.className = 'jq_QuantityTextBox dd-cart-blur';
	AddToCard.CheckQuantityValue(tb);
}

AddToCard.CheckQuantityValue = function(tb) {
	var parent = $j(tb).parents('.add-to');
	var errorDiv = parent.find('.error-div');

	if (!AddToCard.IsQuantityValid(tb)) {
		if (errorDiv.length == 0) {
			errorDiv = $j("<div class='error-div jq_ErrorPanel'><span class='incorrect'><span>Value is incorrect</span></span></div>");
			parent.eq(0).prepend(errorDiv);
		}
		errorDiv.css('display', 'block');
		return false;
	} else {
		errorDiv.css('display', 'none');
	}
	return true;
}

AddToCard.IsQuantityValid = function(tb) {

	if (tb == null)
		return true;

	var inputValue = tb.value;

	var value = parseInt(inputValue);
	if (isNaN(value) || value <= 0 || value > 9999 || value.toString().length != inputValue.length) {
		return false;
	}
	else {
		tb.value = value;
		return true;
	}
}

AddToCard.ArrowClick = function(tb, valueToAdd) {
	var parent = $j(tb).parents('.add-to');
	var textBox = parent.find('.jq_QuantityTextBox')[0];
	if (AddToCard.CheckQuantityValue(textBox)) {
		var value = parseInt(textBox.value);
		if (value + valueToAdd >= 1 && value + valueToAdd <= 9999) {
			textBox.value = value + valueToAdd;
		}
	}
}
/*--- AddToWishList.js ---*//*-------- AddToWishList -------*/
AddToWishList = function() { }


AddToWishList.AddIntoWishList = function(skuNumber) {
    if (skuNumber == null || skuNumber == "undefined")
        return;

    var fullUrl = Config.AddToWishListHandler();
    AddToWishList.GetAnswerBlock(skuNumber).css("display", "none");
    AddToWishList.GetWaitBlock(skuNumber).css("display", "block");
    $j.ajax({
        type: "POST",
        url: fullUrl,
        async: true,
        data: { SkuNumber: skuNumber },
        success: function(answer) {
            if (answer.Error != null) {
                AddToWishList.GetAnswerBlock(skuNumber).css("display", "block");
                AddToWishList.GetAnswerBlock(skuNumber).html(answer.Error);
            }
            else {
                AddToWishList.GetWaitBlock(skuNumber).css("display", "none");
                AddToWishList.GetAnswerBlock(skuNumber).css("display", "block");
                AddToWishList.GetAnswerBlock(skuNumber).html('Added to Wishlist');
                $j(".AddToWishList_Total").html(answer.CartQuantity + " items");
                setTimeout(function() { AddToWishList.HideAnswerPanel(skuNumber); }, 2000);
                var url = "http://" + window.location.host + "/catalog.tpl?op=WishList&addsku=" + skuNumber;
                url = url.replace(window.location.hash, '');
                window.location.href = url;
            }
        },
        error: function(answer) {
            AddToWishList.GetAnswerBlock(skuNumber).css("display", "block");
            AddToWishList.GetAnswerBlock(skuNumber).html($j(".jq_PopupHttpError").html());
            AddToWishList.GetWaitBlock(skuNumber).css("display", "none");
        },
        dataType: "json"
    });
};

AddToWishList.Add = function(skuNumber, it) {

    var userStatusUrl = Config.IsUserRegisteredHandler();
    var isRegistered = UserStatus.Get(userStatusUrl);
    if (isRegistered) {
        AddToWishList.AddIntoWishList(skuNumber);        
    }
    else {

        window.AddToWishListSku = skuNumber;
        $j(document).one("Login.Logined", function(event) {
            $j(document).unbind("Login.Close");
            AddToWishList.AddIntoWishList(window.AddToWishListSku);
            return true;
        });
        Login.Open();
    }
    return false;
}

AddToWishList.GetAnswerBlock = function(skuNumber) {
    return $j(".jq_AddToCart_" + skuNumber + " .jq_WishListAnswer");
}
AddToWishList.GetWaitBlock = function(skuNumber) {
    return $j(".jq_AddToCart_" + skuNumber + " .jq_WishListWaitBlock");
}

AddToWishList.HideAnswerPanel = function(skuNumber) {
    AddToWishList.GetAnswerBlock(skuNumber).css("display", "none");
}

UserStatus = function() { }

UserStatus.Get = function(url)
{
	var result;
	$j.ajax({
		type: "POST",
		url: url,
		async: false,
		data: { },
		success: function(answer) {
			result = answer.IsRegistered;
		},
		error: function(answer) {
			result = false;
		},
		dataType: "json"
	});
	return result;
}

/*--- AjaxPopup.js ---*//* Used triggers:
        AjaxPopup.ErrorPopupsClosed
*/

AjaxPopup = function() { };

/* Client settings of partial render views (see RegisterPartialRenderView on server side) */
AjaxPopup.Settings = function() { };
AjaxPopup.Settings.Login = function() { return { ViewId : 'ucLoginPopupView', Cached : '1' }; };


AjaxPopup.IdBySetting = function(setting) {
    if (!AjaxPopup.CheckSetting(setting)) { return false; }
    return AjaxPopup.GetId(setting.ViewId, null);
};
AjaxPopup.OpenBySetting = function(setting) {
    if (!AjaxPopup.CheckSetting(setting)) { return false; }
    return AjaxPopup.Open(null, setting.ViewId, setting.Cached); 
};
AjaxPopup.CloseBySetting = function(setting) {
    if (!AjaxPopup.CheckSetting(setting)) { return false; }
    return AjaxPopup.Close(null, setting.ViewId, setting.Cached, null);
};
AjaxPopup.CheckSetting = function(setting) {
    return !(setting.ViewId == null || setting.ViewId == undefined ||
             setting.Cached == null || setting.Cached == undefined);
};
AjaxPopup.CloseCachedByLastOpened = function() {
    AjaxPopup.Close(null, AjaxPopup.LastOpened(), '1', null);
};

AjaxPopup.GetId = function(viewId, hashCode) {
    var id = viewId;
    if(hashCode) {
        id += hashCode;    
    }     
    if(id.indexOf('jq_') != 0) {   
        id = 'jq_' + id;           
    }
    return id;
};

AjaxPopup.IsAlreadyCachedBySetting = function(setting) {
    if (!AjaxPopup.CheckSetting(setting)) { return false; }
    var id = AjaxPopup.GetId(setting.ViewId, null);
    return (setting.Cached == '1' && $j('.' + id).length != 0);
};

AjaxPopup.Open = function(e, viewId, cached, args, hashCode) {        
    var id = AjaxPopup.GetId(viewId, hashCode);
    if(cached == '1' && $j('.' + id).length != 0)
    {
        $j('.' + id).show();
        AjaxPopup.LastOpenedUpdate(id, AjaxPopup.LastOpenedActions.Open);
    }
    else
    {   
        var popup = '<div class="popupPosition">' +                    
                    '<div style="display: block; visibility: visible;" class="modalBackground"></div>' +                    
                    '<div style="display: block;" class="popupPanelContainer"></div>'+
                    '</div>';

        var popupControl = $j('<div class="popups ' + id + '"></div>').html(popup);
        var selector = $j('#wrap').length == 0 ? 'body' : '#wrap';
        $j(selector).append(popupControl);
        $j('body').css({ 'cursor': 'wait' });
    
        window.popup = id;
    
        var data = ( args != null ) ? {args: args } : { };
        $j.ajax({
            url: Config.PartialHandlerUrl() + "?view=" + viewId,
	        dataType: 'html',	        
	        type: "POST",
	        data: data,
	        async: false,
	        success: function(html) {
	            AjaxPopup.LastOpenedUpdate(id, AjaxPopup.LastOpenedActions.Open);	            
	            $j('.' + window.popup + ' .popupPanelContainer').html(html);
	            $j('body').css({ 'cursor': 'default' });
            },
	        error: function showError(xhr, status, exc) {
	            $j('.popups.' + id).remove();
	            AjaxPopup.ErrorPopupOpen();
	            $j('body').css({ 'cursor': 'default' });
            }
        });
    }
    
    return false;
};

AjaxPopup.Close = function(e, viewId, cached, hashCode) {
    var id = AjaxPopup.GetId(viewId, hashCode);
    if(cached == '1') {
        if (e == null) { $j('.' + id).hide(); }
        else { $j(e).parents('.' + id).eq(0).hide(); }
    }
    else { 
        $j(e).parents('.' + id).eq(0).remove();
    }
    AjaxPopup.LastOpenedUpdate(id, AjaxPopup.LastOpenedActions.Close);    
    return false;           
};



AjaxPopup.GetErrorPopupClass = function() { return "error-msg-popup"; };

AjaxPopup.isErrorPopupsOpen = function() {
    return ($j('.' + AjaxPopup.GetErrorPopupClass()).length > 0);
};

AjaxPopup.ErrorPopupOpen = function(title, body) {
    
    if (title == null || title == undefined) {
    	title = 'Oops!';
    }
    if (body == null || body == undefined) {
    	body = 'Our server encountered a temporary error and could not complete your request. Please try again in 30 seconds';
    }
    
    var content = '<div id="popup" class="popup-cont brand forms cant fixed-pos" style="z-index:10000;">' +
		            '<div class="top-line top-shade"><span class="c-l"/><span class="c-r"/></div>' +
			            '<div class="rgt-shade"><div class="lft-shade"><div class="content">' +
					        '<div class="b-header">' +
						        '<span>$Title$</span>' +
						        '<a href="#" id="closeBtn">Close</a>' +
						        '<div class="clr"/>' +
                            '</div>' +
                            '<div class="clr hgt10" />' +
					        '<div class="up-cont"><p class="notif-n">$Body$</p></div>' +
					        '<div class="clr hgt10"/>' +
					        '<div class="b-footer">' +
						        '<a class="btn blue-small" href="#"><span><span>Done</span></span></a>' +
                                '<div class="c-lft"/>' +
                            '</div>'+
			            '</div></div></div>' + 
		            '<div class="bot-line bot-shade"><span class="c-l"/><span class="c-r"/></div></div>';

    content = content.replace('$Title$', title).replace('$Body$', body);
    
    var popup = '<div class="popupPosition">' +
                '<div style="display: block; visibility: visible;" class="modalBackground"></div>' +                
                '<div style="display: block;" class="popupPanelContainer">' + content +  '</div>' +
                '</div>';

    var popupControl = $j('<div class="popups ' + AjaxPopup.GetErrorPopupClass() + '"></div>').html(popup);
    var selector = $j('#wrap').length == 0 ? 'body' : '#wrap';
    $j(selector).append(popupControl);
    
    var onClose = function() { 
        $j(popupControl).remove();
        if (!AjaxPopup.isErrorPopupsOpen()) {
            $j(document).trigger("AjaxPopup.ErrorPopupsClosed"); 
        }
        return false; 
    }
    
    $j(popupControl).find('#closeBtn').click(onClose);
    $j(popupControl).find('.blue-small').click(onClose);
    return false;
};


/* LastOpened */
AjaxPopup.LastOpened = function () {
    if(window.AjaxPopupWindows != null && window.AjaxPopupWindows != undefined) {
        return window.AjaxPopupWindows[window.AjaxPopupWindows.length - 1];  
    }
    return '';  
};
AjaxPopup.LastOpenedActions = { "Open": 1, "Close": 2 };
AjaxPopup.LastOpenedUpdate = function(id, action) {
    if(!window.AjaxPopupWindows)
        window.AjaxPopupWindows = new Array();

    if (action == AjaxPopup.LastOpenedActions.Open) {
		window.AjaxPopupWindows.push(id);
	}
	else if (action == AjaxPopup.LastOpenedActions.Close) {
		for(var i=0; i<window.AjaxPopupWindows.length;i++ ) { 
            if(window.AjaxPopupWindows[i] == id)
                window.AjaxPopupWindows.splice(i,1); 
        }
	}	
	for(var i=0; i<window.AjaxPopupWindows.length;i++ ) { 
        $j('.' + window.AjaxPopupWindows[i] + ' .modalBackground').css({ 'display': (i==window.AjaxPopupWindows.length-1 ? 'block' : 'none') });
    }
};
/*--- AjaxView.js ---*//*
  Ajax view renderer
*/

AjaxView = function() { };

AjaxView.Load = function(e, viewId, args) {
  var data = (args != null) ? { args: args} : {};
  $j('body').css({ 'cursor': 'wait' });
  $j.ajax({
    url: Config.PartialHandlerUrl() + "?view=" + viewId,
    dataType: 'html',
    type: "POST",
    data: data,
    async: false,
    success: function(result) {
      var container = args ? '#' + args : 'body';
      $j(container).html(result);
      $j('body').css({ 'cursor': 'default' });
    },
    error: function showError(xhr, status, exc) {
      AjaxPopup.ErrorPopupOpen();
      $j('body').css({ 'cursor': 'default' });
    }
  });
  return false;
};
/*--- Badge.js ---*//*-------- Badge -------*/
Badge = function() { }

Badge.OnOver = function(a, labelId) {
	var parent = $j(a).parents('.badge');
	var infoDiv = parent.find('.dot');
	if (infoDiv.length == 0) {
		var message = TranslationHelper.GetTranslation(labelId);
		infoDiv = $j("<div class='dot'><span class='invoke-panel'><span class='invoke-bg'>" + message + "</span></span></div>");
		parent.eq(0).append(infoDiv);
	}
	infoDiv.css('display', 'block');
}

Badge.OnOut = function(a) {
	var parent = $j(a).parents('.badge');
	var infoDiv = parent.find('.dot');
	if (infoDiv.length > 0) {
		infoDiv.css('display', 'none');
	}
}
/*--- ClientApi.js ---*//// <reference path="jquery.vsdoc.js" />
$j = jQuery.noConflict();

als = function() { }
als.call = function(param) {
    result = false;
    $j.ajax({
        type: "POST",
        data: param,
        timeout: 5000,
        url: Config.ClientApiHandlerUrl(),
        success: function(e) { result = e.result; },
        error: function() {},
        async: false,
        dataType: "json"
    });
    return result;
}

// shopping cart api
als.cart = function() { }
als.cart.hasPixItemsOnly = function() { return als.call({ method: "hasPixItemsOnly" }); }
als.cart.hasGeneralItemsOnly = function() {return als.call({ method: "hasGeneralItemsOnly" });}
als.cart.hasGeneralAndPixItems = function() {return als.call({ method: "hasGeneralAndPixItems" });}
als.cart.hasPixItem = function(name) {return als.call({method: "hasPixItem", name: name});}

/* coockie name where message selector is stored */
als.cart.coockieSelectorName = "ABFlag";

/* get a value from coockie easily */
als.cart.getFromCoockie = function(coockieName) {
  if (document.cookie.length > 0) {
    var start = document.cookie.indexOf(coockieName + "=");
    if (start != -1) {
      start = start + coockieName.length + 1;
      var end = document.cookie.indexOf(";", start);
      if (end == -1) end = document.cookie.length;
      return unescape(document.cookie.substring(start, end));
    }
  }
  return "";
}

/* default message condition */
als.cart.abMessageCondition = function() {
  return parseInt((als.cart.coockieSelectorName)) < 50;
}

/* log message */
als.cart.log = function(message) {
  _gaq.push(['_trackEvent', 'log', message]);
}

/*
* @description: shows different message areas
* depending on condition
* @param condition: bool
* @param showIfTrue: message container #id (shoown if true)
* @param showIfFalse: message container #id (shoown if false)
* @returns message container #id that was shown 
*/
als.cart.switchMassage = function(condition, container, showIfTrue, showIfFalse) {
  if (container) {
    var iftrue = $j(showIfTrue, container);
    var iffalse = $j(showIfFalse, container);
  }
  else {
    var iftrue = $j(showIfTrue);
    var iffalse = $j(showIfFalse);
  }
  if (condition) {
    iftrue.show();
    iffalse.hide();
    return iftrue;
  }
  else {
    iftrue.hide();
    iffalse.show();
    return iffalse;
  }
}

/*
* @description: switch message wrapper
* @parameters:
* @ condition : function name (bool)
* @ iftrue : message #id to show if true
* @ iffalse : message #id to show if false
* @ log : a text to log throw ga
*/
als.cart.selectMessage = function(args) {
  var condition = args['condition'];
  var container = args['container'];
  var iftrue = args['iftrue'];
  var iffalse = args['iffalse'];
  var iflog = args['log'];
  var conditionResult = condition();
  var msg = als.cart.switchMassage(conditionResult, container, iftrue, iffalse);
  if (iflog)
    als.cart.log(msg);
}
/*--- ClientCaching.js ---*/

ClientCaching = function() { }

ClientCaching.setup = function() {


	// Get all als-async-load divs values
	// Create array of params args='...'
	// Send ajax request
	// get response
	//check version
	// Loop through the array and assign html for div

	var args = 'args=';

	$j('[als-async-load]').each(function() {
		var self = $j(this);
		var arg = self.attr('als-async-load');
		args += arg + ';';
	});
	if (args.length > 5)
		args = args.substring(0, args.length - 1);

	$j.ajax({
		url: Config.PartialCachingUrl() + '?' + args + '&type=headermenu' + '&version=' + Config.Version(),
		type: "POST",
		dataType: "json",
		async: true,
		data: {},
		success: function(result) {
			//result = eval('d=' + result);
			var len = result.Items.length;
			for (var i = 0; i < len; i++) {
				var item = result.Items[i];
				var selector = '[als-async-load=' + item.Tab + ',' + item.Menu + ']';
				if ($j(selector).attr('loaded') != 'done') {
					$j(item.Html).appendTo(selector);
					$j(selector).attr('loaded', 'done');
				}
			}
		},
		error: function(req, status, e) {

		},
		complete: function(result) {
		}
	});

}




/*--- Config.js ---*/Config = function() { }
Config.CartSummaryHandler = function() { return "http://www.adorama.com/Als/CartSummaryPage.aspx"; }
Config.EmailSubscribeHandler = function() { return "http://www.adorama.com/als/EmailSubscribeHandler.ashx"; }
Config.ContentLoaderHandler = function() { return "http://www.adorama.com/als/ContentLoaderHandler.ashx"; }
Config.PhoneNumberHandler = function() { return "http://www.adorama.com/als/PhoneNumber.aspx"; }
Config.WebcollageUrl = function() { return "http://content.webcollage.net/adorama/smart-button?ird=true&channel-product-id="; }
Config.GetSettingFromHidden = function(name) { return $j('#_' + name).val(); }

Config.CartViewUrlWithSkuParam = function() { return Config.GetSettingFromHidden('CartViewUrlWithSkuParam'); }
Config.RebateTabAnchor = function() { return Config.GetSettingFromHidden('RebateTabAnchor').toLowerCase(); }
Config.UsedTabAnchor = function() { return Config.GetSettingFromHidden('UsedTabAnchor').toLowerCase(); }
Config.OverviewTabAnchor = function() { return Config.GetSettingFromHidden('OverviewTabAnchor').toLowerCase(); }
Config.WaysToSaveTabAnchor = function() { return Config.GetSettingFromHidden('WaysToSaveTabAnchor').toLowerCase(); }
Config.AddToWishListHandler = function() { return Config.GetSettingFromHidden('AddToWishListHandler'); }
Config.ForgotPasswordHandler = function() { return Config.GetSettingFromHidden('ForgotPasswordHandler'); }
Config.IsUserRegisteredHandler = function() { return Config.GetSettingFromHidden('IsUserRegisteredHandler'); }
Config.AddToCardHandler = function() { return Config.GetSettingFromHidden('AddToCardHandler'); }
Config.ReviewsVisibleForUsed = function() { return Config.GetSettingFromHidden('ReviewsVisibleForUsed'); }
Config.ReviewTabAnchor = function() { return Config.GetSettingFromHidden('ReviewTabAnchor'); }
Config.IsUsedProduct = function() { return Config.GetSettingFromHidden('IsUsedProduct'); }
Config.SendGiftCertUrl = function() { return Config.GetSettingFromHidden('SendGiftCertUrl'); }
Config.InStoreOnlyText = function() { return Config.GetSettingFromHidden('InStoreOnlyText'); }
Config.ClientApiHandlerUrl = function() { return Config.GetSettingFromHidden('ClientApiHandlerUrl'); }
Config.HotProductsUrl = function() { return Config.GetSettingFromHidden('HotProductsUrl'); }
Config.GetTranslationUrl = function() { return Config.GetSettingFromHidden('GetTranslationUrl'); }
Config.PartialHandlerUrl = function() { return Config.GetSettingFromHidden('PartialHandlerUrl'); }
Config.Version = function() { return Config.GetSettingFromHidden('Version'); }
Config.PartialCachingUrl = function() { return Config.GetSettingFromHidden('PartialCachingUrl'); }
Config.SignInHandler = function() { return Config.GetSettingFromHidden('SignInHandler'); }
Config.CreateAccountHandler = function() { return Config.GetSettingFromHidden('CreateAccountHandler'); }
Config.AlsRoot = function() { return Config.GetSettingFromHidden('AlsRoot'); }

/*--- ContentLoader.js ---*/ContentLoader = function() {
	var handler = Config.ContentLoaderHandler();

	ContentLoader.prototype.LoadAll = function() {
		$j("[jsLoad='HotProduct']").each(function() {
			AjaxPostAndParseTemplate('HotProduct', HotProductTemplate, this);
		});

		$j("[jsLoad='RRProduct']").each(function() {
			AjaxPostAndGetPage('RR_RecommendationPlacement', this);
		});
	}

	AjaxPostAndGetPage = function(type, control) {
		var argsdata = $j(control).attr('rr_data');
		$j.ajax({
			url: Config.PartialHandlerUrl() + "?view=" + type + "&args=" + argsdata,
			dataType: 'html',
			type: "POST",
			data: '',
			async: false,
			success: function(html) {
				/* should be changed to many elements */
				var rr_element = $j("[jsLoad='RRProduct']");
				if (rr_element.size()> 1) {
					rr_element.eq(0).html(html);
				} else {
					rr_element.html(html);
				}
			},
			error: function showError(xhr, status, exc) {
			}
		});
	}

	AjaxPostAndParseTemplate = function(type, template, item) {
		var random_class = 'random_' + Math.random().toString().replace('.', '');
		$j(item).addClass(random_class);

		var argsAttr = $j(item).attr('jsLoadArgs');
		var args = (argsAttr && argsAttr != 'undefined') ? argsAttr : '';

		$j.ajax({
			type: "POST",
			url: handler,
			async: true,
			data: { type: type, args: args, element: '.' + random_class },
			success: function(r) {
				var items = eval(r.Items);
				for (var i = 0; i < items.length; i++) {
					var p = items[i];
					var html = template
                        .replace(/\{Price\}/g, p.Price)
                        .replace(/\{ImgAlt\}/g, p.ImgAlt)
                        .replace(/\{ImgSrc\}/g, p.ImgSrc)
                        .replace(/\{ProductName\}/g, p.ProductName)
                        .replace(/\{ProductUrl\}/g, p.ProductUrl);

					$j(r.Element).append(html);
				}
			},
			error: function(r) { },
			dataType: "json"
		});
	}

	var HotProductTemplate = '<div class="product">' +
                                '<div class="add-cart-small">' +
                                    '<div class="price-cont"><strong>{Price}</strong></div>' +
                                '</div>' +
                                '<div class="about-product">' +
                                    '<div class="about-product-lft"><a href="{ProductUrl}"><img class="no-border" alt="{ImgAlt}" src="{ImgSrc}"/></a></div>' +
                                    '<a class="h5" href="{ProductUrl}">{ProductName}</a>' +
                                '</div>' +
                                '<div class="clr">&nbsp;</div>' +
                             '</div>';
}

ContentLoader.Load = function() {
    var loader = new ContentLoader();
    loader.LoadAll();
}

/*--- dropDownList.js ---*/var dropShow=new Object();
var selectId;
var oldMouseDownMethod;

function dropdown(clientId)
{
	if(!dropShow[clientId])
		dropShow[clientId] = false;
	if(dropShow[clientId])
	{
		dropFadeOut(clientId);
	}
	else
	{
		currentID=document.getElementById(clientId);
		if(currentID == null)
			return;
		currentID.style.visibility="visible";
		dropFadeIn(clientId);
	}
}

function dropFadeIn(clientId)
{
	currentID=document.getElementById(clientId);
	if(currentID == null)
		return;
	if(currentID.filters)
	{
		opacityParent = currentID.filters.alpha;
		coeff = 1;
	}
	else
	{
		opacityParent = currentID.style;
		coeff = 100;
	}

	if(opacityParent.opacity<100/coeff)
	{
		opacityParent.opacity=parseFloat(opacityParent.opacity)+100/coeff;
		selectId = clientId;
		oldMouseDownMethod = jQuery("body")[0].onmousedown;
		jQuery("body")[0].onmousedown = processMouseClick;
	}
	else
	{
		dropShow[clientId]=true;
	}
}

function processMouseClick(e)
{
	if(window.event != null)
	{
		if(window.event.srcElement.id == selectId || window.event.srcElement.parentNode.id == selectId)
			return;
	}
	else
	{
		if(e.target.id == selectId || e.target.parentNode.id == selectId)
			return;
	}
	dropFadeOut(selectId);
	jQuery("body")[0].onmousedown = oldMouseDownMethod;
}


function dropFadeOut(clientId)
{//select box fade out
	currentID=document.getElementById(clientId);
	if(currentID == null)
		return;
	if(currentID.filters)
	{
		opacityParent = currentID.filters.alpha;
		coeff = 1;
	}
	else
	{
		opacityParent = currentID.style;
		coeff = 100;
	}
	if(opacityParent.opacity>0)
	{
		opacityParent.opacity=parseFloat(opacityParent.opacity)-100/coeff;
		dropShow[clientId]=false;
		currentID.style.visibility="hidden";
	}
	else
	{
		dropShow[clientId]=false;
		currentID.style.visibility="hidden";
	}
}

function checkme(dropDownId, clientId, textId)
{
	currentID=document.getElementById(clientId);
	if(currentID == null)
		return;
	var index=currentID.selectedIndex;
	document.getElementById(textId).value=currentID.options.item(index).innerHTML;
	dropdown(clientId);
	dropFadeOut(clientId);
	//setTimeout("__doPostBack('" + dropDownId + "', '');", 0);
}
/*--- EmailSubscribe.js ---*/var $js = jQuery.noConflict();
EmailSubscribe = function(parentSelection) {
  var handler = Config.EmailSubscribeHandler();

  var isLoaded = false;
  this.GetIsGroupLoaded = function() { return isLoaded; }
  this.SetIsGroupLoaded = function(value) { isLoaded = value; }

  EmailSubscribe.prototype.Render = function() {
    var template = '<h4 class="subscr">' +
                            'Email Subscriptions<br /><span>Sign up for exclusive deals.</span>' +
                        '</h4>' +
                        '<div class="clr"></div>' +
                        '<div class="signin-form">' +
                            '<label>Email Address:</label>' +
                            '<div class="c-lft"></div>' +
                            '<input type="text" value="" id="email" />' +
                            '<a id="subscribe_btn" href="javascript:void(0);" class="btn blue-small"><span><span>Sign Up</span></span></a>' +
                            '<div class="c-lft"></div>' +
                            /*'<a id="more" href="javascript:void(0);">More Newsletters</a>&nbsp;|&nbsp;' + */
                            '<a target="_blank" href="http://www.adorama.com/catalog.tpl?op=FAQ#Our Privacy Policy">Privacy Policy</a>' +
                            '<div class="clr"></div>' +
                            '<div class="message" style="display:none;"></div>' +
                            '<div class="error" style="display:none;"></div>' +
                        '</div>' +
                        '<div class="clr"></div>' +
                        '<div class="subscribe_group" style="display:none;"></div>';
    $js(parentSelection).append(template);
    $js(parentSelection + ' a[id="subscribe_btn"]').bind("click", { object: this }, this.SubscribeClick);
    $js(parentSelection + ' a[id="more"]').bind("click", { object: this }, this.MoreClick);
  }

  this.GetEmailValid = function(highlight) {
    var emailInput = $js(parentSelection + ' input[type="text"]');
    var email = emailInput.val();
    var isValid = (email && email != '' && email != 'undefined' && Validator.isNotEmail(email) == false);
    if (highlight) {
      if (isValid) {
        emailInput.removeClass('highlight');
      }
      else {
        emailInput.addClass('highlight');
      }
    }
    return { Email: email, IsValid: isValid };
  }

  this.SubscribeClick = function(e) {
    var emailAddress = e.data.object.GetEmailValid(true);
    var email = emailAddress.Email;
    if (emailAddress.IsValid) {
      var container = $js(parentSelection + ' .subscribe_group');
      var groups = new Array();
      if (e.data.object.GetIsGroupLoaded() == true) {
        var checkboxes = $js(parentSelection + ' .subscribe_group input[type="checkbox"]');
        for (var i = 0; i < checkboxes.length; i++) {
          if (checkboxes.eq(i).attr('checked') == true) {
            var groupId = checkboxes.eq(i).attr('groupId');
            groups.push('"' + groupId + '"');
          }
        }
        container.hide();
      }
      var obj = '{ "Email": "' + email.toString() + '", "Groups": [' + groups.join(',') + ']}';
      e.data.object.SendAjaxRequest('subscribe', obj,
                function(r) {
                  $js(parentSelection + ' input[type="text"]').val('');
                  if (r.Message == "ok") {
                    e.data.object.ShowSuccess(email);
                  }
                  else {
                    e.data.object.ShowError();
                  }
                },
                function(r) {
                  e.data.object.ShowError();
                });
    }
  }

  this.ShowSuccess = function(email) {
    var name = email.toString().substring(0, email.indexOf('@'));
    var msg = '<strong>Thank you {name}!</strong><br />Email {email} has been added to our email list.'
      .replace('{email}', email)
      .replace('{name}', name);

    $js(parentSelection + ' .message').html(msg);
    $js(parentSelection + ' .message').show('slow');
    $js(parentSelection + ' .error').html('');
    $js(parentSelection + ' .error').hide();

    setTimeout(function() {
      $js(parentSelection + ' .message').hide('slow');
      }, 5000);
  }

  this.ShowError = function() {
    $js(parentSelection + ' .message').html('');
    $js(parentSelection + ' .message').hide();
    $js(parentSelection + ' .error').html('Error');
    $js(parentSelection + ' .error').show('slow');

    setTimeout(function() {
      $js(parentSelection + ' .error').hide('slow');
      }, 5000);
  }

  this.MoreClick = function(e) {
    var container = $js(parentSelection + ' .subscribe_group');
    if (e.data.object.GetIsGroupLoaded() == false) {
      e.data.object.SendAjaxRequest('more', '',
                function(r) {
                  var groups = eval(r);
                  var html = '<div><input type="checkbox" /><label></label></div>';

                  for (var i = 0; i < groups.length; i++) {
                    var id = 'group' + i.toString();
                    var group = groups[i];

                    container.append(html);
                    var item = container.children('div').eq(i);

                    var checkbox = item.children('input[type="checkbox"]');
                    checkbox.attr('id', id);
                    checkbox.attr('groupId', groups[i].Id);
                    if (groups[i].IsDefault)
                      checkbox.attr('checked', 'checked');

                    var label = item.children('label');
                    label.attr('for', id);
                    label.html(groups[i].Title);
                  }
                  e.data.object.SetIsGroupLoaded(true);
                  container.show("slow", 500);
                },
                function(r) {
                  /* error */
                });
    }
    else {
      container.toggle("slow");
    }
  }

  this.SendAjaxRequest = function(type, args, successCallback, errorCallback) {
    var obj = this;
    $js.ajax({
      type: "POST",
      url: handler,
      async: true,
      data: { type: type, args: args },
      success: function(r) { obj.Execute(successCallback, r) },
      error: function(r) { obj.Execute(errorCallback, r); },
      dataType: "json"
    });
  }

  this.Execute = function(callback, args) {
    if (callback && typeof (callback) == 'function') {
      callback(args);
    }
  }
}            

/*--- EmbeddedPopup.js ---*/
EmbeddedPopup = function() {}

EmbeddedPopup.Show = function(sender) {
    var embedded = $j(sender).parent().find('pre').html();
    if (embedded && embedded != '') {
        var popup = '<div class="popupPosition closeClass">' +
'<div class="modalBackground" style="visibility: visible; display: block;"></div>' +
	'<div class="UsedPopupInformation" style="top:50%;">' +
	                '<div class="popup-cont brand popup-profile flash">' +
						'<div class="b-header">' +
							'<span></span>' +
							'<a ID="CloseButton" >Close</a>' +
							'<div class="clr"></div>' +
						'</div>' +
						'<div class="clr hgt10"></div>' +
						'<div class="up-cont">' +
						'<p class="notif-n">' + embedded + '</p>' +
					'</div>' +
    '</div>' +
'</div>';

        var popupControl = $j('<div class="popups"></div>').html(popup);
        $j('body').append(popupControl);
        $j('.closeClass #CloseButton').click(function() { $j('.closeClass').remove(); });

    }
    return false;
}
/*--- fader.js ---*/var faderConfig = 
	{
		bg_container: 'div',
		popup_container: 'span', popup_position: 'link-related',
		popup_top: -32, popup_left: 120,
		elements: 'div.prompt-cont a'
	};

var activeFader = -1;
var activeLink = null;

var overFader = false;
var overLink = false;

function initFaders()
{
	if (faderConfig.length < 1)
		return;
	$j(faderConfig.elements).attr("faderIndex", 0).bind('mouseover', showFader).bind('mouseout', hideFader);
}

function showFader(e)
{
	overLink = true;

	var faderid = $j(this).attr('faderid');
	if (faderid == undefined) return;

	var fader = $j(faderConfig.bg_container + '[faderid=' + faderid + ']');
	var popup = $j(faderConfig.popup_container + '[faderid=' + faderid + ']');
	
	if (fader.length && popup.length){
		popup.css({
			'display': 'block',
			'visibility': 'hidden',
			'position': 'absolute'
		});
		
		popup.parent().bind('mouseover', function(){
			overFader = true;
		});
		
		popup.parent().bind('mouseout', function(){
			overFader = false;
			setTimeout('hideFaderOut()', 100);
		});

		activeLink = this;
		activeFader = 0;

		fader_set_popup_position(popup, faderConfig.popup_position, faderConfig.popup_top, faderConfig.popup_left);
	}
}

function hideFader(e)
{
	overLink = false;
	setTimeout('hideFaderOut()', 100);
}

function hideFaderOut(){
	if(activeFader <= -1) return;
	
	var faderid = $j(activeLink).attr('faderid');
	if (faderid == undefined) return;
	
	var fader = $j(faderConfig.bg_container + '[faderid=' + faderid + ']');
	var popup = $j(faderConfig.popup_container + '[faderid=' + faderid + ']');
	if (fader && popup){
		if (!overFader && !overLink){
			popup.css('display', 'none');
			activeFader = -1;
			activeLink = null;
		}
	}
}

function fader_set_popup_position(popup, popup_position, popup_top, popup_left) {
	var screenW = $j(window).width();
	var screenH = $j(window).height();
	var popupW = popup.width();
	var popupH = popup.height();
	
	var popupStyles = {};
	switch(popup_position){
		case 'none':
			break;
		case 'centered':
			popupStyles.top = (screenH - popupH) / 2;
			popupStyles.left = (screenW - popupW) / 2;
			break;
		case 'link-related':
			popupStyles.top = $j(activeLink).offset().top + popup_top;
			popupStyles.left = $j(activeLink).offset().left + popup_left;
			break;
		case 'absolute':
			popupStyles.top = popup_top;
			popupStyles.left = popup_left;
			break;
	}
	
	popupStyles.visibility = 'visible';
	popup.css(popupStyles);
}
/*--- formChecker.js ---*/var $j = jQuery.noConflict();
$j(document).ready(function() {
    KeyListener.init();
    progressBar.Init();
    initFaders();
   /* $j.Watermark.PrepareSubmit(); */

    var requestManager = Sys.WebForms.PageRequestManager.getInstance();
    /* begin request */
    requestManager.add_beginRequest(function(sender, args) {
        Sys.WebForms.PageRequestManager.getInstance()._scrollPosition = null;
        window.progress.BeginRequest();
    });
    /* end request */
    requestManager.add_endRequest(function(sender, args) {
        window.progress.EndRequest();
        progressBar.Init();
        initFaders();
        KeyListener.init();
        $j('#up_container').animate({ opacity: 'toggle' }, 5020);
        /* $j.Watermark.PrepareSubmit(); */
    });
});

progressBar = function() {
  var _formCheckForm = null;
  this.get_FormCheckForm = function() {
    if (!_formCheckForm) { _formCheckForm = []; }
    return _formCheckForm;
  };

  var _summaryCheckForm = null;
  this.get_SummaryCheckForm = function() {
    if (!_summaryCheckForm) { _summaryCheckForm = []; }
    return _summaryCheckForm;
  };

  var _isLoadingNow = false;
  this.get_IsLoadingNow = function() { return _isLoadingNow; };
  this.set_IsLoadingNow = function(value) { _isLoadingNow = value; };

  var _prevElement = null;
  this.get_PrevElement = function() { return _prevElement; };
  this.set_PrevElement = function(value) { _prevElement = value; };

  /* Change History Begin */
  var _h = new Object();
  this.addHistory = function(form, name, value) {
    if (form && name && form != '' && name != '') {
      if (!_h[form] || _h[form] == "undefined") _h[form] = new Object();
      _h[form][name] = value;
    }
  }
  this.getHistroy = function(form, name) {
    if (!_h[form] || _h[form] == "undefined") return null;
    return _h[form][name];
  }
  this.clearHistory = function(form) {
    if (_h[form] || _h[form] == "undefined")
      _h[form] = null;
  }

  this.changeHistory = function(form) {
    this.clearHistory(form);
    var inputs = this.GetAllInputElements(form);
    for (var i = 0; i < inputs.length; i++) {
      this.addHistory(form, inputs[i].id, inputs[i].value);
    }
  }
  this.isHistoryChange = function(form) {
    var inputs = this.GetAllInputElements(form);
    for (var i = 0; i < inputs.length; i++) {
      var curr = inputs[i].value;
      var prev = this.getHistroy(form, inputs[i].id);

      if (prev == null) return false;
      if (curr != prev) return true;
    }
    return false;
  }
 
  this.GetAllInputElements = function(form) {
    return $j("#" + form).find("input:text, input:file, input:checkbox, input:radio, select, textarea");
  }
  /* Change History End */

  /* PostBack Query Begin */
  var _Query;
  this.pushQuery = function(element) {
    if (!_Query) _Query = new Array();
    _Query.push(element);
  }
  this.popQuery = function() {
    return _Query ? _Query.shift() : null;
  }
  /* PostBack Query End */

  progressBar.prototype.Initialize = function() {
    $j("input:text, input:file, input:password, textarea").bind("focus", { object: this }, this.elementActivated);
    $j("a, input:button, input:submit, input:radio, input:checkbox").bind("click", { object: this }, this.elementActivated);
    $j("select").bind("change", { object: this }, this.elementActivated );
  }
  progressBar.prototype.AddForm = function(area) {
    this.get_FormCheckForm().unshift(area);
    this.changeHistory(area);
  }
  progressBar.prototype.AddSummaryForm = function(summary) {
    this.get_SummaryCheckForm().unshift(summary);
    $j("#" + summary).bind("mouseover", { object: this }, this.summaryActivated);
    /*$j("#" + summary).bind("mousemove", {object: this}, this.summaryActivated);*/
  }

  progressBar.prototype.summaryActivated = function(event) {
    event.data.object.elementActivated(event);
  }
  progressBar.prototype.elementActivated = function(event) {
    if ((event.srcElement == null || event.srcElement == "undefined") &&
           (event.currentTarget == null || event.currentTarget == "undefined")) return;

    var eventElement = (event.srcElement != null) ? event.srcElement : event.currentTarget;
    var currArea = event.data.object.getFormByElement(eventElement.id);
    var prev = event.data.object.get_PrevElement();

    if (prev && prevArea != 'undefined') {
      var prevArea = event.data.object.getFormByElement(prev.id);
      if (prevArea != currArea) {
        event.data.object.saveForm(event.data.object, prevArea, this.id);
        event.data.object.changeHistory(prevArea);
      }
    }
    else
    {
			var forms = event.data.object.get_FormCheckForm();
			for(var i = 0; i < forms.length; i++)
			{
				if(event.data.object.isHistoryChange(forms[i]))
				{				
					event.data.object.saveForm(event.data.object, forms[i], this.id);
					event.data.object.changeHistory(forms[i]);
				}
			}
		}
    event.data.object.set_PrevElement(eventElement);
  }
  
  var focused;
  
  progressBar.prototype.saveForm = function(obj, prevArea, postBackElementId) { 
		focused = postBackElementId;
  
    if (obj.isHistoryChange(prevArea)) {
      /* hidden button must be server control 'Button' with UseSubmitBehavior="false" */
      var hiddenButton = $j("#" + prevArea).find(".hiddenButton");
      if (hiddenButton.length != 0) {
				if(postBackElementId != 'undefined')
				{
					var postBackElement = $j("#" + postBackElementId);
					if (postBackElement.length != 0) {
						var script = postBackElement[0].onclick ? postBackElement[0].onclick.toString() : postBackElement[0].toString();
						if (script.indexOf("__doPostBack") != -1 || script.indexOf("_DoPostBack") != -1) {
							script = script.toString().replace("function anonymous()", "").replace("\n", "").replace("\n", "").replace("\n", "").replace("{", "").replace("}", "");
							obj.pushQuery(script);
						}
					}
				}
        try 
        { 
					for(var i = 0; i < hiddenButton.length; i++)
						hiddenButton[i].onclick.call(); 
        }
        catch (e) { }
      }
    }
  }

  progressBar.prototype.getFormByElement = function(elementId) {
    var forms = this.get_FormCheckForm();
    if (elementId != '') {
      for (var i = 0; i < forms.length; i++) {
        if ($j("#" + forms[i]).find("#" + elementId).length != 0) { return forms[i]; }
      }
    }
    return null;
  };

  progressBar.prototype.BeginRequest = function() {
    //$j("input:text").unmask();
    window.progress.set_IsLoadingNow(true);
    if ($j(".invisible").length == 0) {
      $j(document.body).prepend("<div class='invisible'><div class='invWait'>&nbsp;</div></div>");
      $j(".invisible").bind("click", { object: this }, function() { return false; });
    }
    $j("body").bind('keypress', function(e) { return false; });
    $j("body").bind('keydown', function(e) { return false; });
    $j("input, select, a").bind('focus', function(e) { return false; });
  }

  progressBar.prototype.EndRequest = function() {
    var historyElement = this.popQuery();
    if (historyElement) {
      try { eval(historyElement); }
      catch (e) { }
    }
    else {
      $j(".invisible").css("display", "none");
      $j(".invisible").remove("");

      $j("body").unbind('keypress');
      $j("body").unbind('keydown');
      $j("input, select, a").unbind('focus');
      
      if(focused)
      {    
				var allowFocus = $j('#' + focused).is('input:text, input:password, textarea, select'); 
				if(allowFocus == true) 
				{				
					var focusedElement = $j('#' + focused);
					
					var timer = setTimeout(function() {
							clearTimeout(timer);
							var value = focusedElement.val();
							focusedElement.focus().val(value);
						}, 1000);
				}
				focused = null;
      }
      $j("input:text[mask_attr]").each(function() {
        var mask = $j(this).attr('mask_attr');
        var isSet = $j(this).attr('mask_attr_set');
        if(mask && mask != 'undefined' && mask != '' && isSet == '0')
        {        
            $j(this).mask(mask);
        }
      });
     
      window.progress.set_IsLoadingNow(false);
    }
  }
}  
/* static member */
progressBar.Init = function()  
{
    if(window.progress == null)
        window.progress = new progressBar();

    var formsHiddenField = $j("#formIDsHiddenField");
    if(formsHiddenField.length != 0)
    {
        var forms = formsHiddenField[0].value.split(",");
        for(var i = 0; i < forms.length; i++)
            window.progress.AddForm(forms[i]);
    }    
    
    var summaryHiddenField = $j("#summaryIDsHiddenField");
    if(summaryHiddenField.length != 0)
    {
        var summary = summaryHiddenField[0].value.split(",");
        for(var j = 0; j < summary.length; j++)
            window.progress.AddSummaryForm(summary[j]);
    }
    window.progress.Initialize(); 
}

KeyListener =
{
	init: function() {
		$j("body").bind('keypress', function(e) {
			var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
			var target = e.target.tagName.toLowerCase();
			if (key == 13 && target == "input") {
				e.preventDefault();
				var parentFieldset = $j(e.target).parents("fieldset ul div");
				/*
				    var anchor = parentFieldset.children("a.subscribe").eq(0);
				    if (anchor.length > 0) 
				    {
					    var script = anchor.attr("href");
					    try {
						    eval(script);
					    }
					    catch (e) {
					    }
				    }
				    else 
				    {
					    parentFieldset = $j(e.target).parents("fieldset ul div");
				*/
				parentFieldset = parentFieldset.find('a.subscribe, input:submit.apply, input:submit.signin, input:submit.go, input:submit.submit, input:submit.update, input:submit.emptyCssClassForScriptSuppport, a.continue, input:image').eq(0);
				if (parentFieldset.length > 0) {
					var button = $j('#' + parentFieldset[0].id);
					button.click();
				}
			}
		});
	}
}

  
	/*--------------------------------------------------------------*/
  
  Vallidation = function() {}
  
  Vallidation.IsNumberKey = function(event) 
  {
      var charCode = (event.which) ? event.which : event.keyCode
     if (charCode > 31 && (charCode < 48 || charCode > 57) 
	 && (charCode < 96 || charCode > 105))
        return false;
     return true;    
  }

	/*--------------------------------------------------------------*/
  
  var isCtrl = false;
  function checkCreditCard(e, someEvent) {
    
    if (someEvent.keyCode == 17) {
      isCtrl = false;
      return false;
    }
    
    if (!/\d$/.test(e.value)) {
      e.value = '';
    }
        
    // Visa: length 16, prefix 4   
    if (/^4\d{0,15}$/.test(e.value)) {
      e.maxLength = '16';    
      return;
    }

    // Mastercard: length 16, prefix 51-55   
    if (/^5[1-5]\d{0,14}$/.test(e.value)) {
      e.maxLength = '16'; 
      return;
    }

    // Discover: length 16, prefix 6011   
    if (/^6011\d{0,12}$/.test(e.value)) {
      e.maxLength = '16';   
      return;
    }

    // American Express: length 15, prefix 34 or 37.    
    if (/^3[4,7]\d{0,13}$/.test(e.value)) {
      e.maxLength = '15';   
      return;
    }
  }
  function checkDigit(someEvent) {
    var result = ((someEvent.keyCode >= 48 && someEvent.keyCode <= 57)
       		 || (someEvent.keyCode >= 96 && someEvent.keyCode <= 105)
                      || someEvent.keyCode == 8
                      || someEvent.keyCode == 9
                      || someEvent.keyCode == 13
                      || someEvent.keyCode == 46
                      || someEvent.keyCode == 35
                      || someEvent.keyCode == 36
                      || someEvent.keyCode == 37
                      || someEvent.keyCode == 116
                      || (someEvent.keyCode == 67 && isCtrl == true)
                      || (someEvent.keyCode == 86 && isCtrl == true)
                      || (someEvent.keyCode == 88 && isCtrl == true)
                      || (someEvent.keyCode == 84 && isCtrl == true)
                      || (someEvent.keyCode == 78 && isCtrl == true)
                      || (someEvent.keyCode == 90 && isCtrl == true)
                      || someEvent.keyCode == 39);
    if (someEvent.keyCode == 17) {
      isCtrl = true;
      return true;
    }
    someEvent.returnValue = result;
    return result;
}

function ExtensionTextBoxHandler(e, someEvent) {    
    var result = /^[ \x00-\x80]*$/.test(e.value);
    someEvent.returnValue = result;
    return result;
}
/*--- ItemSlideShow.js ---*/var NotActialText;

ItemSlideShow = function(startPosition, ItemImagesObject, imgMiddleId, imgParentId, childImageId, zoomPopupId, zoomBtnId, pnlImageContainerId, btnNextId, btnPrevId, ImageNotActialText) {
    this.startPosition = startPosition;
    this.ItemImagesObject = ItemImagesObject;
    this.imgMiddleId = imgMiddleId;
    this.imgParentId = imgParentId;
    this.childImageId = childImageId;
    this.zoomPopupId = zoomPopupId;
    this.zoomBtnId = zoomBtnId;
    this.pnlImageContainerId = pnlImageContainerId;
    this.btnNextId = btnNextId;
    this.btnPrevId = btnPrevId;
    this.InitImages = InitImages;
    this.MoveNext = MoveNext;
    this.MovePrev = MovePrev;
    this.UpdateImages = UpdateImages;
    this.SelectImage = SelectImage;
    this.SelectMiddleImg = SelectMiddleImg;
    this.SelectedIndex = null;
    this.imgMiddleClick = 'Execute(Popup,Popup.Show,\'' + this.zoomPopupId + '\');return false;';
    this.imgMiddleClickNoAction = 'return false;';
    this.MiddleImgClickHandler = this.imgMiddleClick;

    NotActialText = ImageNotActialText;

    /*if (ItemImagesObject.Images) {
        for (var i = 0; i < ItemImagesObject.Images.length; i++) {
            var preloadedImage = new Image(100, 25);
            preloadedImage.src = ItemImagesObject.Images[i].Medium;
        }
    }*/
}

function InitImages()
{
    if(this.ItemImagesObject.DefaultImage == null || this.ItemImagesObject.Images == null)
        return;

	var ItemImages = this.ItemImagesObject;
	var imgMiddle = $j('#' + this.imgMiddleId);
	var zoomBtn = $j('#' + this.zoomBtnId != '' && this.zoomBtnId != 'undefined' ? this.zoomBtnId : 'undefined');
    // slide show is not within popup dialog
	if (this.zoomPopupId != 'null') {
	    imgMiddle.attr('src', ItemImages.DefaultImage.Medium);
	    if (ItemImages.DefaultImage.AllowZoom) {
	        zoomBtn.show();
	        this.MiddleImgClickHandler = this.imgMiddleClick;
	        imgMiddle.addClass('clickable');
	    }
	    else {
	        zoomBtn.hide();
	        this.MiddleImgClickHandler = this.imgMiddleClickNoAction;
	        imgMiddle.removeClass('clickable');
	    }
	    
	    imgMiddle.bind('click', { itemSlideShow: this }, SelectMiddleImg);
	}
	// slide show is within popup dialog
	else {
		var selectedImg = $j('#' + this.imgParentId).attr('src');
		if (selectedImg) {
			selectedImg = selectedImg.replace(/product/, 'large');
			imgMiddle.attr('src', selectedImg);
		}
	}
    InitializeNotActualMessage(imgMiddle, ItemImages.DefaultImage);

    var pnlImageContainer = $j('#' + this.pnlImageContainerId);
	for (i = this.startPosition; i < this.startPosition + parseInt(ItemImages.ShownLength); i++)
	{
		if (i < ItemImages.Images.length && ItemImages.Images[i].Small != null && pnlImageContainer.length == 1)
		{
			var liImage = document.createElement('span');
			pnlImageContainer[0].appendChild(liImage);
			var imagePlace = document.createElement('a');
			var anchorId = 'a' + guid();
			imagePlace.id = anchorId;
			imagePlace.index = i;
			liImage.appendChild(imagePlace);
			$j(imagePlace).bind('mouseover', {itemSlideShow : this, imageId : anchorId}, SelectImage);

			var image = document.createElement('img');
			image.id = 'img' + guid();
			image.alt = 'image';
			image.src = ItemImages.Images[i].Small;
			image.onmouseover = imagePlace.appendChild(image);
		}
	}
	$j('#' + this.btnNextId).bind('click', {itemSlideShow : this}, this.MoveNext);
	$j('#' + this.btnPrevId).bind('click', {itemSlideShow : this}, this.MovePrev);
}

function MoveNext(event)
{
	var ItemImages = event.data.itemSlideShow.ItemImagesObject;
	if (event.data.itemSlideShow.startPosition + parseInt(ItemImages.ShownLength) >= ItemImages.Images.length)
		return;
	
	event.data.itemSlideShow.startPosition++;
	event.data.itemSlideShow.UpdateImages(event);
	return false;
}

function MovePrev(event)
{
	if (event.data.itemSlideShow.startPosition == 0)
		return;

	event.data.itemSlideShow.startPosition--;
	event.data.itemSlideShow.UpdateImages(event);
	return false;
}

function UpdateImages(event)
{
	var ItemImages = event.data.itemSlideShow.ItemImagesObject;
	var imageElements = $j('#' + event.data.itemSlideShow.pnlImageContainerId).find('img');
	for (var i = 0; i < imageElements.length; i++)
	{
	    var index = i + event.data.itemSlideShow.startPosition;
		imageElements[i].src = ItemImages.Images[index].Small;
	}
}

function SelectImage(event)
{
	var ItemImages = event.data.itemSlideShow.ItemImagesObject;
	var selectedElement = $j('#' + event.data.imageId);
	var imgMiddle = $j('#' + event.data.itemSlideShow.imgMiddleId);
	if (selectedElement.length == 1 && imgMiddle.length == 1)
	{
    var index = selectedElement[0].index + event.data.itemSlideShow.startPosition;
    event.data.itemSlideShow.SelectedIndex = index;
    var overlay = $j('div[id$=img_load_wait]');
    var image = new Image();
    $j(image).load(function() {
      imgMiddle.attr('src', image.src);
      overlay.hide();
    });
	  $j(image).attr('src', ItemImages.Images[index].Medium);
	  if(!image.complete) overlay.show();
		InitializeNotActualMessage(imgMiddle, ItemImages.Images[index]);
		var allowZoom = ItemImages.Images[index].AllowZoom;
		var zoomBtn = $j('.btn.small.zoom');
		if (allowZoom) {
		    event.data.itemSlideShow.MiddleImgClickHandler =
		        event.data.itemSlideShow.imgMiddleClick;
		    imgMiddle.addClass('clickable');
		    zoomBtn.show();
		    $j('#' + event.data.itemSlideShow.childImageId).attr('src', 
		        ItemImages.Images[index].Medium.replace(/product/, 'large'));
		}
		else {
		    event.data.itemSlideShow.MiddleImgClickHandler =
		        event.data.itemSlideShow.imgMiddleClickNoAction;
		    // zoom button should not hide if we are in popup
		    if (event.data.itemSlideShow.zoomPopupId != "null") {
		        imgMiddle.removeClass('clickable');
		        zoomBtn.hide();
		    }
		}
	}
}

function SelectMiddleImg(event)
{
    var handler = new Function(event.data.itemSlideShow.MiddleImgClickHandler);
    handler();
}

function InitializeNotActualMessage(img, imgInfo)
{
    var msg = imgInfo.Actual ? '' : NotActialText;
    var container = $j(img).parent().find('.no-actual-image');
    if(container.length==0)
     container = $j("<div class='no-actual-image'/>").appendTo($j(img).parent());
    container.text(msg); 
}
/*--- jquery.hoverIntent.js ---*//**
* hoverIntent is similar to jQuery's built-in "hover" function except that
* instead of firing the onMouseOver event immediately, hoverIntent checks
* to see if the user's mouse has slowed down (beneath the sensitivity
* threshold) before firing the onMouseOver event.
* 
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* hoverIntent is currently available for use in all personal or commercial 
* projects under both MIT and GPL licenses. This means that you can choose 
* the license that best suits your project, and use it accordingly.
* 
* // basic usage (just like .hover) receives onMouseOver and onMouseOut functions
* $j("ul li").hoverIntent( showNav , hideNav );
* 
* // advanced usage receives configuration object only
* $j("ul li").hoverIntent({
*	sensitivity: 7, // number = sensitivity threshold (must be 1 or higher)
*	interval: 100,   // number = milliseconds of polling interval
*	over: showNav,  // function = onMouseOver callback (required)
*	timeout: 0,   // number = milliseconds delay before onMouseOut function call
*	out: hideNav    // function = onMouseOut callback (required)
* });
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne <brian@cherne.net>
*/
(function($j) {
	$j.fn.hoverIntent = function(f,g) {
		// default configuration options
		var cfg = {
			sensitivity: 7,
			interval: 100,
			timeout: 0
		};
		// override configuration options with user supplied object
		cfg = $j.extend(cfg, g ? { over: f, out: g } : f );

		// instantiate variables
		// cX, cY = current X and Y position of mouse, updated by mousemove event
		// pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
		var cX, cY, pX, pY;

		// A private function for getting mouse position
		var track = function(ev) {
			cX = ev.pageX;
			cY = ev.pageY;
		};

		// A private function for comparing current and previous mouse position
		var compare = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			// compare mouse positions to see if they've crossed the threshold
			if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) {
				$j(ob).unbind("mousemove",track);
				// set hoverIntent state to true (so mouseOut can be called)
				ob.hoverIntent_s = 1;
				return cfg.over.apply(ob,[ev]);
			} else {
				// set previous coordinates for next time
				pX = cX; pY = cY;
				// use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
				ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval );
			}
		};

		// A private function for delaying the mouseOut function
		var delay = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			ob.hoverIntent_s = 0;
			return cfg.out.apply(ob,[ev]);
		};

		// A private function for handling mouse 'hovering'
		var handleHover = function(e) {
			// next three lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut
			var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
			while ( p && p != this ) { try { p = p.parentNode; } catch(e) { p = this; } }
			if ( p == this ) { return false; }

			// copy objects to be passed into t (required for event object to be passed in IE)
			var ev = jQuery.extend({},e);
			var ob = this;

			// cancel hoverIntent timer if it exists
			if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }

			// else e.type == "onmouseover"
			if (e.type == "mouseover") {
				// set "previous" X and Y position based on initial entry point
				pX = ev.pageX; pY = ev.pageY;
				// update "current" X and Y position based on mousemove
				$j(ob).bind("mousemove",track);
				// start polling interval (self-calling timeout) to compare mouse coordinates over time
				if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}

			// else e.type == "onmouseout"
			} else {
				// unbind expensive mousemove event
				$j(ob).unbind("mousemove",track);
				// if hoverIntent state is true, then call the mouseOut function after the specified delay
				if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
			}
		};

		// bind the function to the two event listeners
		return this.mouseover(handleHover).mouseout(handleHover);
	};
})(jQuery);
/*--- jquery.innerfade.js ---*//* =========================================================

// jquery.innerfade.js

// Datum: 2008-02-14
// Firma: Medienfreunde Hofmann & Baldes GbR
// Author: Torsten Baldes
// Mail: t.baldes@medienfreunde.com
// Web: http://medienfreunde.com

// based on the work of Matt Oakes http://portfolio.gizone.co.uk/applications/slideshow/
// and Ralf S. Engelschall http://trainofthoughts.org/

 *
 *  <ul id="news"> 
 *      <li>content 1</li>
 *      <li>content 2</li>
 *      <li>content 3</li>
 *  </ul>
 *  
 *  $j('#news').innerfade({ 
 *	  animationtype: Type of animation 'fade' or 'slide' (Default: 'fade'), 
 *	  speed: Fading-/Sliding-Speed in milliseconds or keywords (slow, normal or fast) (Default: 'normal'), 
 *	  timeout: Time between the fades in milliseconds (Default: '2000'), 
 *	  type: Type of slideshow: 'sequence', 'random' or 'random_start' (Default: 'sequence'), 
 * 		containerheight: Height of the containing element in any css-height-value (Default: 'auto'),
 *	  runningclass: CSS-Class which the container get’s applied (Default: 'innerfade'),
 *	  children: optional children selector (Default: null)
 *  }); 
 *

// ========================================================= */


(function($j) {

    $j.fn.innerfade = function(options) {
        return this.each(function() {   
            $j.innerfade(this, options);
        });
    };

    $j.innerfade = function(container, options) {
        var settings = {
        		'animationtype':    'fade',
            'speed':            'normal',
            'type':             'sequence',
            'timeout':          2000,
            'containerheight':  'auto',
            'runningclass':     'innerfade',
            'children':         null
        };
        if (options)
            $j.extend(settings, options);
        if (settings.children === null)
            var elements = $j(container).children();
        else
            var elements = $j(container).children(settings.children);
        if (elements.length > 1) {
            $j(container).css('position', 'relative').css('height', settings.containerheight).addClass(settings.runningclass);
            for (var i = 0; i < elements.length; i++) {
                $j(elements[i]).css('z-index', String(elements.length-i)).css('position', 'absolute').hide();
            };
            if (settings.type == "sequence") {
                setTimeout(function() {
                    $j.innerfade.next(elements, settings, 1, 0);
                }, settings.timeout);
                $j(elements[0]).show();
            } else if (settings.type == "random") {
            		var last = Math.floor ( Math.random () * ( elements.length ) );
                setTimeout(function() {
                    do { 
												current = Math.floor ( Math.random ( ) * ( elements.length ) );
										} while (last == current );             
										$j.innerfade.next(elements, settings, current, last);
                }, settings.timeout);
                $j(elements[last]).show();
						} else if ( settings.type == 'random_start' ) {
								settings.type = 'sequence';
								var current = Math.floor ( Math.random () * ( elements.length ) );
								setTimeout(function(){
									$j.innerfade.next(elements, settings, (current + 1) %  elements.length, current);
								}, settings.timeout);
								$j(elements[current]).show();
						}	else {
							alert('Innerfade-Type must either be \'sequence\', \'random\' or \'random_start\'');
						}
				}
    };

    $j.innerfade.next = function(elements, settings, current, last) {
	
        for (var i = 0; i < elements.length; i++) {
			if((i!=last)&&(i!=current))
                $j(elements[i]).hide();
        };

        if (settings.animationtype == 'slide') {
            $j(elements[last]).slideUp(settings.speed);
            $j(elements[current]).slideDown(settings.speed);
        } else if (settings.animationtype == 'fade') {
            $j(elements[last]).fadeOut(settings.speed);
            $j(elements[current]).fadeIn(settings.speed, function() {
							removeFilter($j(this)[0]);
						});
        } else
            alert('Innerfade-animationtype must either be \'slide\' or \'fade\'');
        if (settings.type == "sequence") {
            if ((current + 1) < elements.length) {
                current = current + 1;
                last = current - 1;
            } else {
                current = 0;
                last = elements.length - 1;
            }
        } else if (settings.type == "random") {
            last = current;
            while (current == last)
                current = Math.floor(Math.random() * elements.length);
        } else
            alert('Innerfade-Type must either be \'sequence\', \'random\' or \'random_start\'');
        setTimeout((function() {
            $j.innerfade.next(elements, settings, current, last);
        }), settings.timeout);
    };

})(jQuery);

// **** remove Opacity-Filter in ie ****
function removeFilter(element) {
	if(element.style.removeAttribute){
		element.style.removeAttribute('filter');
	}
}

/*--- jquery.lazyload.mini.js ---*/
(function($){$.fn.lazyload=function(options){var settings={threshold:0,failurelimit:0,event:"scroll",effect:"show",container:window};if(options){$.extend(settings,options);}
var elements=this;if("scroll"==settings.event){$(settings.container).bind("scroll",function(event){var counter=0;elements.each(function(){if($.abovethetop(this,settings)||$.leftofbegin(this,settings)){}else if(!$.belowthefold(this,settings)&&!$.rightoffold(this,settings)){$(this).trigger("appear");}else{if(counter++>settings.failurelimit){return false;}}});var temp=$.grep(elements,function(element){return!element.loaded;});elements=$(temp);});}
this.each(function(){var self=this;if(undefined==$(self).attr("original")){$(self).attr("original",$(self).attr("src"));}
if("scroll"!=settings.event||undefined==$(self).attr("src")||settings.placeholder==$(self).attr("src")||($.abovethetop(self,settings)||$.leftofbegin(self,settings)||$.belowthefold(self,settings)||$.rightoffold(self,settings))){if(settings.placeholder){$(self).attr("src",settings.placeholder);}else{$(self).removeAttr("src");}
self.loaded=false;}else{self.loaded=true;}
$(self).one("appear",function(){if(!this.loaded){$("<img />").bind("load",function(){$(self).hide().attr("src",$(self).attr("original"))
[settings.effect](settings.effectspeed);self.loaded=true;}).attr("src",$(self).attr("original"));};});if("scroll"!=settings.event){$(self).bind(settings.event,function(event){if(!self.loaded){$(self).trigger("appear");}});}});$(settings.container).trigger(settings.event);return this;};$.belowthefold=function(element,settings){if(settings.container===undefined||settings.container===window){var fold=$(window).height()+$(window).scrollTop();}else{var fold=$(settings.container).offset().top+$(settings.container).height();}
return fold<=$(element).offset().top-settings.threshold;};$.rightoffold=function(element,settings){if(settings.container===undefined||settings.container===window){var fold=$(window).width()+$(window).scrollLeft();}else{var fold=$(settings.container).offset().left+$(settings.container).width();}
return fold<=$(element).offset().left-settings.threshold;};$.abovethetop=function(element,settings){if(settings.container===undefined||settings.container===window){var fold=$(window).scrollTop();}else{var fold=$(settings.container).offset().top;}
return fold>=$(element).offset().top+settings.threshold+$(element).height();};$.leftofbegin=function(element,settings){if(settings.container===undefined||settings.container===window){var fold=$(window).scrollLeft();}else{var fold=$(settings.container).offset().left;}
return fold>=$(element).offset().left+settings.threshold+$(element).width();};$.extend($.expr[':'],{"below-the-fold":"$.belowthefold(a, {threshold : 0, container: window})","above-the-fold":"!$.belowthefold(a, {threshold : 0, container: window})","right-of-fold":"$.rightoffold(a, {threshold : 0, container: window})","left-of-fold":"!$.rightoffold(a, {threshold : 0, container: window})"});})(jQuery);
/*--- jquery.timers.js ---*/jQuery.fn.extend({
	everyTime: function(interval, label, fn, times, belay) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, times, belay);
		});
	},
	oneTime: function(interval, label, fn) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, 1);
		});
	},
	stopTime: function(label, fn) {
		return this.each(function() {
			jQuery.timer.remove(this, label, fn);
		});
	}
});

jQuery.extend({
	timer: {
		guid: 1,
		global: {},
		regex: /^([0-9]+)\s*(.*s)?$/,
		powers: {
			// Yeah this is major overkill...
			'ms': 1,
			'cs': 10,
			'ds': 100,
			's': 1000,
			'das': 10000,
			'hs': 100000,
			'ks': 1000000
		},
		timeParse: function(value) {
			if (value == undefined || value == null)
				return null;
			var result = this.regex.exec(jQuery.trim(value.toString()));
			if (result[2]) {
				var num = parseInt(result[1], 10);
				var mult = this.powers[result[2]] || 1;
				return num * mult;
			} else {
				return value;
			}
		},
		add: function(element, interval, label, fn, times, belay) {
			var counter = 0;
			
			if (jQuery.isFunction(label)) {
				if (!times) 
					times = fn;
				fn = label;
				label = interval;
			}
			
			interval = jQuery.timer.timeParse(interval);

			if (typeof interval != 'number' || isNaN(interval) || interval <= 0)
				return;

			if (times && times.constructor != Number) {
				belay = !!times;
				times = 0;
			}
			
			times = times || 0;
			belay = belay || false;
			
			if (!element.$timers) 
				element.$timers = {};
			
			if (!element.$timers[label])
				element.$timers[label] = {};
			
			fn.$timerID = fn.$timerID || this.guid++;
			
			var handler = function() {
				if (belay && this.inProgress) 
					return;
				this.inProgress = true;
				if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
					jQuery.timer.remove(element, label, fn);
				this.inProgress = false;
			};
			
			handler.$timerID = fn.$timerID;
			
			if (!element.$timers[label][fn.$timerID]) 
				element.$timers[label][fn.$timerID] = window.setInterval(handler,interval);
			
			if ( !this.global[label] )
				this.global[label] = [];
			this.global[label].push( element );
			
		},
		remove: function(element, label, fn) {
			var timers = element.$timers, ret;
			
			if ( timers ) {
				
				if (!label) {
					for ( label in timers )
						this.remove(element, label, fn);
				} else if ( timers[label] ) {
					if ( fn ) {
						if ( fn.$timerID ) {
							window.clearInterval(timers[label][fn.$timerID]);
							delete timers[label][fn.$timerID];
						}
					} else {
						for ( var fn in timers[label] ) {
							window.clearInterval(timers[label][fn]);
							delete timers[label][fn];
						}
					}
					
					for ( ret in timers[label] ) break;
					if ( !ret ) {
						ret = null;
						delete timers[label];
					}
				}
				
				for ( ret in timers ) break;
				if ( !ret ) 
					element.$timers = null;
			}
		}
	}
});

if (jQuery.browser.msie)
	jQuery(window).one("unload", function() {
		if(jQuery && jQuery != undefined)
		{
		try
		{	var global = jQuery.timer.global;
			for ( var label in global ) {
				var els = global[label], i = els.length;
				while ( --i )
					jQuery.timer.remove(els[i], label);
			}
		}catch(e)
		{
		}
		}
	});
	
/*--- jquery.url.js ---*//* ===========================================================================
 *
 * JQuery URL Parser
 * Version 1.0
 * Parses URLs and provides easy access to information within them.
 *
 * Author: Mark Perkins
 * Author email: mark@allmarkedup.com
 *
 * For full documentation and more go to http://projects.allmarkedup.com/jquery_url_parser/
 *
 * ---------------------------------------------------------------------------
 *
 * CREDITS:
 *
 * Parser based on the Regex-based URI parser by Steven Levithan.
 * For more information (including a detailed explaination of the differences
 * between the 'loose' and 'strict' pasing modes) visit http://blog.stevenlevithan.com/archives/parseuri
 *
 * ---------------------------------------------------------------------------
 *
 * LICENCE:
 *
 * Released under a MIT Licence. See licence.txt that should have been supplied with this file,
 * or visit http://projects.allmarkedup.com/jquery_url_parser/licence.txt
 *
 * ---------------------------------------------------------------------------
 * 
 * EXAMPLES OF USE:
 *
 * Get the domain name (host) from the current page URL
 * jQuery.url.attr("host")
 *
 * Get the query string value for 'item' for the current page
 * jQuery.url.param("item") // null if it doesn't exist
 *
 * Get the second segment of the URI of the current page
 * jQuery.url.segment(2) // null if it doesn't exist
 *
 * Get the protocol of a manually passed in URL
 * jQuery.url.setUrl("http://allmarkedup.com/").attr("protocol") // returns 'http'
 *
 */

jQuery.url = function()
{
	var segments = {};
	
	var parsed = {};
	
	/**
    * Options object. Only the URI and strictMode values can be changed via the setters below.
    */
  	var options = {
	
		url : window.location, // default URI is the page in which the script is running
		
		strictMode: false, // 'loose' parsing by default
	
		key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"], // keys available to query 
		
		q: {
			name: "queryKey",
			parser: /(?:^|&)([^&=]*)=?([^&]*)/g
		},
		
		parser: {
			strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,  //less intuitive, more accurate to the specs
			loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ // more intuitive, fails on relative paths and deviates from specs
		}
		
	};
	
    /**
     * Deals with the parsing of the URI according to the regex above.
 	 * Written by Steven Levithan - see credits at top.
     */		
	var parseUri = function()
	{
		str = decodeURI( options.url );
		
		var m = options.parser[ options.strictMode ? "strict" : "loose" ].exec( str );
		var uri = {};
		var i = 14;

		while ( i-- ) {
			uri[ options.key[i] ] = m[i] || "";
		}

		uri[ options.q.name ] = {};
		uri[ options.key[12] ].replace( options.q.parser, function ( $0, $1, $2 ) {
			if ($1) {
				uri[options.q.name][$1] = $2;
			}
		});

		return uri;
	};

    /**
     * Returns the value of the passed in key from the parsed URI.
  	 * 
	 * @param string key The key whose value is required
     */		
	var key = function( key )
	{
		if ( ! parsed.length )
		{
			setUp(); // if the URI has not been parsed yet then do this first...	
		} 
		if ( key == "base" )
		{
			if ( parsed.port !== null && parsed.port !== "" )
			{
				return parsed.protocol+"://"+parsed.host+":"+parsed.port+"/";	
			}
			else
			{
				return parsed.protocol+"://"+parsed.host+"/";
			}
		}
	
		return ( parsed[key] === "" ) ? null : parsed[key];
	};
	
	/**
     * Returns the value of the required query string parameter.
  	 * 
	 * @param string item The parameter whose value is required
     */		
	var param = function( item )
	{
		if ( ! parsed.length )
		{
			setUp(); // if the URI has not been parsed yet then do this first...	
		}
		return ( parsed.queryKey[item] === null ) ? null : parsed.queryKey[item];
	};

    /**
     * 'Constructor' (not really!) function.
     *  Called whenever the URI changes to kick off re-parsing of the URI and splitting it up into segments. 
     */	
	var setUp = function()
	{
		parsed = parseUri();
		
		getSegments();	
	};
	
    /**
     * Splits up the body of the URI into segments (i.e. sections delimited by '/')
     */
	var getSegments = function()
	{
		var p = parsed.path;
		segments = []; // clear out segments array
		segments = parsed.path.length == 1 ? {} : ( p.charAt( p.length - 1 ) == "/" ? p.substring( 1, p.length - 1 ) : path = p.substring( 1 ) ).split("/");
	};
	
	return {
		
	    /**
	     * Sets the parsing mode - either strict or loose. Set to loose by default.
	     *
	     * @param string mode The mode to set the parser to. Anything apart from a value of 'strict' will set it to loose!
	     */
		setMode : function( mode )
		{
			strictMode = mode == "strict" ? true : false;
			return this;
		},
		
		/**
	     * Sets URI to parse if you don't want to to parse the current page's URI.
		 * Calling the function with no value for newUri resets it to the current page's URI.
	     *
	     * @param string newUri The URI to parse.
	     */		
		setUrl : function( newUri )
		{
			options.url = newUri === undefined ? window.location : newUri;
			setUp();
			return this;
		},		
		
		/**
	     * Returns the value of the specified URI segment. Segments are numbered from 1 to the number of segments.
		 * For example the URI http://test.com/about/company/ segment(1) would return 'about'.
		 *
		 * If no integer is passed into the function it returns the number of segments in the URI.
	     *
	     * @param int pos The position of the segment to return. Can be empty.
	     */	
		segment : function( pos )
		{
			if ( ! parsed.length )
			{
				setUp(); // if the URI has not been parsed yet then do this first...	
			} 
			if ( pos === undefined )
			{
				return segments.length;
			}
			return ( segments[pos] === "" || segments[pos] === undefined ) ? null : segments[pos];
		},
		
		attr : key, // provides public access to private 'key' function - see above
		
		param : param // provides public access to private 'param' function - see above
		
	};
	
}();
/*--- jquery.watermark.js ---*/var $j = jQuery.noConflict();

(function($) {
	
	$.clearwatermarks = function() {
		$("[wmwrap='true']").find("input,textarea").watermark({remove:true});
	};
	
		
	$.watermark = function(o) {
		o.el = $(o.el);
		if(o.remove) {
			if(o.el.parent().attr("wmwrap") == 'true') {
				o.el.parent().replaceWith(o.el);
			};
		} else {
			if(o.el.parent().attr("wmwrap") != 'true') {
				o.el = o.el.wrap("<span class='wmw-span' wmwrap='true' style='position:relative;'/>");
				var l = $("<label/>");
				
				if(o.html) { l.html(o.html); };
				if(o.cls) { l.addClass(o.cls); };
				if(o.css) { l.css(o.css); };
				
				l.css({position:"absolute",left:"10px",display:"inline",cursor:"text"});
				if(!o.el.is("textarea")) { l.css({top:($.browser.mozilla)?"2px" : "3px"}); };
				
				if(!o.cls && !o.css) {
					l.css("color","#333");
				};
				
				var focus = function() {
					l.hide();
				};
				
				var blur = function() {
					if(o.el.val() == "") {
						l.show();
					} else {
						l.hide();
					};
				};
				
				var click = function() {
					o.el.focus();
				};
				
				if(o.inherit) {
					if(typeof o.inherit == "string") {
						l.css(o.inherit,o.el.css(o.inherit));
					} else {
						for(var x=0;x<o.inherit.length;x++) {
							l.css(o.inherit[x],o.el.css(o.inherit[x]));
						};
					};
				};
				
				o.el.focus(focus).blur(blur);
				l.click(click);
				o.el.before(l);
				if($.browser.mozilla && o.el.is("textarea")) { o.el.focus().blur();  }
				if(o.el.val() != "") { l.hide(); };
			};
		};
		return o.el;
	};
	
	$.fn.watermark = function(o) {
		return this.each(function() {
			if(typeof(o) == "string") {
				try {o = eval("(" + o + ")");} catch(ex) {o = {html:o};};
			};
			o.el = this;
			return $.watermark(o);
		});
	};
})(jQuery);

function setupWatermark() {    
    $j("[watermark]").each(function(num, el) {        
        $j(el).watermark($j(el).attr("watermark"));
    });
};
 
 $j(document).ready(function() {    
    setupWatermark();    
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function(sender, args) { setupWatermark(); });
 });
/*--- js.custom.js ---*/var id=null;
var MenuItemObj;
var smItemObj;
var smItemClass="";
var activeFlag = 0;
var smFlag = 1;
var unDef;

function DoOver(iObj, smObj, actClass) {
	if ((MenuItemObj != unDef) && ($j(MenuItemObj).attr("id") != $j(iObj).attr("id"))) {
		smFlag = 1;
		DoHide();
	}

	if ($j(MenuItemObj).attr("id") == $j(iObj).attr("id")) {
		smFlag = 0;
	}
	else {
		MenuItemObj = iObj;
		if (actClass != unDef) {
			smItemClass = actClass;
			$j(MenuItemObj).addClass(smItemClass);
		}
		smItemObj = smObj;
		if (smItemObj != unDef) {
			$j(smItemObj).fadeIn("fast");
		}
		activeFlag = 1;
	}
	
}

function killtimer(){

	if(id!=null){
		clearTimeout(id);
		id=null;		
	}

	return true;
}

function DoHide(){
	
	if (smFlag) {

		if(id!=null) {
			killtimer();		
		}

		$j(MenuItemObj).removeClass(smItemClass);
		MenuItemObj = unDef;
		
		if(smItemObj != unDef) {
			$j(smItemObj).hide();
			smItemObj = unDef;						
		}
		activeFlag = 0;
	
	}

}

function reset(){

	killtimer();		
	
	if (activeFlag) {
		smFlag = 1;
		id = setTimeout('DoHide()', 200);
	}
	else {
		$j(MenuItemObj).removeClass(smItemClass);
		MenuItemObj = unDef;
		if (smItemObj != unDef) {
			$j(smItemObj).hide();
			smItemObj = unDef;				
		}
	}			
}

function  DoOut(aSMflag) {		
	if (aSMflag) {			
		reset();
	}
	else smFlag = 0;
}

var smID;
var miClass;
var flagSMClose;
var flagSMActive = 0;

function makeTall() {
	if ($j(this).attr("id") == "support-btn") {
		objClass = "#support-btn";
		smObjID = "#support-box";
	}
	else {
		objClass = "." + this.className.substring(this.className.indexOf('mb1item'), (this.className.indexOf('mb1item') + 8));
		objNumber = this.className.substring((this.className.indexOf('mb1item') + 7), (this.className.indexOf('mb1item') + 8));
		smObjID = (parseInt(objNumber) > 3) ? "#adorama-electronics-si" + (parseInt(objNumber)-3) : "#adorama-photo-si" + objNumber;
	}
	if (smObjID == smID) { flagSMClose = 0; }
	else {
		flagSMClose = 1;
		if (smID != unDef) {
			makeShort();
			flagSMClose = 0;
		}
	}
	if ((smID == unDef) || (smObjID != smID)) {
		miClass = objClass;
		smID = smObjID;
		$j(miClass).addClass("active-mi");
		$j(smID).fadeIn("fast");
	}
}
function makeShort() {
	if ((flagSMClose) || (!flagSMActive)) {
		$j(miClass).removeClass("active-mi");
		$j(smID).hide();
		smID = unDef;
	}
}
function doOverSM() {
	flagSMClose = 0
}
function doOverFlag() {
	flagSMActive = 1
}
function doOutFlag() {
	flagSMActive = 0
}
/*--- Login.js ---*//*-------- login form -------*/
/* Used triggers:
Login.Close
Login.Error
Login.Logined
*/
Login = function() { };

Login.Open = function() {
	var loginPopup = AjaxPopup.Settings.Login();
	var isCached = AjaxPopup.IsAlreadyCachedBySetting(loginPopup);
	var ret = AjaxPopup.OpenBySetting(loginPopup);
	if (!isCached) { Login.Setup(); }
	var idLogin = AjaxPopup.IdBySetting(loginPopup);
	$j('.' + idLogin + ' .jq_SignInForm .jq_Email').focus();
	return ret;
};

Login.Close = function() {
	ret = AjaxPopup.CloseBySetting(AjaxPopup.Settings.Login());
	$j(document).trigger("Login.Close");
	return ret;
};

Login.Setup = function() {
	$j('.jq_ForgotPasswordUserPopup_tbEmail').bind('keypress', function(e) {
		if (e.which == 13) {
			$j('.jq_ForgotPasswordUserPopup_SendEmailBottom').click();
		};
	});
	var idLogin = AjaxPopup.IdBySetting(AjaxPopup.Settings.Login());
	$j('.' + idLogin + ' .jq_SignInForm .jq_Email, '
     + '.' + idLogin + ' .jq_SignInForm .jq_Password').bind('keypress', function(e) {
     	if (e.which == 13) {
     		$j('.' + idLogin + ' .jq_SignInForm .jq_SubmitBottom').click();
     	};
     });

     $j('.' + idLogin + ' .jq_CreateAccount .jq_NameFirst, '
	 + '.' + idLogin + ' .jq_CreateAccount .jq_NameLast, '
	 + '.' + idLogin + ' .jq_CreateAccount .jq_Email, '
	 + '.' + idLogin + ' .jq_CreateAccount .jq_Password, '
	 + '.' + idLogin + ' .jq_CreateAccount .jq_PasswordConfirm').bind('keypress', function(e) {
				 	if (e.which == 13) {
				 		$j('.' + idLogin + ' .jq_CreateAccount .jq_btnCreate').click();
				 	};
				 });

};

Login.ForgotPasswordClick = function(ForgotPassword, PasswordHasBeenSentPopup) {
    var fullUrl = Config.ForgotPasswordHandler();
	$j("#" + ForgotPassword + " .jq_ForgotPassword_WaitBlock").css("display", "block");
	var Email_val = $j("#" + ForgotPassword + " .jq_ForgotPasswordUserPopup_tbEmail").val();

	$j.ajax({
	    type: "POST",
	    url: fullUrl,
	    async: true,
	    dataType: "json",
	    data: { Email: Email_val },
	    success: function(answer) {
    		$j("#" + ForgotPassword + " .jq_ForgotPassword_WaitBlock").css("display", "none");
    		if (answer.Error != null) {
    			$j("#" + ForgotPassword + " .b-header").each(function() {
    				if ($j(this).hasClass("err")) {
    					$j(this).show();
    				} else {
    					$j(this).hide();
    				}
    			});
    			$j("#" + ForgotPassword + " .jq_RegularText").css("display", "none");
    			$j("#" + ForgotPassword + " .jq_RegularTextErrorServer .jq_message").html(answer.Error);
    			$j("#" + ForgotPassword + " .jq_RegularTextErrorServer").show(500);
    			$j("#" + ForgotPassword + " .jq_ForgotPasswordUserPopup_tbEmail")
                    .parent(".ff-row").addClass("err-field");
    		}
    		else {
    			setTimeout(function() { Validator.CheckSet('validateFgPass', true); }, 50);
    			$j("#" + ForgotPassword).css("display", "none");
    			$j("#" + PasswordHasBeenSentPopup).css("display", "block");
    		}
    	},
    	error: function(error) {
    		$j("#" + ForgotPassword + " .jq_ForgotPassword_WaitBlock").css("display", "none");
    		$j("#" + ForgotPassword + " .jq_RegularText").css("display", "none");
    		$j("#" + ForgotPassword + " .jq_RegularTextErrorServer .jq_message").html($j(".jq_PopupHttpError").html());
    		$j("#" + ForgotPassword + " .jq_RegularTextErrorServer").css("display", "block");
    	}	    
	});	    

	return false;
};

Login.SignIn = function(id) {
    $j("#" + id + " .jq_SignIn_WaitBlock").css("display", "block");
    var Email_val = $j("#" + id + " .jq_Email").val();
    var Password_val = $j("#" + id + " .jq_Password").val();
    var fullUrl = Config.SignInHandler();

    $j.ajax({
        type: "POST",
        url: fullUrl,
        async: true,
        dataType: "json",
        data: { Email: Email_val,
                Password: Password_val
        },
        success: function(answer) {
            $j("#" + id + " .jq_SignIn_WaitBlock").css("display", "none");
            if (answer.Error != null || answer.Exception != null) {
                if (answer.Error != null) {
                    $j("#" + id + " .jq_RegularHeader").css("display", "none");
                    $j("#" + id + " .jq_RegularText .jq_message").html(answer.Error);
                    $j("#" + id + " .jq_RegularText").css("display", "block");
                    $j("#" + id + " .jq_RegularHeaderError").css("display", "block");
                    $j("#" + id + " .jq_Password").val("");
                }
                else if (answer.Exception != null) {
                    AjaxPopup.ErrorPopupOpen();
                }
                $j(document).trigger("Login.Error");
            }
            else {
                $j(document).trigger("Login.Logined");
            }
        },
        error: function(error) {
            $j("#" + id + " .jq_SignIn_WaitBlock").css("display", "none");
            $j("#" + id + " .jq_RegularHeader").css("display", "none");
            $j("#" + id + " .jq_RegularText .jq_message").html($j(".jq_PopupHttpError").html());
            $j("#" + id + " .jq_RegularText").css("display", "block");
            $j("#" + id + " .jq_RegularHeaderError").css("display", "block");
            $j("#" + id + " .jq_Password").val("");
            $j(document).trigger("Login.Error");
        }
    });	 

    return false;
};

Login.CreateAccount = function(id) {

	$j("#" + id + " .jq_CreateAccount_WaitBlock").css("display", "block");

	var FirstName_val = $j("#" + id + " .jq_NameFirst").val();
	var LastName_val = $j("#" + id + " .jq_NameLast").val();
	var Email_val = $j("#" + id + " .jq_Email").val();
	var Password_val = $j("#" + id + " .jq_Password").val();
	var PasswordConfirm_val = $j("#" + id + " .jq_PasswordConfirm").val();
	var fullUrl = Config.CreateAccountHandler();

	$j.ajax({
	    type: "POST",
	    url: fullUrl,
	    async: true,
	    dataType: "json",
	    data: { FirstName: FirstName_val,
    		LastName: LastName_val,
    		Email: Email_val,
    		Password: Password_val,
    		PasswordConfirm: PasswordConfirm_val
    	},
	    success: function(answer) {
    		$j("#" + id + " .jq_CreateAccount_WaitBlock").css("display", "none");
    		if (answer.Error != null) {
    			$j("#" + id + " .jq_RegularHeader").css("display", "none");
    			$j("#" + id + " .jq_RegularTextErrorServer .jq_message").html(answer.Error);
    			$j("#" + id + " .jq_RegularTextErrorServer").css("display", "block");
    			$j("#" + id + " .jq_RegularHeaderError").css("display", "block");
    			$j("#" + id + " .jq_Password").val("");
    			$j("#" + id + " .jq_PasswordConfirm").val("");
    			$j(document).trigger("Login.Error");
    		}
    		else {
    			if (answer.Message == 'OK') {
    				$j(document).trigger("Login.Logined");
    				/*window.location = document.location.href;*/
    			}
    			else {
    				$j("#" + id).css("display", "none");
    			}
    		}
    	},
    	error: function(error) {
    		$j("#" + id + " .jq_CreateAccount_WaitBlock").css("display", "none");
    		$j("#" + id + " .jq_RegularHeader").css("display", "none");
    		$j("#" + id + " .jq_RegularTextErrorServer .jq_message").html($j(".jq_PopupHttpError").html());
    		$j("#" + id + " .jq_RegularTextErrorServer").css("display", "block");
    		$j("#" + id + " .jq_RegularHeaderError").css("display", "block");
    		$j("#" + id + " .jq_Password").val("");
    		$j("#" + id + " .jq_PasswordConfirm").val("");
    		$j(document).trigger("Login.Error");
    	}
	});
	
	

	return false;

};
/*--- popup.js ---*/Popup = function() {
}

Popup.Show = function(win) {
	$j('#' + win).css({ display: 'block' });
	$j('#' + win + '_Status').val('1');
	if($j('#' + win+' input[type="text"]').length>0)
	{
		$j('#' + win+' input[type="text"]')[0].focus();
	}else
	{
		if($j('#' + win+' a').length>0)
		{
			$j('#' + win+' a')[0].focus();
		}
	}
	return false;
}

Popup.LoadAndShow = function(win, innerClass, url) {
	if ($j('#' + win).length == 0) {
		Popup.Load(url, win);
	}
	else {
		$j('.' + innerClass).show();
		Popup.Show(win);
		setTimeout(function() { $j('.' + innerClass + ' input:text').first().focus(); }, 60);
	}

	return false;
}

		//		$j(document).one("keydown", function(e) {
		//			pressed = (e.keyCode ? e.keyCode : e.which);
		//			if (pressed == 27) { $j(".popupExit").click() }
		//		});

Popup.Load = function(url, win) {
	var popupContent = $j("<div/>").load(url, function() {
		$j("body").append(popupContent);
		setTimeout(function() { $j('#' + win + ' input:text').first().focus(); }, 60);
		return false;
	});
}

Popup.Hide = function(win) {
	$j('#' + win).css({ display: 'none' });
	$j('#' + win + '_Status').val('');
	return false;
}

Popup.Remove = function(win) {
	$j('#' + win).remove();
	return false;
}

Popup.ShowBySelector = function(selector) {
	$j(selector).css({ display: 'block' });
	$j(selector + '_Status').val('1');
	if($j(selector+' input[type="text"]').length>0)
	{
		$j(selector+' input[type="text"]')[0].focus();
	}else
	{
		if($j(selector+' a').length>0)
		{
			$j(selector+' a')[0].focus();
		}
	}
	return false;
}

Popup.HideBySelector = function(selector) {
	$j(selector).css({ display: 'none' });
	$j(selector + '_Status').val('');
	return false;
}


Popup.SetFocus = function(el) {
    setTimeout(function(){$j('#' + el).focus();	},60);
	return false;
}
/*--- PopupBackground.js ---*/var jquery = jQuery.noConflict();

jquery(document).ready(function() {
    var requestManager = Sys.WebForms.PageRequestManager.getInstance();

    requestManager.add_endRequest(function(sender, args) {
        DeleteMultipleBackground();
    });
});

function DeleteMultipleBackground() {
    var backgrounds = jquery('.modalBackground');
    if (backgrounds.length > 1) {
        backgrounds.slice(0, backgrounds.length - 1).removeClass('modalBackground');
    }
}
/*--- Print.js ---*/
Print = function() {}

Print.Click = function(linkId) {
	var sku = $j('#ProductDetailsSkuValue').val();
	if (sku.length > 0) {
		link = $j('#' + linkId);
		var href = link.attr("href");
		if (href) {
			var str = href.toString();
			var url = str.substring(0, str.lastIndexOf('/') + 1);
			link.attr("href", url + sku);
		}
	}
	return true;
}
/*--- productReview.js ---*/function ShowEngine(pageId, zipLocation)
{
	var skuDiv = $j('div.reviewsSkuHidden');
	InitPowerReviewsConstants(pageId, zipLocation, 'javascript:void(0);');
	ExtendJScriptMethods();
	engine($j('div.powerReviewsDivFlag'));
	prData(pr_data_callback);
}

function InitPowerReviewsConstants(pageId, zipLocation, writeReviewUrl)
{
	pr_page_id = pageId;
	pr_zip_location=zipLocation;
	pr_write_review=writeReviewUrl;
	pr_data_callback = function(info){
	};
}

function OpenReviewsTab()
{
	var reviewTab = $j('.tabs a.reviewsTabFlag')[0];
	if(reviewTab != null)
	{
		window.location.hash = "Reviews";
		InformationalTabs.Click(reviewTab);
	}
	return false;
}

function OpenWriteReviewsTab()
{
	var reviewTab = $j('.tabs a.writeReviewsTabFlag')[0];
	if(reviewTab != null)
	{
		window.location.hash = "WriteReviews";
		InformationalTabs.Click(reviewTab);
		var iframe = $j('#tb_writereviews iframe');
		var refVal = $j(iframe).attr('ref');
		var srcVal = $j(iframe).attr('src');
		if (refVal != srcVal) {
			$j(iframe).attr('src', refVal);
		}
	}
	return false;
}

function ExtendJScriptMethods()
{
	jQuery.fn.extend({
		write: function(text) {
		if(text.lastIndexOf('<link rel="stylesheet" ')== -1)
			this[0].innerHTML+=text;
		return this;
        }
    });

  jQuery.fn.extend({
	getElementById: function(id) {
				return document.getElementById(id);
       }
   });
}

/*--- RequestPrice.js ---*/RequestPrice = function() {}





RequestPrice.SendClick = function(fullUrl, skuNumber, requestPricePopup, priceHasBeenSentPopup, errorPopup, clientGuid) {
    
    
	$j(".jq_RequestPriceBlockContent_" + clientGuid).hide();
	$j(".jq_RequestPriceBlockWait_" + clientGuid).show();
	var email = $j(".jq_RequestPriceEmail_" + clientGuid).val();
	
	$j.ajax({
		type: "POST",
		url: fullUrl,
		async: false,
		data: { SkuNumber: skuNumber, Email: email },
		success: function(answer) {
		    
		    if (answer.Error != null) {
			    $j("#" + errorPopup + " .jq_message").html(answer.Error);
			    $j("#" + errorPopup).show();
		    }
		    else
		    {
		        $j("#" + requestPricePopup).hide();
		        $j("#" + priceHasBeenSentPopup).show();		        
		    }
        	$j(".jq_RequestPriceBlockWait_" + clientGuid).hide();
	        $j(".jq_RequestPriceBlockContent_" + clientGuid).show();	    
		},
		error: function(answer) {
	        $j(".jq_RequestPriceBlockWait_" + clientGuid).hide();
	        $j(".jq_RequestPriceBlockContent_" + clientGuid).show();

		    $j("#" + errorPopup + " .jq_message").html($j(".jq_PopupHttpError").html());
			$j("#" + errorPopup).show();	
		},
		dataType: "json"
	});

	return false;
}

RequestPrice.SetEmpty = function(validatedAttribute) {
    setTimeout(function() {
        Validator.CheckSet(validatedAttribute, true);
        $j('.' + validatedAttribute + ' .jq_RequestPrice').css("display", "block");
        $j('.' + validatedAttribute + ' .jq_HasBeenSent').css("display", "none");
        $j('.' + validatedAttribute + ' .jq_Error').css("display", "none");
    }, 50);
    return true;
}
/*--- SearchView.js ---*/SearchView = function() {
    SearchView.getSearchResultPageUrl = function(selector) {
        var searchTerm = $j(selector).val();

        searchTerm = SearchView.trimString(searchTerm).replace(/[=?\\""]/g, '');
        if (searchTerm != '') {
            var trim = searchTerm.replace(/[*]/g, '');
            if (trim.length < 2) {
                alert("Please enter 2 letters or more");
                url = '';
                return url;
            }

            text = searchTerm.replace(/\s+/g, "%20").replace(/\&+/g, "%26");
            url = text.replace(/[*?=.\|<>:%&\/\\]/g, "");
            url = Config.AlsRoot() + '/SearchPage/' + url + '/?Count=10&SearchInfo=' + text;
        }
        else {
            alert("Please, fill in search criteria field");
            url = '';
        }
        return url;
    }

    SearchView.trimString = function(sourceString) {
        sourceString = sourceString.replace(/ /g, ' ');
        return sourceString.replace(/(^\s+)|(\s+$)/g, "");
    }

    SearchView.prototype.Search = function(selector) {
        var url = SearchView.getSearchResultPageUrl(selector);
		if (url.length > 255)
		url = url.substring(0, 255);
        if (url != '') {
            window.location = url;
        }
        return false;
    }
}
/*--- SendEmail.js ---*/
/*-------- SendEmail -------*/
SendEmail = function() { }

SendEmail.Subscribe = function(fullUrl, emailControl, errorDiv, messageDiv) {
	email = $j("#" + emailControl).val();
	$j("#" + errorDiv).css("display", "none");
	$j("#" + messageDiv).css("display", "none");
	if (!Validator.isEmpty(email) && !Validator.isNotEmail(email)) {
		$j.ajax(
   		{
   			type: "POST",
   			url: fullUrl,
   			async: true,
   			data: { Email: email },
   			success: function(answer) {
   				$j("#" + messageDiv).html(answer.Message);
   				$j("#" + messageDiv).show(500);
   			},
   			error: function(answer) {
   				$j("#" + errorDiv).html($j(".jq_PageHttpError").html());
   				$j("#" + errorDiv).show(500);
   			},
   			dataType: "json"
   		});
	}
	else {
		$j("#" + errorDiv).html("E-mail is not in a valid format");
		$j("#" + errorDiv).show(500);
	}
	return false;
}

SendEmail.RadioButtonChanged = function(MyselfRadioButtonId, SendToAFriendPanel) {
	
	if ($j("#" + MyselfRadioButtonId != '' && MyselfRadioButtonId != 'undefined' ? MyselfRadioButtonId: 'undefined' ).is(':checked'))
		$j("#" + SendToAFriendPanel).css("display", "none");
	else
		$j("#" + SendToAFriendPanel).css("display", "block");
}

SendEmail.SetEmpty = function(SendMeRadionButton, SendToAFriendRadioButton, 
                              SendToAFriendPanel, EmailMessageTextBox, defaultMessage)
{
  setTimeout(function() {
	$j("#" + SendMeRadionButton != '' && SendMeRadionButton != 'undefined' ? SendMeRadionButton: 'undefined' ).attr('checked', false);
	$j("#" + SendToAFriendRadioButton != '' && SendToAFriendRadioButton != 'undefined' ? SendToAFriendRadioButton: 'undefined').attr('checked', true);
	$j("#" + SendToAFriendPanel != '' && SendToAFriendPanel != 'undefined' ? SendToAFriendPanel: 'undefined').css("display", "block");    
    Validator.CheckSet('validate', true);
    Validator.CheckSet('validatefr', true);
    $j("#" + EmailMessageTextBox).val(defaultMessage);
    }, 50);
}

SendEmail.SendClick = function(fullUrl, skuNumber, SendMeRadionButton, SendToAFriendRadioButton, SendToAFriendPanel,
                               YourEmailAddressTextBox, YourNameTextBox,
                               FriendsNameTextBox, FriendsEmailAddressTextBox, 
                               EmailMessageTextBox, defaultMessage) {

	$j(".SendMail_WaitBlock").css("display", "block");

	var SendMeRadionButton_val = $j("#" + SendMeRadionButton != '' && SendMeRadionButton != 'undefined' ? SendMeRadionButton: 'undefined').is(':checked');
	var YourEmailAddressTextBox_val = $j("#" + YourEmailAddressTextBox).val();
	var YourNameTextBox_val = $j("#" + YourNameTextBox).val();
	var FriendsNameTextBox_val = $j("#" + FriendsNameTextBox).val();
	var FriendsEmailAddressTextBox_val = $j("#" + FriendsEmailAddressTextBox).val();
	var EmailMessageTextBox_val = $j("#" + EmailMessageTextBox).val();

	$j.ajax({
		type: "POST",
		url: fullUrl,
		async: true,
		data: { SkuNumber: skuNumber,
		    SendMeRadionButton: SendMeRadionButton_val,
			YourEmailAddressTextBox: YourEmailAddressTextBox_val,
			YourNameTextBox: YourNameTextBox_val,
			FriendsNameTextBox: FriendsNameTextBox_val,
			FriendsEmailAddressTextBox: FriendsEmailAddressTextBox_val,
			EmailMessageTextBox: EmailMessageTextBox_val
		},
		success: function(answer) {
			if (answer.Error != null) {
				$j(".SendMail_Error").css("display", "block");				
				var errMess = $j(".SendMail_Error .jq_message");
                if (errMess.length) errMess.html(answer.Error);
			}
			else {
				$j(".SendMail_LinkPopup").css("display", "none");
				$j(".SendMail_HasBeenSent").css("display", "block");
				$j(".SendMail_HasBeenSent_fromPanel").css("display", (SendMeRadionButton_val ? "none" : "block"));
				if (SendMeRadionButton_val) {
					$j(".jq_SendMail_HasBeenSent_ToEmail").html(YourEmailAddressTextBox_val);
					$j(".jq_SendMail_HasBeenSent_ToName").html(YourNameTextBox_val);					
					$j(".jq_SendMail_HasBeenSent_FromName").html('');
					$j(".jq_SendMail_HasBeenSent_FromEmail").html('');
				}
				else {
					$j(".jq_SendMail_HasBeenSent_ToEmail").html(FriendsEmailAddressTextBox_val);
					$j(".jq_SendMail_HasBeenSent_ToName").html(FriendsNameTextBox_val);					
					$j(".jq_SendMail_HasBeenSent_FromEmail").html(YourEmailAddressTextBox_val);
					$j(".jq_SendMail_HasBeenSent_FromName").html(YourNameTextBox_val);
				}
				$j(".SendMail_HasBeenSent_Message").html(EmailMessageTextBox_val);                
                
                SendEmail.SetEmpty(SendMeRadionButton, SendToAFriendRadioButton, SendToAFriendPanel, EmailMessageTextBox, defaultMessage);
			}
			$j(".SendMail_WaitBlock").css("display", "none");
		},
		error: function(error) {
			$j(".SendMail_Error").css("display", "block");			
			var errMess = $j(".SendMail_Error .jq_message");
            if (errMess.length) errMess.html($j(".jq_PopupHttpError").html());			
			$j(".SendMail_WaitBlock").css("display", "none");
		},
		dataType: "json"
	});

	return false;

}
/*--- StartupScripts.js ---*/SettingsManager = function() { } 
        
SettingsManager.Get = function(name, value) {
    return (value != null && value != 'undefined') 
        ? $j('[als_' + name.toLowerCase() + '=' + value + ']')
        : $j('[als_' + name.toLowerCase() + ']');
}

SettingsManager.Value = function(element, name) {
    return $j(element).attr('als_' + name.toLowerCase());
}


InformationalTabs = function() { }

InformationalTabs.Click = function(anchor) {
	/*IE7 fast buttons switch*/
	var parent = $j(anchor).parents('.tabs').eq(0);
	var old_anchor = parent.find('.on').eq(0);

	old_anchor.removeClass('on');
	$j(anchor).addClass('on');

	/*IE7 fast content switch*/
	var old_id = old_anchor.attr('tab_anchor');
	$j('#tb_' + old_id).hide();
	var cur_id = $j(anchor).attr('tab_anchor');
	var cur_content = $j('#tb_' + cur_id);
	cur_content.show();

	var testimonials = cur_content.find('.JQtestimonials');
	if (testimonials.length > 0) {
		testimonials.children().hide();
		testimonials.find('li:first-child').show();
	}
}

InformationalTabs.setup = function() {

	InformationalTabs.setupWriteReviewLink();

	$j('.tabs a').click(function() { InformationalTabs.Click(this); });

	if (window.location.hash != '' && window.location.hash != '#') {
		$j('.tabs a').each(function() {
			var hash = window.location.hash.toString().toUpperCase();
			if (this.href.toString().toUpperCase().indexOf(hash) != -1) {
				InformationalTabs.Click(this);
			}
		});
	}

	/*
	window.productTab = new AnchorTab('.tabs', '.product_information_content', '.product_information_tab', 'on',
	function(anchor) {
	if (anchor == 'overview') {
	$j('.main-block').removeClass('tech-specs-tab');
	}
	else {
	$j('.main-block').addClass('tech-specs-tab');
	if (anchor == 'writereviews') $j('a.reviewsTabFlag').addClass('on');
	}
	if (anchor == 'writereviews') {
	$j('.main-block').removeClass('tech-specs-tab');
	$j('.main-block').addClass('write-review-tab');
	var iframe = $j('div.writereviews iframe');
	if ($j(iframe).attr('src') == null) {
	$j(iframe).attr('src', $j(iframe).attr('ref'))
	}

	}
	else {
	if (anchor != 'overview') {
	$j('.main-block').addClass('tech-specs-tab');
	}
	$j('.main-block').removeClass('write-review-tab');
	}
            	
	$j('.JQtestimonials').children().hide();
	$j($j('.JQtestimonials').children()[0]).show();

	}, null, false, null, false);

	window.productTab.Setup();
	*/
}

InformationalTabs.setupWriteReviewLink = function() {
	if ($j('.prSummaryWriteReviewLink').length == 0) {
		setTimeout(function() { InformationalTabs.setupWriteReviewLink(); }, 100);
	}
	else {
		$j('.prSummaryWriteReviewLink').click(function() { return OpenWriteReviewsTab(); });
	}

	if (window.location.hash.toUpperCase() == "#WriteReviews".toUpperCase()) {
		OpenWriteReviewsTab()
	}
}

HotProductLoader = function() { }
HotProductLoader.setup = function() {
    if ($j(".jqDynamicHotProductList").length > 0) {
        $j.ajax({
            type: "POST",
            url: Config.HotProductsUrl(),
            async: true,
            success: function(r) {
                $j(".jqDynamicHotProductList").html(r);
                if (r == "") {
                    $j(".jqDynamicHotProductPlace").hide();
                }
            }
        });
    }
}

WaysToBuyView = function() { }

WaysToBuyView.setupFooter = function(anchor) {
  anchor = anchor || "new";
  var showForPrefix = "ShowFor";
  var productTypes = ["New", "Used", "FactoryRefurbished", "International",
      "Variant", "Warranty"];
  var currentType = showForPrefix + anchor;
  for (var i = 0; i < productTypes.length; i++) {
    var productType = showForPrefix + productTypes[i];
    if (productType.toLowerCase() == currentType.toLocaleLowerCase())
      SettingsManager.Get(productType).show();
    else
      SettingsManager.Get(productType).hide();
  }
}

WaysToBuyView.setup = function() {
	window.wayToBuyTab = new AnchorTab('.way-buy-links', '.wayToBuyTabsContainer', '.wayToBuyTabContainer', 'on',
        function(anchor) { WaysToBuyView.TabClickCallback(anchor); }, '', false, 'new', false);
	window.wayToBuyTab.Setup();
	var anchor = document.location.hash != "" ? document.location.hash.replace('#', '') :
    Config.IsUsedProduct() == "1" ? "used" : "new";
	WaysToBuyView.setupFooter(anchor);
	WaysToBuyView.TabClickCallback(anchor);
}

WaysToBuyView.TabClickCallback = function(anchor) {
	/* change sku in product details */

	var sku = '';
	$j('.tabIdentifierSku input:hidden').each(function() {
		if (sku == '' && $j(this).parent().is('.' + anchor)) {
			sku = $j(this).val();
			if (sku != '') {
				$j('.ProductDetailsSkuNumberContainer').html(escape(sku));
				$j('#ProductDetailsSkuValue').val(escape(sku));
			}
		}
	});

	/* show or hide block dependency 'hideForUsed' attribute */

	var hideForUser = anchor == Config.UsedTabAnchor() || (anchor == '' && Config.IsUsedProduct() == '1')
	
	if (hideForUser) SettingsManager.Get('HideForUsed').each(function() {
		$j(this).hide();
	});
	else SettingsManager.Get('HideForUsed').each(function() {
		$j(this).show();
	});

	WaysToBuyView.setupFooter(anchor);

	var nav = $j('#nav');
	var overview = nav.find('[tab_anchor="overview"]').eq(0);
	if (overview.length > 0)
		InformationalTabs.Click(overview[0]);
}

/* Header and Footer begin */

HeaderFooter = function() {}

HeaderFooter.setup = function() {
    $j('.top-search-text-box').val('Search Adorama');
    $j('.bottom-search-text-box').val('Search Adorama');
    HeaderFooter.LoadPixSiteUrl('sid3');

    $j((".smenubar a.arrow,#support-btn")).hoverIntent({
        sensitivity: 3,
        interval: 200,
        over: makeTall,
        timeout: 500,
        out: makeShort
    });
    $j((".mb-items,#support-box")).hoverIntent({
        sensitivity: 1,
        interval: 0,
        over: doOverSM,
        timeout: 0,
        out: makeShort
    });
    $j(".smenubar a.arrow,.mb-items,#support-btn,#support-box").hover(function() { doOverFlag() }, function() { doOutFlag() });

    $j("#fp-tabs-cont li:first").slideDown(300);
    $j("#fp-tabs a:first").addClass("on");
    $j("#fp-tabs a.btn").click(function() {
        $j("#fp-tabs-cont li").not("." + this.id).hide();
        $j(this).addClass("on");
        $j("#fp-tabs a.btn").not(this).removeClass("on");
    });
}

HeaderFooter.LoadPixSiteUrl = function(name) {
	var cookieValue;
	if (document.cookie && document.cookie != '') {
		var cookies = document.cookie.split(';');
		for (var i = 0; i < cookies.length; i++) {
			var cookie = $j.trim(cookies[i]);
			/* Does this cookie string begin with the name we want? */
			if (cookie.substring(0, name.length + 1) == (name + '=')) {
				cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
				break;
			}
		}
	}
	if (cookieValue && cookieValue != 'undefined') {
		$j('#pix').attr('href', 'http://www.adoramapix.com?sid=' + cookieValue.toString());
		$j('#pix1').attr('href', 'http://www.adoramapix.com?sid=' + cookieValue.toString());
	}
}

/* Header and Footer end */

Search = function() { }
Search.Go = function(selector) {
	var searchTextBox = $j(selector);
	if (searchTextBox.val() == 'Search Adorama') {
		searchTextBox.val('');
	}

	if (!Validator.Check('ValidateTopSearch')) {
		return false;
	}

	SearchViewObject.Search('.top-search-text-box');

	return false;
}

Search.BottomGo = function(selector) {
	var searchTextBox = $j(selector);
	if (searchTextBox.val() == 'Search Adorama') {
		searchTextBox.val('');
	}

	if (!Validator.Check('ValidateBottomSearch')) {
		return false;
	}

	SearchViewObject.Search('.bottom-search-text-box');

	return false;
}

Search.ErrorPageGo = function(selector) {
	var searchTextBox = $j(selector);
	if (searchTextBox.val() == 'Search Adorama') {
		searchTextBox.val('');
	}

	if (!Validator.Check('ValidateErrorPageSearch')) {
		return false;
	}

	SearchViewObject.Search('#ErrorPageSearch');

	return false;
}

/* 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;
}

/* string utils end */


FeaturedItemsView = function() { }

FeaturedItemsView.setup = function() {
	window.featuredProductTab = new SimpleTab('.ov-in', '.featured_product_tabs', '.featured_product_tab', 'on', '.prev', '.next');
	window.featuredProductTab.Setup();
}



AdminArea = function() {}

AdminArea.setup = function() {
    $j('#tabs li a').click(function(){
        $j('.content div.content_item').hide();
        var tab = $j(this).attr('href').toString();
        $j(tab).show();
    });
    
    $j('#Preview').attr('src', '');
    $j('#tab_preview').click(function() {
        var source = $j('#hfCurrentContent').val();
        if (source != 'Not set') {
            source = source == '' ? source : 'http://' + $j.url.attr('host') + '/Als/Categories/' + source;
        $j('#Preview').attr('src', source);
        }
    });
}

CustomerTestimonialsView = function() { }
CustomerTestimonialsView.setup = function() {
    $j('.JQtestimonials').innerfade({ animationtype: 'fade', speed: 200, timeout: 5000, type: 'random', containerheight: '175px' });
}

PrintProductPage = function() {}
PrintProductPage.setup = function() {
    Utils.DisableButton('#panel-content');
    Utils.Setup(function() { Utils.DisableButton('.pb-body'); });  
    $j('.jq_ShowTabCheckBox input:checkbox:enabled').each(function(){this.checked = false;});
    $j('.jq_FirstShowTabCheckBox input:checkbox:enabled').each(function(){this.checked = true;});
}
PrintProductPage.CheckboxClickHandler = function(checkbox, container) {
    if ($j('#' + checkbox)[0].checked) { $j('#' + container).show(); }
    else { $j('#' + container).hide(); }
}

ItemBadgesView = function() {}

ItemBadgesView.setup = function() {
    window.ProcessingSku = new Object();
    window.ProcessingSku.OriginalDocumentWrite = document.write;
    window.ProcessingSku.Sku = new Array();
    
    SettingsManager.Get('sku').each(function() {
        var sku = SettingsManager.Value(this, 'sku');
        var container = $j(this);
        
        if(sku != null && sku != 'undefined')
        {        
            var exists = false;
            for(var i = 0; i < window.ProcessingSku.Sku.length; i++)
            {
                if(window.ProcessingSku.Sku[i].sku == sku) { exists = true; break; }
            }       
            if(exists == false) { 
                window.ProcessingSku.Sku.push({ sku: sku, container: container });
            }
        }
    });     
    
    window.ProcessingSku.Lock = null;
    window.ProcessingSku.Index = 0;
    for(var index = 0; index < window.ProcessingSku.Sku.length; index++) 
    { 
        setTimeout(function() { ItemBadgesView.setupOne(); }, (index + 1) * 100);
    }
}

ItemBadgesView.setupOne = function() {
	if (window.ProcessingSku.Lock == null) {
		window.ProcessingSku.Lock = new Object();

		document.write = function(text) { var temp = '<pre>' + text + '</pre>'; alert(temp); $j(window.ProcessingSku.Sku[window.ProcessingSku.Index].container).html(temp); }
		var url = Config.WebcollageUrl() + window.ProcessingSku.Sku[window.ProcessingSku.Index].sku;

		$j.getScript(url, function() {
			window.ProcessingSku.Index++;
			if (window.ProcessingSku.Index == window.ProcessingSku.Sku.length - 1) {
				document.write = window.ProcessingSku.OriginalDocumentWrite;
			}
			window.ProcessingSku.Lock = null;
		});
	}
	else {
		setTimeout(function() { ItemBadgesView.setupOne(); }, 100);
	}
}

PriceView = function() {}

PriceView.InStoreOnlyButtonMouseOut = function(e)
{
    $j('.InStoreOnlyPopup').hide();
}

PriceView.InStoreOnlyButtonMouseOver = function(e)
{
    if($j('.InStoreOnlyPopup').length == 0)
    {
        var text = '<div class="dot InStoreOnlyPopup" style="display:none;">' +
                    '<span class="invoke-panel inverse">' +
                        '<span class="invoke-bg">' + Config.InStoreOnlyText()  + '</span>' +
                    '</span>' +
	           '</div>';
        $j('body').append(text);	           
    }
    var popup = $j('.InStoreOnlyPopup');
    $j(popup).remove();
    $j(e).parent().append(popup);
    $j(popup).show();    
}


Loader = function() { }

Loader.checkProductPage = function(href) {
	return href.indexOf('.html') != -1;
}
Loader.checkPrintProductPage = function(href) {
	return href.indexOf('/printproductpage') != -1;
}
Loader.checkSearchPage = function(href) {
	return href.indexOf('/searchpage') != -1;
}
Loader.checkAdminArea = function(href) {
	return href.indexOf('/admin/staticcontent') != -1;
}
Loader.checkBrandSearchPage = function(href) {
	return href.indexOf('/brandsearch') != -1;
}

Loader.init = function() {
	var href = window.location.href.toString().toLowerCase();

	if (this.checkAdminArea(href)) {
		AdminArea.setup();
	}
	else {
		//$j("#imgbiz").lazyload(); //bizrate
		ClientCaching.setup();
		HotProductLoader.setup();
		setupWatermark();
		HeaderFooter.setup();
		FeaturedItemsView.setup();
		Utils.DisableAutoComplete();
		CustomerTestimonialsView.setup();
		HoursBox.Setup('.hoursBoxPanelClientID', '.HoursPanelClientID');
		Login.Setup();
		tb_init('a.thickbox, area.thickbox, input.thickbox'); /* pass where to apply thickbox */
		window.SearchViewObject = new SearchView();
		/*
		var combination = getcombo();
		if (combination != undefined) {
		if (combination == '0') {
		var sbwidth = 990, sbheight = 46;
		}
		}
		
		*/
		if (this.checkProductPage(href)) {
			InformationalTabs.setup();
			WaysToBuyView.setup();
		} else if (this.checkPrintProductPage(href)) {
			PrintProductPage.setup();
		}
		/*ItemBadgesView.setup();*/
	}
}

Loader.setup = function() {
    $j(document).ready(function() { Loader.init(); });
    if (typeof (Sys) != 'undefined') {
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function(sender, args) { Loader.init(); });
    }
}
/*--- tabs.js ---*/AnchorTab = function(tabsSelector, contentSelector, itemSelector, selectedTabCssClass, tabChangedHandler,
                        defaultTabAnchor, isPopup, defaultTabAnchorAfterPopupClosed, isSlideShow) {
    /*all css classes used for identifying elements must have lowercase names*/
    this.tabsSelector = tabsSelector;
    this.contentSelector = contentSelector;
    this.itemSelector = itemSelector;
    this.selectedTabCssClass = selectedTabCssClass;
    this.tabChangedHandler = tabChangedHandler;
    this.defaultTabAnchor = defaultTabAnchor;
    this.isPopup = isPopup;
    this.defaultTabAnchorAfterPopupClosed = defaultTabAnchorAfterPopupClosed;
    this.isSlideShow = isSlideShow;

    AnchorTab.prototype.Setup = function() {
        var tab = this;
        if (window.location.hash != '' && window.location.hash != '#') {
            $j(this.tabsSelector + ' a').each(function() {
                var hash = window.location.hash.toString().toUpperCase();
                if (this.href.toString().toUpperCase().indexOf(hash) != -1) {
                    tab.TabClick(this);
                }
            });
        }
        $j(this.tabsSelector + ' a').click(function() { tab.TabClick(this); });
    }

    AnchorTab.prototype.TabClick = function(a) {
       // debugger;
        $j(this.tabsSelector + ' a').removeClass(this.selectedTabCssClass);
        $j(a).addClass(this.selectedTabCssClass);

        var isnopopup = $j(a).attr("isnopopup");
        if ((this.isPopup == false) || (isnopopup == 'true')) {
            $j(this.contentSelector + ' ' + this.itemSelector).hide();
        }

        var anchor = $j(a)[0].hash.toString().toLowerCase().substring(1);
        if (typeof (isSlideShow) != 'undefined' && isSlideShow) {
            var tab = $j(this.contentSelector + ' .' + anchor);
            var speedTime = (tab.height() > 300 ? tab.height() : 300);
            $j(this.contentSelector + ' .' + anchor).slideDown(speedTime);
        }
        else {
            $j(this.contentSelector + ' .' + anchor).show();
        }

        if (this.tabChangedHandler && typeof (this.tabChangedHandler) == 'function')
            this.tabChangedHandler(anchor);

        if (this.isPopup == false) {
            if ($j(a).is('.showDefaultTabToo') && this.defaultTabAnchor != null && this.defaultTabAnchor != '') {
                $j(this.contentSelector + ' .' + this.defaultTabAnchor.toLowerCase()).css({ display: 'block' });
            }
        }
        return false;
    }

    AnchorTab.prototype.DefaultTabClick = function() {
        if (this.defaultTabAnchor) {
            window.location.hash = this.defaultTabAnchor;
            this.TabClick($j(this.tabsSelector + ' a.' + this.defaultTabAnchor.toLowerCase())[0]);
        }
    }

    AnchorTab.prototype.Close = function() {
        var anchorOrig = window.location.hash;
        var anchor = anchorOrig.toLowerCase();
        anchor = anchor.substring(1, anchor.length);
        $j(this.tabsSelector + ' a').removeClass(this.selectedTabCssClass);
        $j(this.itemSelector + '.' + anchor).css({ display: 'none' });
        window.location.hash = "#";

        if (this.defaultTabAnchorAfterPopupClosed) {
            AnchorTab.SelectTabByAnchor(this, this.defaultTabAnchorAfterPopupClosed);
        }
        return false;
    }
}

AnchorTab.Init = 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(); });
		}
	}
}

AnchorTab.SelectTabByAnchor = function(tab, anchor, innerAnchor, notScroll) {
    var anchorLocal = '#' + anchor.toString().toLowerCase();
    window.location.hash = anchor;
    $j(tab.tabsSelector + ' a').each(function() {
      if (this.href.toString().toLowerCase().indexOf(anchorLocal) != -1) {
        tab.TabClick(this);
        if(notScroll == null)
        {
            if (innerAnchor != null && typeof(innerAnchor) != 'undefined')
                Utils.scrollToAnchor(innerAnchor);
            else
                Utils.scrollToAnchor(this.id);
        }
      }
    });
}

AnchorTab.ReselectTab = function(tab, anchor) {
    $j(tab.tabsSelector + ' a.' + tab.selectedTabCssClass).each(function() {
        if($j(this).css('display') == 'none') {
            AnchorTab.SelectTabByAnchor(tab, anchor, true);
        }
    });
}


SimpleTab = function(tabsSelector, contentSelector, itemSelector, selectedTabCssClass, prevButtonSelector, nextButtonSelector) {
	SimpleTab.prototype.Setup = function() {
		var tab = this;
		$j(tabsSelector + ' a').click(function() {
			tab.TabClick(this);
		});

		$j(prevButtonSelector).click(function() {
			var current = tab.getSelectedIndex();
			if (current != 0)
				tab.TabClick($j(tabsSelector + ' a').eq(current - 1)[0]);
		});

		$j(nextButtonSelector).click(function(index) {
			var current = tab.getSelectedIndex();
			if (current != $j(tabsSelector + ' a').length - 1)
				tab.TabClick($j(tabsSelector + ' a').eq(current + 1)[0]);
		});
	}

	this.getSelectedIndex = function() {
		var indexLocal = 0;
		$j(tabsSelector + ' a').each(function(index) {
			if ($j(this).hasClass(selectedTabCssClass)) {
				indexLocal = index;
			}
		});
		return indexLocal;
	}

	SimpleTab.prototype.TabClick = function(a) {
    	/* temporarly removed, please see bug# 44577, it seems like it stops here */
		$j(tabsSelector + ' a').removeClass(selectedTabCssClass);
		$j(a).addClass(selectedTabCssClass);

		var aLocal = a;
		$j(tabsSelector + ' a').each(function(index) {
			var display = $j(this)[0].id == aLocal.id ? 'block' : 'none';
			$j(contentSelector + ' ' + itemSelector).eq(index).css({ display: display });
		});
		return false;
	}
}


/*--- thickbox.js ---*//*
 * Thickbox 3.1 - One Box To Rule Them All.
 * By Cody Lindley (http://www.codylindley.com)
 * Copyright (c) 2007 cody lindley
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/
		  
var tb_pathToImage = "http://www.adorama.com/Artworks2/als/Images/loadingAnimation.gif";

/* add thickbox to href & area elements that have a class of .thickbox */
function tb_init(domChunk){
    imgLoader = new Image(); /* preload image */
	imgLoader.src = tb_pathToImage;

	$j(domChunk).click(function(){
	var t = this.title || this.name || null;
	var a = this.href || this.alt;
	var g = this.rel || false;
	tb_show(t,a,g);
	this.blur();
	return false;
	});
}

function tb_show(caption, url, imageGroup) { /* function called when the user clicks on a thickbox link */

	try {
		if (typeof document.body.style.maxHeight === "undefined") {/* if IE 6 */
			$j("body","html").css({height: "100%", width: "100%"});
			$j("html").css("overflow","hidden");
			if (document.getElementById("TB_HideSelect") === null) {/* iframe to hide select elements in ie6 */
				$j("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
				$j("#TB_overlay").click(tb_remove);
			}
		}else{ /* all others */
			if(document.getElementById("TB_overlay") === null){
				$j("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
				$j("#TB_overlay").click(tb_remove);
			}
		}
		
		if(tb_detectMacXFF()){
			$j("#TB_overlay").addClass("TB_overlayMacFFBGHack");/* use png overlay so hide flash */
		}else{
			$j("#TB_overlay").addClass("TB_overlayBG"); /* use background and opacity */
		}
		
		if(caption===null){caption="";}
		$j("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");/*add loader to the page*/
		$j('#TB_load').show(); /* show loader */
		
		var baseURL;
	   if(url.indexOf("?")!==-1){ /* ff there is a query string involved */
			baseURL = url.substr(0, url.indexOf("?"));
	   }else{ 
	   		baseURL = url;
	   }
	   
	   var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
	   var urlType = baseURL.toLowerCase().match(urlString);

		if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){ /* code to show images */
				
			TB_PrevCaption = "";
			TB_PrevURL = "";
			TB_PrevHTML = "";
			TB_NextCaption = "";
			TB_NextURL = "";
			TB_NextHTML = "";
			TB_imageCount = "";
			TB_FoundURL = false;
			if(imageGroup){
				TB_TempArray = $j("a[rel="+imageGroup+"]").get();
				for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) {
					var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
						if (!(TB_TempArray[TB_Counter].href == url)) {						
							if (TB_FoundURL) {
								TB_NextCaption = TB_TempArray[TB_Counter].title;
								TB_NextURL = TB_TempArray[TB_Counter].href;
								TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>";
							} else {
								TB_PrevCaption = TB_TempArray[TB_Counter].title;
								TB_PrevURL = TB_TempArray[TB_Counter].href;
								TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>";
							}
						} else {
							TB_FoundURL = true;
							TB_imageCount = "Image " + (TB_Counter + 1) +" of "+ (TB_TempArray.length);											
						}
				}
			}

			imgPreloader = new Image();
			imgPreloader.onload = function(){		
			imgPreloader.onload = null;
				
			/* Resizing large images - orginal by Christian Montoya edited by me. */
			var pagesize = tb_getPageSize();
			var x = pagesize[0] - 150;
			var y = pagesize[1] - 150;
			var imageWidth = imgPreloader.width;
			var imageHeight = imgPreloader.height;
			if (imageWidth > x) {
				imageHeight = imageHeight * (x / imageWidth); 
				imageWidth = x; 
				if (imageHeight > y) { 
					imageWidth = imageWidth * (y / imageHeight); 
					imageHeight = y; 
				}
			} else if (imageHeight > y) { 
				imageWidth = imageWidth * (y / imageHeight); 
				imageHeight = y; 
				if (imageWidth > x) { 
					imageHeight = imageHeight * (x / imageWidth); 
					imageWidth = x;
				}
			}
			// End Resizing
			
			TB_WIDTH = imageWidth + 30;
			TB_HEIGHT = imageHeight + 60;
			$j("#TB_window").append("<a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key</div>"); 		
			
			$j("#TB_closeWindowButton").click(tb_remove);
			
			if (!(TB_PrevHTML === "")) {
				function goPrev(){
					if($j(document).unbind("click",goPrev)){$j(document).unbind("click",goPrev);}
					$j("#TB_window").remove();
					$j("body").append("<div id='TB_window'></div>");
					tb_show(TB_PrevCaption, TB_PrevURL, imageGroup);
					return false;	
				}
				$j("#TB_prev").click(goPrev);
			}
			
			if (!(TB_NextHTML === "")) {		
				function goNext(){
					$j("#TB_window").remove();
					$j("body").append("<div id='TB_window'></div>");
					tb_show(TB_NextCaption, TB_NextURL, imageGroup);				
					return false;	
				}
				$j("#TB_next").click(goNext);
				
			}

			document.onkeydown = function(e){ 	
				if (e == null) { /* ie */
					keycode = event.keyCode;
				} else { /* mozilla */
					keycode = e.which;
				}
				if(keycode == 27){ /* close */
					tb_remove();
				} else if(keycode == 190){ /* display previous image */
					if(!(TB_NextHTML == "")){
						document.onkeydown = "";
						goNext();
					}
				} else if(keycode == 188){ /* display next image */
					if(!(TB_PrevHTML == "")){
						document.onkeydown = "";
						goPrev();
					}
				}	
			};
			
			tb_position();
			$j("#TB_load").remove();
			$j("#TB_ImageOff").click(tb_remove);
			$j("#TB_window").css({display:"block"}); /* for safari using css instead of show */
			};
			
			imgPreloader.src = url;
		}else{/* code to show html */
			
			var queryString = url.replace(/^[^\?]+\??/,'');
			var params = tb_parseQuery( queryString );

			TB_WIDTH = (params['width']*1) || 630; /* defaults to 630 if no paramaters were added to URL */
			TB_HEIGHT = (params['height']*1) || 440; /* defaults to 440 if no paramaters were added to URL */
			ajaxContentW = TB_WIDTH;
			ajaxContentH = TB_HEIGHT;
			
			if(url.indexOf('TB_iframe') != -1){/* either iframe or ajax window */
					urlNoQuery = url.split('TB_');
					$j("#TB_iframeContent").remove();
					if(params['modal'] != "true"){ /* iframe no modal */
						$j("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key</div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>");
					}else{ /* iframe modal */
					$j("#TB_overlay").unbind();
						$j("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>");
					}
			}else{/* not an iframe, ajax */
					if($j("#TB_window").css("display") != "block"){
						if(params['modal'] != "true"){ /* ajax no modal */
						$j("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>close</a> or Esc Key</div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>");
						}else{ /* ajax modal */
						$j("#TB_overlay").unbind();
						$j("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>");							
						}
					}else{/* this means the window is already up, we are just loading new content via ajax */
						$j("#TB_ajaxContent")[0].style.width = ajaxContentW +"px";
						$j("#TB_ajaxContent")[0].style.height = ajaxContentH +"px";
						$j("#TB_ajaxContent")[0].scrollTop = 0;
						$j("#TB_ajaxWindowTitle").html(caption);
					}
			}
					
			$j("#TB_closeWindowButton").click(tb_remove);
			
				if(url.indexOf('TB_inline') != -1){	
					$j("#TB_ajaxContent").append($j('#' + params['inlineId']).children());
					$j("#TB_window").unload(function () {
						$j('#' + params['inlineId']).append( $j("#TB_ajaxContent").children() ); /* move elements back when you're finished */
					});
					tb_position();
					$j("#TB_load").remove();
					$j("#TB_window").css({display:"block"});
				}else if(url.indexOf('TB_iframe') != -1){
					tb_position();
					if($j.browser.safari){/* safari needs help because it will not fire iframe onload */
						$j("#TB_load").remove();
						$j("#TB_window").css({display:"block"});
					}
				}else{
					$j("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){/* to do a post change this load method */
						tb_position();
						$j("#TB_load").remove();
						tb_init("#TB_ajaxContent a.thickbox");
						$j("#TB_window").css({display:"block"});
					});
				}
			
		}

		if(!params['modal']){
			document.onkeyup = function(e){ 	
				if (e == null) { /* ie */
					keycode = event.keyCode;
				} else { /* mozilla */
					keycode = e.which;
				}
				if(keycode == 27){ /* close */
					tb_remove();
				}	
			};
		}
		
	} catch(e) {
		/*nothing here*/
	}
}

/*helper functions below*/
function tb_showIframe(){
	$j("#TB_load").remove();
	$j("#TB_window").css({display:"block"});
}

function tb_remove() {
 	$j("#TB_imageOff").unbind("click");
	$j("#TB_closeWindowButton").unbind("click");
	$j("#TB_window").fadeOut("fast",function(){$j('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();});
	$j("#TB_load").remove();
	if (typeof document.body.style.maxHeight == "undefined") {/*if IE 6*/
		$j("body","html").css({height: "auto", width: "auto"});
		$j("html").css("overflow","");
	}
	document.onkeydown = "";
	document.onkeyup = "";
	return false;
}

function tb_position() {
$j("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
	if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { /* take away IE6 */
		$j("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
	}
}

function tb_parseQuery ( query ) {
   var Params = {};
   if ( ! query ) {return Params;}/* return empty object */
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) {continue;}
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}

function tb_getPageSize(){
	var de = document.documentElement;
	var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
	arrayPageSize = [w,h];
	return arrayPageSize;
}

function tb_detectMacXFF() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    return true;
  }
}



/*--- Translation.js ---*//*-------- TranslationHelper -------*/
TranslationHelper = function() { }

TranslationHelper.GetTranslation = function(labelId) {
	if (typeof (trslArray[labelId]) == 'undefined') {
		var fullUrl = Config.GetTranslationUrl();
		$j.ajax({
			type: "POST",
			dataType: "json",
			url: fullUrl,
			async: false,
			data: { LabelId: labelId },
			success: function(answer) {
				var retVal = '';
				if (answer.Error == null) {
					retVal = answer.Message;
				}
				trslArray[labelId] = retVal;
			}
		});
	}
	if (typeof (trslArray[labelId]) != 'undefined') {
		return trslArray[labelId];
	}
	return '';
}

/*--- Utils.js ---*/function Utils()
{ }

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.scrollToAnchor = function(anchorName) {
	var anchor = $j("#" + anchorName);
	if (anchor.length != 0) {
		var targetOffset = anchor.offset().top;
		$j(window).scrollTop(targetOffset);
	}
	return false;
}

Utils.scrollToSelector = function(selector) {
var anchor = $j(selector);
	if (anchor.length != 0) {
		var targetOffset = anchor.offset().top;
		$j(window).scrollTop(targetOffset);
	}
	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.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.DisableAutoComplete = function() {
	$j('input:text').attr('autocomplete', 'off');
}

Utils.ShowCenteredPopup = function(url, width, height) 
{
 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=no';
 params += ', status=no';
 params += ', toolbar=no';
 newwin=window.open(url,'centeredPopupWindowname', params);
 if (window.focus) {newwin.focus()}
 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.ShowPopup = function(url, width, height, left, top) {
	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=no';
	params += ', status=no';
	params += ', toolbar=no';
	newwin = window.open(url, 'centeredPopupWindowname', params);
	if (window.focus) { newwin.focus() }
	return false;
}

Utils.ShowPopup = function(url, width, height) {
	var params = 'width=' + width + ', height=' + height;
	params += ', directories=no';
	params += ', location=no';
	params += ', menubar=no';
	params += ', resizable=no';
	params += ', scrollbars=no';
	params += ', status=no';
	params += ', toolbar=no';
	newwin = window.open(url, 'centeredPopupWindowname', params);
	if (window.focus) { newwin.focus() }
	return false;
}

Utils.DisableButton = function(containerSelector) {
	$j(containerSelector + ' input:button').attr('disabled', 'disabled');
	$j(containerSelector + ' input:submit').attr('disabled', 'disabled');
	$j(containerSelector + ' a').attr('disabled', 'disabled');
}

function S4() {
	return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
function guid() {
	return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}

SubscribeDropDown = function() {}

SubscribeDropDown.DropDown = function(btn){
	var dropDown = $j(btn).parents(".subscr-box").children(".subscribe_group");
	if (dropDown.css('display') == 'none') { dropDown.show(); }
	else { dropDown.hide(); }
	return false;
}
/*-------- HoursBox -------*/
HoursBox = function() {

}
HoursBox.Setup = function(hoursBoxPanel, HoursPanel) {
	$j(hoursBoxPanel + " a").click(function() {
		if ($j(hoursBoxPanel).hasClass('sht-on')) {
			$j(hoursBoxPanel).removeClass('sht-on');
			$j(HoursPanel).hide();
		}
		else {
			$j(hoursBoxPanel).addClass('sht-on');
			$j(HoursPanel).slideDown("fast");
		}
		return false;
	});
}

function RRWrapper(uniqueId, pageType, pageArea, idForPlacement) {

	var getUniqueId = uniqueId;
	var getPageType =  pageType;
	var getPageArea = pageArea;
	var getIdForPlacement = idForPlacement;

	function GetCombineKey(key) {
		return key + getUniqueId;
	}

	function getWindowProperty(key, defaultValue) {
		try {
			if (window[key] != undefined)
				return window[key];
		}
		finally { }

		window[key] = defaultValue;
		return defaultValue;
	}

	function setWindowProperty(key, value){
		window[key] = value;
	}

	function getCounter() {
		return getWindowProperty(GetCombineKey('r3_Counter'));
	}

	function setCounter(value) {
		return setWindowProperty(GetCombineKey('r3_Counter'), value);
	}

	function getOriginalDocumentWrite() {
		return getWindowProperty(GetCombineKey('r3_OriginalDocumentWrite'));
	}

	function setOriginalDocumentWrite(value) {
		return setWindowProperty(GetCombineKey('r3_OriginalDocumentWrite'), value);
	}

	function getLock() {
		return getWindowProperty(GetCombineKey('r3_Lock'));
	}

	function setLock(value) {
		return setWindowProperty(GetCombineKey('r3_Lock'), value);
	}

	function rr_write() {
	
		if (getLock() == null) {
			setLock(new Object());

			try {
				// override document.write function
				document.write = function(text) {
					var r3_placement = $j('#' + getIdForPlacement);

					if (r3_placement.length == 0) {
						r3_placement.html(text);
					} else {
						if (r3_placement.children().length == 0) {
							r3_placement.html(text);
						} else {
							var curHtml = r3_placement.children().eq(0).html();
							r3_placement.children().eq(0).html(curHtml + text);
						}
					}
					setCounter(getCounter() + 1);
				}
				r3_placement(getPageType + '.' + getPageArea);
			}
			finally {
				rr_reset();
			}
		}
	}

	function rr_reset() {
		if (getCounter() == 1) {
			document.write = getOriginalDocumentWrite();
			setCounter(0);
		} else {
			setTimeout(rr_reset, 150);
		}
	}

	RRWrapper.prototype.Execute = function() {
		
		setCounter(0);
		setOriginalDocumentWrite(document.write);
		setLock(null);

		if (getLock() == null) {
			rr_write();
		}
		else {
			setTimeout(rr_write, 200);
		}
	}
}

/*--- Validation.js ---*/function validateRequiredLi(source, args)
{
	var controltovalidate = $get(source.controltovalidate);
	if (args.Value == "" || args.Value == '')
	{
		args.IsValid = false;
		addClassToObject(controltovalidate.parentNode, "alertClient")
	}
	else
	{
		args.IsValid = true;
		removeClassFromObject(controltovalidate.parentNode, "alertClient");
	}
}

function validateEmailRegularWithServerLi(source, args)
{
	var controltovalidate = $get(source.controltovalidate);
	args.IsValid = args.Value.search(/^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/) != -1;
	var hiddenEmail = $get(registerObject.hiddenEmail);
	if (!args.IsValid)
	{
		addClassToObject(controltovalidate.parentNode, "alertClient")
	}
	else if (hiddenEmail.value != "1")
	{
		removeClassFromObject(controltovalidate.parentNode, "alertClient");
	}
}

function isEmailExist(source, args)
{
	var controltovalidate = $get(source.controltovalidate);
	var hiddenEmail = $get(registerObject.hiddenEmail);
	if (hiddenEmail.value == "3" || hiddenEmail.value == "2" || hiddenEmail.value == "0")
	{
		removeClassFromObject(controltovalidate.parentNode, "alertClient");
		args.IsValid = true;
	}
	else
	{
		addClassToObject(controltovalidate.parentNode, "alertClient")
		args.IsValid = false;
	}
}

function validateEmailServer(validatorId)
{
	var regularValidator = $get(validatorId);
	ValidatorValidate(regularValidator)

	var isValid = regularValidator.isvalid;
	var hiddenEmail = $get(registerObject.hiddenEmail);
	if (isValid)
	{
		hiddenEmail.value = "0";
		var email = $get($get(validatorId).controltovalidate).value;
		Als.Adorama.UI.ValidationService.ValidateEmail(email, validateEmailCallback, OnError, OnTimeout);
	}
	else
		hiddenEmail.value = "2";
}

function addClassToObject(object, className)
{
	if (object.className.indexOf(className) == -1)
		object.className = object.className + " " + className;
}

function removeClassFromObject(object, className)
{
	if (object.className.indexOf(className) != -1)
	{
		object.className = object.className.substring(0, object.className.indexOf(className));
	}
}

function validateEmailCallback(result)
{
	var hiddenEmail = $get(registerObject.hiddenEmail);
	hiddenEmail.value = result ? "1" : "3";

	if (hiddenEmail.value == "3")
	{
		try
		{
			updateEmail();
		}
		catch(e){}
	}

	ValidatorValidate($get(registerObject.vldEmail));
}

function OnError(fault)
{
	alert("Error occured:\n" + fault.get_message());
}

function OnTimeout()
{
	alert("Timeout occured");
}

/* checkbox list required validator */
function CheckboxListValidator()
{
    CheckboxListValidator.prototype.Validate = function(source, args)
    {
        args.IsValid = false;
        if(args.Value != '')
        {   
            var container = document.getElementById(args.Value);
            var collection = container.getElementsByTagName('input');
            if(collection.length > 0) 
            { 
                for(var i = 0; i < collection.length; i++) 
                { 
                    if(collection[i].type == 'checkbox' && collection[i].checked) 
                    { 
                        args.IsValid = true; 
                        break; 
                    } 
                }         
            }

        }
    }
}

/*--- Validator.js ---*//*-------- Validator -------*/
/*
Example of using:
 
<div validate_for="forYourEmail" class="ff-row">
<label>Your email address:<span>*</span></label>
<input validate="required email" validate_item="forYourEmail" type="text" />
</div>
<a href="#" onclick="return Execute(Validator,Validator.Check,'validate');">click</a>
*/

var Validator = {
    
	CheckSet: function(byattr, isSetToValid) {
	    
	    var ret = true;

		if (ret)
			$j('input[' + byattr + ']').each(
                    function() {
                    	var attr = $j(this).attr(byattr);
                    	var isvalid = true;

                    	if (isvalid && attr.indexOf('required') != -1) {
                    		if (isSetToValid)
                    		    $j(this).val('');
                    		else {
                    		    var val = $j(this).val();
                    		    isvalid = !Validator.isEmpty(val);
                    		}
                    	}

                    	if (isvalid && attr.indexOf('email') != -1) {
                    	    if (isSetToValid)
                    		    $j(this).val('');
                    		else {
                    		    var val = $j(this).val();
                    		    isvalid = !Validator.isNotEmail(val);
                    		}
                    	}
                        
                        if (!isSetToValid)
                        {
                            var attrSameVal = $j(this).attr(byattr + '_sameval');                        
                            if (attrSameVal)
                            {
                                var sameVal = $j(this).val();
                                $j('input[' + byattr + '_sameval=' + attrSameVal + ']').each(
                                    function() {
                                        if (sameVal != $j(this).val())
                                        {
                                            Validator.SetField(this, byattr, false);
                                            isvalid = false;
                                        }
                                    }
                                );
                            }
                        }
                        
                        
                    	Validator.SetField(this, byattr, isvalid);
                    	ret = ret && isvalid;
                    }
            );
        
        $j('[' + byattr + '_show]').each(
            function() {
                 var attr = $j(this).attr(byattr + '_show');
                 if (attr == 'none') $j(this).css("display", "none");
                 if (attr == 'valid') $j(this).css("display", (ret ? "block" : "none"));
                 if (attr == 'invalid') $j(this).css("display", (ret ? "none" : "block"));
                 if (attr == 'invalid animation') 
                 {
                    if (!ret)
                      {$j(this).show(500);}
                    else
                      { $j(this).css("display", "none"); }
                }
            }
        );
        
		return ret;
	    
	},
	Check: function(byattr) {
        return Validator.CheckSet(byattr, false);
	},
	SetField: function(it, byattr, is_correct) {
		var changecss = $j(it).attr(byattr + '_item');
		if (!is_correct)
			$j('[' + byattr + '_for=' + changecss + ']').addClass('err-field');
		else
			$j('[' + byattr + '_for=' + changecss + ']').removeClass('err-field');
	},
	isEmpty: function(val) {
		return (val.length <= 0);
	},
	isNotEmail: function(val) {
	return Validator.Test(val, "^[a-z0-9,!#\$%&'\*\+/=\?\^_`\{\|}~-]+(\.[a-z0-9,!#\$%&'\*\+/=\?\^_`\{\|}~-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*\.([a-z]{2,})$");
	},
	Test: function(val, p) {
		return !(val == '' || new RegExp(p).test(val));
	}
};

/*--- webkit.js ---*/if(Sys && Sys != 'undefined')
{
    Sys.Browser.WebKit = {}; //Safari 3 is considered WebKit

    if (navigator.userAgent.indexOf('WebKit/') > -1) 
    {
	    Sys.Browser.agent = Sys.Browser.WebKit;
	    Sys.Browser.version = parseFloat(navigator.userAgent.match(/WebKit\/(\d+(\.\d+)?)/)[1]);
	    Sys.Browser.name = 'WebKit';
    }
}
