
/** File: lists.js */
function toggleKeepCopyInList(checkboxElement,formId) {
   if(checkboxElement.checked)
       document.forms[formId].deleteFromList.value = false;
   else
       document.forms[formId].deleteFromList.value = true;
}

function showAddToListForm(divId,itemKey,itemType,callBackDivRef,callback, currentUrl, fromListId) {
    var url = "/community/addToListShowDialog.do?itemKey=" + itemKey + "&itemType="+itemType+"&parentUrl="+currentUrl+"&fromListId="+fromListId;
    $("div#"+divId).load(url,function(){callback(callBackDivRef)});
}

function showWishListItemReservationForm(divId,listItemId,userId,callBackDivRef, callback) {
    var url = "/community/wishListItemReservationShowDialog.do?listItemId=" + listItemId + "&userId="+userId;
    $("div#"+divId).load(url,function(){callback(callBackDivRef)});
}

function fillBlueReviewContainerDiv(divId,contentDivId) {
   var content = $("div#"+contentDivId).html();
   $("div#"+divId).html(content);
   selectBlueTab($("div#"+divId),'blueReviewContainer');
}

function showReserveListItemForm(divId,reservationFormContentDivId) {
   fillBlueReviewContainerDiv(divId,reservationFormContentDivId);
}

function showPostListCommentForm(divId,listCommentFormContentDivId) {
   fillBlueReviewContainerDiv(divId,listCommentFormContentDivId)
}

function createListShowHide() {
    if($("#newList >  #createList > .createListBody").css('display') != "none") {
        $("#newList > #newListBtn").css("background-color","#FFF");
         $("#newList >  #createList > .createListBody").fadeOut();
    }
    else {
        $("#newList > #newListBtn").css("background-color","#EBF4F5");
        $("#newList  >  #createList > .createListBody").fadeIn();
    }
}
 
function selectBlueTab(selectTab, selectedDiv) {
    var parentContainer = selectTab.parents('.lblueContainer');
    parentContainer.children(".lblueBoxContainer").css("display","block");
    parentContainer.children().children().removeClass("noBG");
    selectTab.children("span").removeClass("noBG");
    selectTab.siblings("a").children("span").addClass("noBG");
    var selectedDivRef =  parentContainer.children().children('.lblueBoxMain').children('.' + selectedDiv);
    if(selectedDivRef.siblings().css('display') != undefined) {
        selectedDivRef.siblings().css('display','none');
        selectedDivRef.css('display','block');
    }
    else {
        selectedDivRef.css('display','block');
    }
}

function deselectBlueTab(selectTab) {
    //select tab is reference to the selected blue tab (a link)
    var parentContainer = selectTab.parents(".lblueContainer");
    parentContainer.children(".lblueBoxContainer").css("display","none");
    parentContainer.children().children().addClass("noBG");
    selectTab.children("span").addClass("noBG");
    selectTab.siblings("a").children("span").addClass("noBG");
    parentContainer.children().children('.lblueBoxMain').children().fadeOut();
    /*selectedDivRef.siblings().fadeOut(function() {
    selectedDivRef.fadeOut();
        });*/
}

function swapListView(refDiv) {

    refDiv.fadeOut(function() {
         refDiv.siblings().fadeIn();
    });

}

function asyncFormSubmitCallback(callbackData, action, formId, onlb) {
 if($("#tempDiv").size() == 0)
        $(document.body).append("<div id='tempDiv' style='display:none;'></div>");
    $("#tempDiv").html(callbackData);
    var lbObjTemp = lbObjContainer.Get($("#tempDiv > div").attr("id"));
    if(lbObjTemp != undefined) {
        $("div#lightboxContainer").html(callbackData);
         lbShow(lbObjTemp);
         if (onlb)
           onlb();
    }
    else{
        action($("#tempDiv").children(),formId);
    }
}
function addToList(divRef,formId) {
    var popupRef;
    var refTab;
    // this is to check if the add to list is triggered from the grid view popup
    if($("#" + formId).parents('.popupListContent').attr('class') == 'popupListContent') {
        popupRef = $("#" + formId).parents('.popupListContent');
        }
    if($("#" + formId).attr("class") == 'updateListItem')
        refTab = $("#" + formId).parents('.lblueContainer').children(".lblueTabContainer").children().children(".wishListTab");
    else
        refTab = $("#" + formId).parents('.lblueContainer').children(".lblueTabContainer").children().children(".addToListTab");
   $($("#" + formId).parent()).html("<div class='listErrorMsg'>" + $(divRef).html() + "</div>");
    if(popupRef != undefined)
        setTimeout(function(){ hideA2L(popupRef)},3000);
    else
        setTimeout(function(){deselectBlueTab(refTab)},3000);
}

function prepareAsyncSelection(formId, action, param )
{
    $(document).ready(function() {
    	formAsync($("#" + formId), function( data ) {
            asyncFormSubmitCallback(data, action, formId);
            });
        });
}

function formAsync( form, callback )
{
    form.submit( function() {
        var url = form.attr("action");
    	if (url.charAt(url.length-1) == '?') url = url.substr(0, url.length-1);
    	var formElements=form[0].elements;
        var params = new Object();
	    for(var i=0;i<formElements.length; i++){
           if ( (formElements[i].type != 'radio' && formElements[i].type != 'checkbox') || formElements[i].checked) {
                params[formElements[i].name] = formElements[i].value;
           }
        }
        $.post(url, params, callback);
    	return false;
    });
}
var BLANKGIF = "/images/main/images2_5/shared/blank.gif";
//var tagsArray = new Array();
function blurTag(divRef) {
    var enteredVal;
    enteredVal = $(divRef).val();
    if($.trim($(divRef).val()) == '') 
        $("#" + divRef).val('click to enter your tag');
    else{
         if (formatTags(enteredVal,divRef)) {
            updateTagValues(divRef, true)
        };
//        formatTags($(divRef).val(),divRef);
//        tagsArray.push(enteredVal);
        $(divRef).val('click to enter your tag');
    }
}

function commaSeperatedTag(divRef) {
        var enteredVal;
        enteredVal = $(divRef).val();
        enteredVal = $.trim(enteredVal.substring(0,enteredVal.length-1));
        if (enteredVal != "") {
        if (formatTags(enteredVal,divRef)) {
            updateTagValues(divRef)
        };
//        tagsArray.push(enteredVal);
         $(divRef).val('');
        }
        else
            $(divRef).val('');
}

function updateTagValues(divRef, doTriggerOnChange) {
//    ($(divRef).parent('.tagContainer').children('.eachTag').children('.tagCenter').children('.tagText')).each(function (){
//       alert($(this).text());
//    });
    var tagTextDiv = $(divRef).parent('.tagContainer').children('.eachTag').children('.tagCenter').children('.tagText');
    var tagTexts = new Array();
    tagTextDiv.each(function() {
        var tagText = $(this).text();
        if (tagText)
            tagTexts.push(tagText);
    });
    $(divRef).parent('.tagContainer').children('.tagValues').val(tagTexts.join(","));
   // alert($(divRef).parent('.tagContainer').children('.tagValues').attr("class"));
    if(doTriggerOnChange)
        $(divRef).parent('.tagContainer').children('.tagValues').trigger("onchange",function(){});
}

function formatTags(tagText, divRef) {
   // if(!onTagClickFunction)
        onTagClickFunction = '';
   // alert("format tags version: "+onTagClickFunction);
//        var numTags = tagsArray.length;
        var tagsVar = '';
        tagsVar +=   "<div class='eachTag'>"
        tagsVar +=   "<div class='tagCenter'>"
        tagsVar +=      "<div class='tagLeft'><img src='" + BLANKGIF + "' width='7px' height='17px'><!-- --></img></div>"
        tagsVar +=      "<div class='tagText'>" + tagText + "</div>"
        tagsVar +=      "<div class='tagRight'><a href='#' onclick=\"removeTag($(this));"+onTagClickFunction+"; return false;\"><img src='" + BLANKGIF + "' width='12px' height='17px'><!-- --></img></a></div>"
        tagsVar +=  "</div></div>";
    //alert(tagsVar);
        $(divRef).before(tagsVar);
    return true;
}

function removeTag(tagRef) {
    $(tagRef).parents('.eachTag').fadeOut();
    var divRef = $(tagRef).parents('.tagContainer').children('.newTag')
    $(tagRef).parents('.eachTag').remove();
    updateTagValues(divRef, true);
}

function initializeExistingTags(tagArr, textBoxRef) {
    var tempTagArr = tagArr.split(',');
     for(var i=0; i<tempTagArr.length; i++){
         if($.trim(tempTagArr[i]) != '')
            formatTags(tempTagArr[i],textBoxRef);
        }
      updateTagValues(textBoxRef,false);
}

function toggleDoUpdate(formId, elementId, checkboxRef) {
//    alert("toggled " + formId + " for element " + elementId);
//    alert(document.forms[formId]);
//    alert(document.getElementById(elementId));
//    alert(document.getElementById(elementId).value);
        document.getElementById(elementId).value = 'true';
    
//   alert('do updated');
//    alert(document.getElementById(elementId).value);
}

function toggleCheckboxUpdate(formId, elementId, checkboxRef) {
    if ($(checkboxRef).attr('checked'))
        document.getElementById(elementId).value = 'true';
    else
        document.getElementById(elementId).value = 'false';
}

function allCheckboxesSelected(elementRef){
    var allChecked = true;
    $('.' + elementRef).each(function(){
        if(!$(this).attr("checked")){
            allChecked = false;
        }
    });
    return allChecked;
}

function toggleDoUpdateAll(formId, checkboxRef,linkRef, elementRef) {

    if($(linkRef).text() != "check all"){
        $(linkRef).html('check all');
        clearAllCheckboxes(formId, checkboxRef,linkRef, elementRef)
    }
    else{
        $(linkRef).html('clear all');
        checkAllCheckboxes(formId, checkboxRef,linkRef, elementRef)
    }
}

function checkAllCheckboxes(formId, checkboxRef,linkRef, elementRef){
    $('.' + checkboxRef).attr('checked','true');
    $('.' + elementRef).attr('value','true');
}

function clearAllCheckboxes(formId, checkboxRef,linkRef, elementRef){
    $('.' + checkboxRef).removeAttr('checked');
    $('.' + elementRef).attr('value','false');
}

function copyShowHideWishListRadio(radioRef) {
    if(radioRef.value == "wish_list" && radioRef.checked)
        $(".copyListRegistry").css("display","block");
    else
       $(".copyListRegistry").css("display","none");
    fixWishlistProblem(radioRef);
}

function fixWishlistProblem(radioRef){
    if(radioRef.value != "wish_list"){
        $('#typeWishlist').removeAttr("checked");
    }else{
        $('#typeWishlist').attr("checked","true");
    }
}

function copyShowHideWishList(selectRef) {
    if($(selectRef).children('option:selected').attr('title') == "wish_list")
        $(".copyListRegistry").css("display","block");
    else
       $(".copyListRegistry").css("display","none");
}

/*** AM new homepage design ***/
var scrollList = new Array();
var scrollListIndex = new Array();

function scrollListScrollLeft(scrollObj){
    var aScrollList = scrollList[scrollObj];
    var aScrollListIndex = scrollListIndex[scrollObj];
    if(aScrollList == null){
        aScrollList = $(scrollObj);
        aScrollListIndex = 0;
    }
    if(aScrollListIndex > -1 ){
         if(aScrollListIndex != 0)
            aScrollListIndex -= 1;
        $(aScrollList[aScrollListIndex]).css("display","block");
    }
    scrollList[scrollObj] = aScrollList;
    scrollListIndex[scrollObj] = aScrollListIndex;
}

function scrollListScrollRight(scrollObj,listLength){
    var aScrollList = scrollList[scrollObj];
    var aScrollListIndex = scrollListIndex[scrollObj];

    if(aScrollList == null){
        aScrollList = $(scrollObj);
        aScrollListIndex = 0;
    }
    if(aScrollListIndex != aScrollList.length - listLength){
        $(aScrollList[aScrollListIndex]).css("display","none");
        if(aScrollListIndex != aScrollList.length - listLength)
            aScrollListIndex += 1;
    }
    scrollList[scrollObj] = aScrollList;
    scrollListIndex[scrollObj] = aScrollListIndex;
}

function scrollListRight(e){
	//copy the onclick content cause we will disable it
	//otherwise user can rapid click the button and this
	//causes problems
	var caller = e.srcElement;
	if(caller == null)
		caller = e.currentTarget;

	$(caller).removeAttr("onmousedown");
	$(caller).unbind("click");

	var sliderDiv = e.data.slider;
	var left = parseInt(sliderDiv.css("left"));
	var width = parseInt(sliderDiv.css("width"));
	var offset = parseInt($(sliderDiv).parent().css("width"));

	if(left - offset >= (-1*width) && (left - offset)+width > 100){
		sliderDiv.animate({
			"left":(left-offset)+"px"
		},"slow",function(){
			$(caller).bind("click",{slider:sliderDiv},scrollListRight);
		});
	}else{
		//slider.animate({"left":(-1*width)+offset+"px"});
		$(caller).bind("click",{slider:sliderDiv},scrollListRight);

	}
	return false;
}

function scrollListLeft(e){
	//copy the onclick content cause we will disable it
	//otherwise user can rapid click the button and this
	//causes problems
	var caller = e.srcElement;
	if(caller == null)
		caller = e.currentTarget;

	$(caller).removeAttr("onmousedown");
	$(caller).unbind("click");

	var sliderDiv = e.data.slider;
	var left = parseInt(sliderDiv.css("left"));
	var width = parseInt(sliderDiv.css("width"));
	offset = parseInt($(sliderDiv).parent().css("width"));

	if(left < 0){
		sliderDiv.animate({
			"left":(left+offset)+"px"
		},"slow",function(){
			$(caller).bind("click",{slider:sliderDiv},scrollListLeft);
		});
	}else{
		//slider.animate({"left":(-1*width)+offset+"px"});
		$(caller).bind("click",{slider:sliderDiv},scrollListLeft);

	}
	return false;
}


//this function is used when there are star ratings in the blue box container, like in the wide organice search grid and we want to hide the number of ratings when the blue box opens to prevent the over lapping of the number of ratings text and the blue box
function toggleStarNumRating(refDiv) {
    var ratingRef = refDiv.parents('.lblueContainer').find('.ratingNum');
    if(ratingRef) {
        if(ratingRef.css('display') != 'none')
            ratingRef.css('display','none');
        else {
            ratingRef.css('display','block');
        }
    }
}

/** File: library.js */
var count,timeoutID, IsNav4, IsStand, objVar, IsIE4
   IsNav4 = false;
   IsIE4 = false;
   IsDOM = false;
   IsDHTML = false;
   if (document.all) {
   	IsIE4 = true;
   	IsDHTML = true;
   }
   else if (document.getElementById)
          {
   		IsDOM = true;
   		IsDHTML = true;
          }

   else if(parseInt(navigator.appVersion) == 4 && navigator.appName == "Netscape") {
   		IsNav4 = true;
   		IsDHTML = true;
   }

   function addLoadEvent(func) {
	   var oldonload = window.onload;
	   if (typeof window.onload != 'function') {
	     window.onload = func;
	   } else {
	     window.onload = function() {
	       oldonload();
	       func();
	     }
	   }
	 }

	function formatCurrency(amount, pruneWholeNumbers)
	{
		var initial = parseFloat(amount);
		if(isNaN(initial)) { return 0.00; }

		var minus = '';
		if(initial < 0) { minus = '-'; }
		initial = Math.abs(initial);
		initial = parseInt((initial + .005) * 100);
		initial = initial / 100;
		s = new String(initial);
		if(s.indexOf('.') < 0) { s += '.00'; }
		if(s.indexOf('.') == (s.length - 2)) { s += '0'; }

		sNew = "";
		end = s.length-3;
		start = 0;

		//add commas
		for(i=start;i<end;i++) {
			if((end-i) % 3 == 0 && i>0) {
				sNew =sNew + ",";
			}
			sNew = sNew + s.charAt(i) ;
		}

		//add decimals
		for(i=end;i<s.length;i++) {
			sNew = sNew + s.charAt(i);
		}

		//add the minus sign
		if(i<0) {
			sNew = "-" + sNew;
		}

		if(pruneWholeNumbers && sNew.indexOf('.00') > 0) {
			sNew  = sNew.substring(0,sNew.indexOf('.00'));
		}

		return minus + sNew;
	}


	function decimalPoints(number, decimalPoints) {
		if(isNAN(number)) {
			return 0;
		}
		if(number.toFixed) {
     	 return number.toFixed(decimalPoints);
		}
		return number;
	}  
		
		
	function confirmUrlRequest(msg, url) {
		if(window.confirm(msg)) {
			window.location.href=url;
		}
	}
	
	function getXMLHttpRequest() { 
		var xmlhttp; 
	/*@cc_on
	@if (@_jscript_version >= 5) 
		try { 
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); 
		} catch (e) { 
			try { 
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
			} catch (E) { 
				xmlhttp = false; 
			} 
		} 
	@else 
		xmlhttp = false; 
	@end @*/
		if (!xmlhttp && typeof XMLHttpRequest != 'undefined') { 
			try { 
				xmlhttp = new XMLHttpRequest(); 
			} catch (e) { 
				xmlhttp = false; 
			} 
		} 
		return xmlhttp; 
	}


   function setZIndex(obj, zOrder) {

   	if (IsIE4) {
   	 	obj.style.zIndex = zOrder;
   	}

   	else if(IsNav4) {
   		obj.zIndex = zOrder;
   	}
   	else if(IsDOM) {
   		obj.zIndex = zOrder;
   	}
   }   

   function getObj(layerName) {
   	if(IsNav4) {
   		 return eval("document." + layerName); 	}
   	else if(IsIE4) {
   		return eval("document.all." + layerName); }
   	else if(IsDOM) {
   		return document.getElementById(layerName)	}
	}

	function makeInherit(obj) {
        obj.style.visibility="inherit";		
	}
	
	function makeVisible(obj) {
		if(IsDOM) {
	        obj.style.visibility="visible";		}
		else if(IsIE4) {
			obj.style.visibility = "visible"; 	}
		else if(IsNav4) {
			obj.visibility = "visible"; 	}
	}

	function makeHidden(obj) {
		if(IsDOM) {
	    obj.style.visibility= "hidden";	}
		else if(IsIE4) {
		obj.style.visibility = "hidden"; }
		else if(IsNav4) {
		obj.visibility = "hidden"; }
	
	}
	
	
	
	function writeText(strToWrite, layerId) {
		var layer = getObj(layerId);
		layer.innerHTML = '';
		layer.innerHTML = strToWrite;
	}

	function HttpObject() {
		function _nullEvent() {
			;
		}
		function _send() {			
			var request = this.xmlHttp;
			request.open(this.method, this.url);
			request.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
			request.onreadystatechange = this.statechange;
			request.send(null);
		}
		this.xmlHttp     = getXMLHttpRequest();
		var request = this.xmlHttp;
		var myHttpObj = this;
		this.statechange = function () {
								var xmlReq = myHttpObj.xmlHttp;
								if(xmlReq.readyState == 1) {
									myHttpObj.onStart();
								}
								else if(xmlReq.readyState == 4) {
									if(xmlReq.status == 200) {
										myHttpObj.onSuccess();
									}
									else {
										myHttpObj.onFailure();
									}
								}
							};
		this.send        = _send;
		this.method      = "GET";
		this.url 		 = '';
		this.onStart	 = _nullEvent;
		this.onSuccess   = _nullEvent;
		this.onFailure   = _nullEvent;
	}

	
	function submitHttpRequest(getURL, startText, completionText, layerName) {
		var startFunction = function() {
			writeText(startText,layerName);
		}
		var completionFunction = function() {
			writeText(completionText, layerName);
		}
	
		var httpObject = new HttpObject();
		if(startText.length > 0) {
			httpObject.onStart   = startFunction;
		}
		httpObject.onFailure = completionFunction;
		httpObject.onSuccess = completionFunction;
		httpObject.url =  getURL;
		httpObject.send();
	}
	


    function install( aEvent, extName, iconURL, url) {		
        var params = new Array();
       
		if (url != null)
		{
			href = url;
		}
		else
		{
			var href = aEvent.target.href;
		}
		
		params[extName] = {URL: href, IconURL: iconURL, toString: function () { return this.URL; } };
		
        InstallTrigger.install(params);

        try {
            var p = new XMLHttpRequest();
            p.open("GET", "/core/install.php?uri="+href, true);
            p.send(null);
        } catch(e) { }
        return false;
    }

//***********************************************************************//
//**************************downloadInterceptor***************************************//

var IsIE, IsIE6Plus, IsWin2kPlus, popWidth, popHeight;

popWidth=400;
popHeight=300;

IsIE = false;
IsFirefox = false;
IsIE6Plus = false;
IsWin2kPlus = false;
IsFirefox15Plus = false;

var useragent = navigator.userAgent.toLowerCase();
var downloadUrl = 'http://download.pronto.com/download/prontoapp/pronto-beta.exe';
var firefoxdl= 'http://download.pronto.com/firefox/prontoFox.xpi';
if ( useragent.indexOf("windows nt 5") != -1
	|| useragent.indexOf("windows xp") != -1
	|| useragent.indexOf("windows 2000") != -1
	|| useragent.indexOf("winnt5") != -1
	|| useragent.indexOf("winnt 5") != -1
	) {
		IsWin2kPlus = true;
}

if (useragent.indexOf("opera") == -1
	&& useragent.indexOf("gecko") == -1
	&& useragent.indexOf("netscape") == -1
	&& useragent.indexOf("safari") == -1
	&& useragent.indexOf("konqueror") == -1
	&& useragent.indexOf("webtv") == -1
	&& useragent.indexOf("omniweb") == -1
	&& useragent.indexOf("msie") != -1) {
		IsIE = true;
		if (useragent.indexOf("msie 6") != -1
			|| useragent.indexOf("msie 7") != -1) {
			IsIE6Plus = true;
		}
}

IsFirefox= (useragent.indexOf("firefox") > -1);

function checkFirefoxVersion(allowedVersion) {
	if(!IsFirefox) {
		return false;
	}
	agent = window.navigator.userAgent;
	version = agent.substring(agent.lastIndexOf("/")+1);
	//if the first character is a "." prepend "0"	
	if(version.substring(0,1) == "."){
		version = "0" + version ;
	}
	versionArray = version.split(".");
	if(versionArray.length >= 2) {
		fullVersion = versionArray[0] + "." + versionArray[1];
	}
	else if(versionArray.length ==1 ) {
		fullVersion = versionArray[0];
	}
	return parseFloat(fullVersion)>= parseFloat(allowedVersion);
}

if(IsFirefox) {
	IsFirefox15Plus = checkFirefoxVersion(1.5);
}

function noFunction() {
}

// pf_popups.js
function editoption()
{
	//alert("hello");
	window.open('pf_eula_preventinstall.html', 'winname');
}

// cookie stuff
function setCookie(name, value, expires) {
	setCookieWithDomain(name,value,expires,".pronto.com");
}

function setCookieWithDomain(name, value, expires, domain) {
	var cookieString = name + "=" + escape(value) + "; path=/; domain="+domain;
	if (expires != null) {
		cookieString += "; expires=" + expires.toGMTString();
	}
	document.cookie = cookieString;
}

function setLandingPage(landingPage, domain) {
	var expires = new Date();
	expires.setDate(expires.getDate() + 30); //30 days
	setCookieWithDomain("landingPage", landingPage, expires, domain);
}

function getCookieValue(name) {
	var cookieString = document.cookie;
	var start = cookieString.indexOf(name + "=");
	if (start == -1) { return null; }
	var end = cookieString.indexOf(";", start);
	end = end == -1 ? cookieString.length : end;
	return unescape(cookieString.substring(start + name.length + 1, end));
}

function deleteCookie(name) {
	setCookie(name, "", new Date(0));
}

// tab dropdown functions
var subdropTimer = null;
var currentSub = null;

function subdropOn(divid) {
	if(currentSub == divid)
		clearTimeout(subdropTimer);
	else if(currentSub != null)
		document.getElementById(currentSub).style.display = 'none';

	var drop = document.getElementById(divid);
    drop.style.width = document.getElementById(divid + 'container').offsetWidth + 10 + 'px';
	drop.style.display = 'block';
	currentSub = divid;
}

function subdropOff(divid) {
	subdropTimer = setTimeout('dosubdropOff(\'' + divid + '\')', 500);
}

function dosubdropOff(divid) {
	var drop = document.getElementById(divid);
	drop.style.display = 'none';
}

//browse category popup
var browseCatTimer = null;

function showBrowseCat(divid, xoffset, yoffset) {
	if(isSEM)
		var url = '/browseCategoriesDropDown.do?SEM=true';
	else
		var url = '/browseCategoriesDropDown.do';

    if ($("div#" + divid).css("display") == "none") {
        if(xoffset != undefined && yoffset != undefined) {
            $("div#" + divid).load(url, function() {
                var xAdjust = -66;
                if(jQuery.browser.msie && jQuery.browser.version == '6.0')
                    var yAdjust = -3;
                else
                    var yAdjust = -2;
                $("div#" + divid).css("left", xoffset + xAdjust +  "px");
                $("div#" + divid).css("top", yoffset  + yAdjust + "px");
                $("div#" + divid).css("display", 'block');
            })
            if(jQuery.browser.msie && jQuery.browser.version == '6.0')
                $("#navigation_head").find(".navselect").hide();
        }
    }
}

function hideBrowseCat(divid) {
    $("div#" + divid).css("display", "none");
    if(jQuery.browser.msie && jQuery.browser.version == '6.0')
                $("#navigation_head").find(".navselect").show();
}

function showAllDepts(divid, xoffset, yoffset) {
    if ($("div#" + divid).css("display") == "none") {
        if(xoffset != undefined && yoffset != undefined) {
            $("div#" + divid).load('/browseCategoriesDropDown.do?linkType=department',function(){
                $("div#" + divid).css("left", xoffset - 361 + "px");
                $("div#" + divid).css("top", yoffset  - 4 + "px");
                $("div#" + divid).css("display", 'block');
            })
        }
    }
}


function showMyPronto(divid, xoffset, yoffset) {
    if ($("div#" + divid).css("display") == "none") {
        if(xoffset != undefined && yoffset != undefined) {
             $("div#" + divid).siblings('.prontoLinks').css("display", "block");
            $("div#" + divid).css("left", xoffset - 7 + "px");
            $("div#" + divid).css("top", yoffset  - 4 + "px");
            $("div#" + divid).siblings('.prontoLinks').css("left", xoffset - 7 + "px");
            $("div#" + divid).siblings('.prontoLinks').css("top", yoffset  - 4 + "px");

        }
        $("div#" + divid).css("display", 'block');
        $("div#" + divid).siblings('.prontoLinks').css("display", 'block');
    }
}

function hideShowPronto(divid) {
    $("div#" + divid).css("display", "none");
    $("div#" + divid).siblings(".prontoLinks").css("display", "none")
}


function hideSection(container) {
    $('#'+container).hide();
}

function showSection(container) {
    $('#'+container).show();
}

function slideUp(container) {
    $('#' + container).slideUp(300);
}

function slideDown(container) {
    $('#' + container).slideDown(300);
}

function fastSlideUp(container) {
    $('#' + container).slideUp(100);
}

function fastSlideDown(container) {
    $('#' + container).slideDown(100);
}

// messaging alert. example: send a friend from product page returns to product page with alert
setTimeout(function(){ $('.outputMessageContainer').fadeIn('slow'); }, 2000);
setTimeout(function(){ $('.outputMessageContainer').fadeOut('slow'); }, 6000);

/** File: jquery-1-2-6.js */
/*
 * jQuery 1.2.6 - New Wave Javascript
 *
 * Copyright (c) 2008 John Resig (jquery.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * $Date: 2008/12/30 19:47:58 $
 * $Rev: 5685 $
 */
(function(){var _jQuery=window.jQuery,_$=window.$;var jQuery=window.jQuery=window.$=function(selector,context){return new jQuery.fn.init(selector,context);};var quickExpr=/^[^<]*(<(.|\s)+>)[^>]*$|^#(\w+)$/,isSimple=/^.[^:#\[\.]*$/,undefined;jQuery.fn=jQuery.prototype={init:function(selector,context){selector=selector||document;if(selector.nodeType){this[0]=selector;this.length=1;return this;}if(typeof selector=="string"){var match=quickExpr.exec(selector);if(match&&(match[1]||!context)){if(match[1])selector=jQuery.clean([match[1]],context);else{var elem=document.getElementById(match[3]);if(elem){if(elem.id!=match[3])return jQuery().find(selector);return jQuery(elem);}selector=[];}}else
return jQuery(context).find(selector);}else if(jQuery.isFunction(selector))return jQuery(document)[jQuery.fn.ready?"ready":"load"](selector);return this.setArray(jQuery.makeArray(selector));},jquery:"1.2.6",size:function(){return this.length;},length:0,get:function(num){return num==undefined?jQuery.makeArray(this):this[num];},pushStack:function(elems){var ret=jQuery(elems);ret.prevObject=this;return ret;},setArray:function(elems){this.length=0;Array.prototype.push.apply(this,elems);return this;},each:function(callback,args){return jQuery.each(this,callback,args);},index:function(elem){var ret=-1;return jQuery.inArray(elem&&elem.jquery?elem[0]:elem,this);},attr:function(name,value,type){var options=name;if(name.constructor==String)if(value===undefined)return this[0]&&jQuery[type||"attr"](this[0],name);else{options={};options[name]=value;}return this.each(function(i){for(name in options)jQuery.attr(type?this.style:this,name,jQuery.prop(this,options[name],type,i,name));});},css:function(key,value){if((key=='width'||key=='height')&&parseFloat(value)<0)value=undefined;return this.attr(key,value,"curCSS");},text:function(text){if(typeof text!="object"&&text!=null)return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(text));var ret="";jQuery.each(text||this,function(){jQuery.each(this.childNodes,function(){if(this.nodeType!=8)ret+=this.nodeType!=1?this.nodeValue:jQuery.fn.text([this]);});});return ret;},wrapAll:function(html){if(this[0])jQuery(html,this[0].ownerDocument).clone().insertBefore(this[0]).map(function(){var elem=this;while(elem.firstChild)elem=elem.firstChild;return elem;}).append(this);return this;},wrapInner:function(html){return this.each(function(){jQuery(this).contents().wrapAll(html);});},wrap:function(html){return this.each(function(){jQuery(this).wrapAll(html);});},append:function(){return this.domManip(arguments,true,false,function(elem){if(this.nodeType==1)this.appendChild(elem);});},prepend:function(){return this.domManip(arguments,true,true,function(elem){if(this.nodeType==1)this.insertBefore(elem,this.firstChild);});},before:function(){return this.domManip(arguments,false,false,function(elem){this.parentNode.insertBefore(elem,this);});},after:function(){return this.domManip(arguments,false,true,function(elem){this.parentNode.insertBefore(elem,this.nextSibling);});},end:function(){return this.prevObject||jQuery([]);},find:function(selector){var elems=jQuery.map(this,function(elem){return jQuery.find(selector,elem);});return this.pushStack(/[^+>] [^+>]/.test(selector)||selector.indexOf("..")>-1?jQuery.unique(elems):elems);},clone:function(events){var ret=this.map(function(){if(jQuery.browser.msie&&!jQuery.isXMLDoc(this)){var clone=this.cloneNode(true),container=document.createElement("div");container.appendChild(clone);return jQuery.clean([container.innerHTML])[0];}else
return this.cloneNode(true);});var clone=ret.find("*").andSelf().each(function(){if(this[expando]!=undefined)this[expando]=null;});if(events===true)this.find("*").andSelf().each(function(i){if(this.nodeType==3)return;var events=jQuery.data(this,"events");for(var type in events)for(var handler in events[type])jQuery.event.add(clone[i],type,events[type][handler],events[type][handler].data);});return ret;},filter:function(selector){return this.pushStack(jQuery.isFunction(selector)&&jQuery.grep(this,function(elem,i){return selector.call(elem,i);})||jQuery.multiFilter(selector,this));},not:function(selector){if(selector.constructor==String)if(isSimple.test(selector))return this.pushStack(jQuery.multiFilter(selector,this,true));else
selector=jQuery.multiFilter(selector,this);var isArrayLike=selector.length&&selector[selector.length-1]!==undefined&&!selector.nodeType;return this.filter(function(){return isArrayLike?jQuery.inArray(this,selector)<0:this!=selector;});},add:function(selector){return this.pushStack(jQuery.unique(jQuery.merge(this.get(),typeof selector=='string'?jQuery(selector):jQuery.makeArray(selector))));},is:function(selector){return!!selector&&jQuery.multiFilter(selector,this).length>0;},hasClass:function(selector){return this.is("."+selector);},val:function(value){if(value==undefined){if(this.length){var elem=this[0];if(jQuery.nodeName(elem,"select")){var index=elem.selectedIndex,values=[],options=elem.options,one=elem.type=="select-one";if(index<0)return null;for(var i=one?index:0,max=one?index+1:options.length;i<max;i++){var option=options[i];if(option.selected){value=jQuery.browser.msie&&!option.attributes.value.specified?option.text:option.value;if(one)return value;values.push(value);}}return values;}else
return(this[0].value||"").replace(/\r/g,"");}return undefined;}if(value.constructor==Number)value+='';return this.each(function(){if(this.nodeType!=1)return;if(value.constructor==Array&&/radio|checkbox/.test(this.type))this.checked=(jQuery.inArray(this.value,value)>=0||jQuery.inArray(this.name,value)>=0);else if(jQuery.nodeName(this,"select")){var values=jQuery.makeArray(value);jQuery("option",this).each(function(){this.selected=(jQuery.inArray(this.value,values)>=0||jQuery.inArray(this.text,values)>=0);});if(!values.length)this.selectedIndex=-1;}else
this.value=value;});},html:function(value){return value==undefined?(this[0]?this[0].innerHTML:null):this.empty().append(value);},replaceWith:function(value){return this.after(value).remove();},eq:function(i){return this.slice(i,i+1);},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments));},map:function(callback){return this.pushStack(jQuery.map(this,function(elem,i){return callback.call(elem,i,elem);}));},andSelf:function(){return this.add(this.prevObject);},data:function(key,value){var parts=key.split(".");parts[1]=parts[1]?"."+parts[1]:"";if(value===undefined){var data=this.triggerHandler("getData"+parts[1]+"!",[parts[0]]);if(data===undefined&&this.length)data=jQuery.data(this[0],key);return data===undefined&&parts[1]?this.data(parts[0]):data;}else
return this.trigger("setData"+parts[1]+"!",[parts[0],value]).each(function(){jQuery.data(this,key,value);});},removeData:function(key){return this.each(function(){jQuery.removeData(this,key);});},domManip:function(args,table,reverse,callback){var clone=this.length>1,elems;return this.each(function(){if(!elems){elems=jQuery.clean(args,this.ownerDocument);if(reverse)elems.reverse();}var obj=this;if(table&&jQuery.nodeName(this,"table")&&jQuery.nodeName(elems[0],"tr"))obj=this.getElementsByTagName("tbody")[0]||this.appendChild(this.ownerDocument.createElement("tbody"));var scripts=jQuery([]);jQuery.each(elems,function(){var elem=clone?jQuery(this).clone(true)[0]:this;if(jQuery.nodeName(elem,"script"))scripts=scripts.add(elem);else{if(elem.nodeType==1)scripts=scripts.add(jQuery("script",elem).remove());callback.call(obj,elem);}});scripts.each(evalScript);});}};jQuery.fn.init.prototype=jQuery.fn;function evalScript(i,elem){if(elem.src)jQuery.ajax({url:elem.src,async:false,dataType:"script"});else
jQuery.globalEval(elem.text||elem.textContent||elem.innerHTML||"");if(elem.parentNode)elem.parentNode.removeChild(elem);}function now(){return+new Date;}jQuery.extend=jQuery.fn.extend=function(){var target=arguments[0]||{},i=1,length=arguments.length,deep=false,options;if(target.constructor==Boolean){deep=target;target=arguments[1]||{};i=2;}if(typeof target!="object"&&typeof target!="function")target={};if(length==i){target=this;--i;}for(;i<length;i++)if((options=arguments[i])!=null)for(var name in options){var src=target[name],copy=options[name];if(target===copy)continue;if(deep&&copy&&typeof copy=="object"&&!copy.nodeType)target[name]=jQuery.extend(deep,src||(copy.length!=null?[]:{}),copy);else if(copy!==undefined)target[name]=copy;}return target;};var expando="jQuery"+now(),uuid=0,windowData={},exclude=/z-?index|font-?weight|opacity|zoom|line-?height/i,defaultView=document.defaultView||{};jQuery.extend({noConflict:function(deep){window.$=_$;if(deep)window.jQuery=_jQuery;return jQuery;},isFunction:function(fn){return!!fn&&typeof fn!="string"&&!fn.nodeName&&fn.constructor!=Array&&/^[\s[]?function/.test(fn+"");},isXMLDoc:function(elem){return elem.documentElement&&!elem.body||elem.tagName&&elem.ownerDocument&&!elem.ownerDocument.body;},globalEval:function(data){data=jQuery.trim(data);if(data){var head=document.getElementsByTagName("head")[0]||document.documentElement,script=document.createElement("script");script.type="text/javascript";if(jQuery.browser.msie)script.text=data;else
script.appendChild(document.createTextNode(data));head.insertBefore(script,head.firstChild);head.removeChild(script);}},nodeName:function(elem,name){return elem.nodeName&&elem.nodeName.toUpperCase()==name.toUpperCase();},cache:{},data:function(elem,name,data){elem=elem==window?windowData:elem;var id=elem[expando];if(!id)id=elem[expando]=++uuid;if(name&&!jQuery.cache[id])jQuery.cache[id]={};if(data!==undefined)jQuery.cache[id][name]=data;return name?jQuery.cache[id][name]:id;},removeData:function(elem,name){elem=elem==window?windowData:elem;var id=elem[expando];if(name){if(jQuery.cache[id]){delete jQuery.cache[id][name];name="";for(name in jQuery.cache[id])break;if(!name)jQuery.removeData(elem);}}else{try{delete elem[expando];}catch(e){if(elem.removeAttribute)elem.removeAttribute(expando);}delete jQuery.cache[id];}},each:function(object,callback,args){var name,i=0,length=object.length;if(args){if(length==undefined){for(name in object)if(callback.apply(object[name],args)===false)break;}else
for(;i<length;)if(callback.apply(object[i++],args)===false)break;}else{if(length==undefined){for(name in object)if(callback.call(object[name],name,object[name])===false)break;}else
for(var value=object[0];i<length&&callback.call(value,i,value)!==false;value=object[++i]){}}return object;},prop:function(elem,value,type,i,name){if(jQuery.isFunction(value))value=value.call(elem,i);return value&&value.constructor==Number&&type=="curCSS"&&!exclude.test(name)?value+"px":value;},className:{add:function(elem,classNames){jQuery.each((classNames||"").split(/\s+/),function(i,className){if(elem.nodeType==1&&!jQuery.className.has(elem.className,className))elem.className+=(elem.className?" ":"")+className;});},remove:function(elem,classNames){if(elem.nodeType==1)elem.className=classNames!=undefined?jQuery.grep(elem.className.split(/\s+/),function(className){return!jQuery.className.has(classNames,className);}).join(" "):"";},has:function(elem,className){return jQuery.inArray(className,(elem.className||elem).toString().split(/\s+/))>-1;}},swap:function(elem,options,callback){var old={};for(var name in options){old[name]=elem.style[name];elem.style[name]=options[name];}callback.call(elem);for(var name in options)elem.style[name]=old[name];},css:function(elem,name,force){if(name=="width"||name=="height"){var val,props={position:"absolute",visibility:"hidden",display:"block"},which=name=="width"?["Left","Right"]:["Top","Bottom"];function getWH(){val=name=="width"?elem.offsetWidth:elem.offsetHeight;var padding=0,border=0;jQuery.each(which,function(){padding+=parseFloat(jQuery.curCSS(elem,"padding"+this,true))||0;border+=parseFloat(jQuery.curCSS(elem,"border"+this+"Width",true))||0;});val-=Math.round(padding+border);}if(jQuery(elem).is(":visible"))getWH();else
jQuery.swap(elem,props,getWH);return Math.max(0,val);}return jQuery.curCSS(elem,name,force);},curCSS:function(elem,name,force){var ret,style=elem.style;function color(elem){if(!jQuery.browser.safari)return false;var ret=defaultView.getComputedStyle(elem,null);return!ret||ret.getPropertyValue("color")=="";}if(name=="opacity"&&jQuery.browser.msie){ret=jQuery.attr(style,"opacity");return ret==""?"1":ret;}if(jQuery.browser.opera&&name=="display"){var save=style.outline;style.outline="0 solid black";style.outline=save;}if(name.match(/float/i))name=styleFloat;if(!force&&style&&style[name])ret=style[name];else if(defaultView.getComputedStyle){if(name.match(/float/i))name="float";name=name.replace(/([A-Z])/g,"-$1").toLowerCase();var computedStyle=defaultView.getComputedStyle(elem,null);if(computedStyle&&!color(elem))ret=computedStyle.getPropertyValue(name);else{var swap=[],stack=[],a=elem,i=0;for(;a&&color(a);a=a.parentNode)stack.unshift(a);for(;i<stack.length;i++)if(color(stack[i])){swap[i]=stack[i].style.display;stack[i].style.display="block";}ret=name=="display"&&swap[stack.length-1]!=null?"none":(computedStyle&&computedStyle.getPropertyValue(name))||"";for(i=0;i<swap.length;i++)if(swap[i]!=null)stack[i].style.display=swap[i];}if(name=="opacity"&&ret=="")ret="1";}else if(elem.currentStyle){var camelCase=name.replace(/\-(\w)/g,function(all,letter){return letter.toUpperCase();});ret=elem.currentStyle[name]||elem.currentStyle[camelCase];if(!/^\d+(px)?$/i.test(ret)&&/^\d/.test(ret)){var left=style.left,rsLeft=elem.runtimeStyle.left;elem.runtimeStyle.left=elem.currentStyle.left;style.left=ret||0;ret=style.pixelLeft+"px";style.left=left;elem.runtimeStyle.left=rsLeft;}}return ret;},clean:function(elems,context){var ret=[];context=context||document;if(typeof context.createElement=='undefined')context=context.ownerDocument||context[0]&&context[0].ownerDocument||document;jQuery.each(elems,function(i,elem){if(!elem)return;if(elem.constructor==Number)elem+='';if(typeof elem=="string"){elem=elem.replace(/(<(\w+)[^>]*?)\/>/g,function(all,front,tag){return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?all:front+"></"+tag+">";});var tags=jQuery.trim(elem).toLowerCase(),div=context.createElement("div");var wrap=!tags.indexOf("<opt")&&[1,"<select multiple='multiple'>","</select>"]||!tags.indexOf("<leg")&&[1,"<fieldset>","</fieldset>"]||tags.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"<table>","</table>"]||!tags.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!tags.indexOf("<td")||!tags.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||!tags.indexOf("<col")&&[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"]||jQuery.browser.msie&&[1,"div<div>","</div>"]||[0,"",""];div.innerHTML=wrap[1]+elem+wrap[2];while(wrap[0]--)div=div.lastChild;if(jQuery.browser.msie){var tbody=!tags.indexOf("<table")&&tags.indexOf("<tbody")<0?div.firstChild&&div.firstChild.childNodes:wrap[1]=="<table>"&&tags.indexOf("<tbody")<0?div.childNodes:[];for(var j=tbody.length-1;j>=0;--j)if(jQuery.nodeName(tbody[j],"tbody")&&!tbody[j].childNodes.length)tbody[j].parentNode.removeChild(tbody[j]);if(/^\s/.test(elem))div.insertBefore(context.createTextNode(elem.match(/^\s*/)[0]),div.firstChild);}elem=jQuery.makeArray(div.childNodes);}if(elem.length===0&&(!jQuery.nodeName(elem,"form")&&!jQuery.nodeName(elem,"select")))return;if(elem[0]==undefined||jQuery.nodeName(elem,"form")||elem.options)ret.push(elem);else
ret=jQuery.merge(ret,elem);});return ret;},attr:function(elem,name,value){if(!elem||elem.nodeType==3||elem.nodeType==8)return undefined;var notxml=!jQuery.isXMLDoc(elem),set=value!==undefined,msie=jQuery.browser.msie;name=notxml&&jQuery.props[name]||name;if(elem.tagName){var special=/href|src|style/.test(name);if(name=="selected"&&jQuery.browser.safari)elem.parentNode.selectedIndex;if(name in elem&&notxml&&!special){if(set){if(name=="type"&&jQuery.nodeName(elem,"input")&&elem.parentNode)throw"type property can't be changed";elem[name]=value;}if(jQuery.nodeName(elem,"form")&&elem.getAttributeNode(name))return elem.getAttributeNode(name).nodeValue;return elem[name];}if(msie&&notxml&&name=="style")return jQuery.attr(elem.style,"cssText",value);if(set)elem.setAttribute(name,""+value);var attr=msie&&notxml&&special?elem.getAttribute(name,2):elem.getAttribute(name);return attr===null?undefined:attr;}if(msie&&name=="opacity"){if(set){elem.zoom=1;elem.filter=(elem.filter||"").replace(/alpha\([^)]*\)/,"")+(parseInt(value)+''=="NaN"?"":"alpha(opacity="+value*100+")");}return elem.filter&&elem.filter.indexOf("opacity=")>=0?(parseFloat(elem.filter.match(/opacity=([^)]*)/)[1])/100)+'':"";}name=name.replace(/-([a-z])/ig,function(all,letter){return letter.toUpperCase();});if(set)elem[name]=value;return elem[name];},trim:function(text){return(text||"").replace(/^\s+|\s+$/g,"");},makeArray:function(array){var ret=[];if(array!=null){var i=array.length;if(i==null||array.split||array.setInterval||array.call)ret[0]=array;else
while(i)ret[--i]=array[i];}return ret;},inArray:function(elem,array){for(var i=0,length=array.length;i<length;i++)if(array[i]===elem)return i;return-1;},merge:function(first,second){var i=0,elem,pos=first.length;if(jQuery.browser.msie){while(elem=second[i++])if(elem.nodeType!=8)first[pos++]=elem;}else
while(elem=second[i++])first[pos++]=elem;return first;},unique:function(array){var ret=[],done={};try{for(var i=0,length=array.length;i<length;i++){var id=jQuery.data(array[i]);if(!done[id]){done[id]=true;ret.push(array[i]);}}}catch(e){ret=array;}return ret;},grep:function(elems,callback,inv){var ret=[];for(var i=0,length=elems.length;i<length;i++)if(!inv!=!callback(elems[i],i))ret.push(elems[i]);return ret;},map:function(elems,callback){var ret=[];for(var i=0,length=elems.length;i<length;i++){var value=callback(elems[i],i);if(value!=null)ret[ret.length]=value;}return ret.concat.apply([],ret);}});var userAgent=navigator.userAgent.toLowerCase();jQuery.browser={version:(userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[])[1],safari:/webkit/.test(userAgent),opera:/opera/.test(userAgent),msie:/msie/.test(userAgent)&&!/opera/.test(userAgent),mozilla:/mozilla/.test(userAgent)&&!/(compatible|webkit)/.test(userAgent)};var styleFloat=jQuery.browser.msie?"styleFloat":"cssFloat";jQuery.extend({boxModel:!jQuery.browser.msie||document.compatMode=="CSS1Compat",props:{"for":"htmlFor","class":"className","float":styleFloat,cssFloat:styleFloat,styleFloat:styleFloat,readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing"}});jQuery.each({parent:function(elem){return elem.parentNode;},parents:function(elem){return jQuery.dir(elem,"parentNode");},next:function(elem){return jQuery.nth(elem,2,"nextSibling");},prev:function(elem){return jQuery.nth(elem,2,"previousSibling");},nextAll:function(elem){return jQuery.dir(elem,"nextSibling");},prevAll:function(elem){return jQuery.dir(elem,"previousSibling");},siblings:function(elem){return jQuery.sibling(elem.parentNode.firstChild,elem);},children:function(elem){return jQuery.sibling(elem.firstChild);},contents:function(elem){return jQuery.nodeName(elem,"iframe")?elem.contentDocument||elem.contentWindow.document:jQuery.makeArray(elem.childNodes);}},function(name,fn){jQuery.fn[name]=function(selector){var ret=jQuery.map(this,fn);if(selector&&typeof selector=="string")ret=jQuery.multiFilter(selector,ret);return this.pushStack(jQuery.unique(ret));};});jQuery.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(name,original){jQuery.fn[name]=function(){var args=arguments;return this.each(function(){for(var i=0,length=args.length;i<length;i++)jQuery(args[i])[original](this);});};});jQuery.each({removeAttr:function(name){jQuery.attr(this,name,"");if(this.nodeType==1)this.removeAttribute(name);},addClass:function(classNames){jQuery.className.add(this,classNames);},removeClass:function(classNames){jQuery.className.remove(this,classNames);},toggleClass:function(classNames){jQuery.className[jQuery.className.has(this,classNames)?"remove":"add"](this,classNames);},remove:function(selector){if(!selector||jQuery.filter(selector,[this]).r.length){jQuery("*",this).add(this).each(function(){jQuery.event.remove(this);jQuery.removeData(this);});if(this.parentNode)this.parentNode.removeChild(this);}},empty:function(){jQuery(">*",this).remove();while(this.firstChild)this.removeChild(this.firstChild);}},function(name,fn){jQuery.fn[name]=function(){return this.each(fn,arguments);};});jQuery.each(["Height","Width"],function(i,name){var type=name.toLowerCase();jQuery.fn[type]=function(size){return this[0]==window?jQuery.browser.opera&&document.body["client"+name]||jQuery.browser.safari&&window["inner"+name]||document.compatMode=="CSS1Compat"&&document.documentElement["client"+name]||document.body["client"+name]:this[0]==document?Math.max(Math.max(document.body["scroll"+name],document.documentElement["scroll"+name]),Math.max(document.body["offset"+name],document.documentElement["offset"+name])):size==undefined?(this.length?jQuery.css(this[0],type):null):this.css(type,size.constructor==String?size:size+"px");};});function num(elem,prop){return elem[0]&&parseInt(jQuery.curCSS(elem[0],prop,true),10)||0;}var chars=jQuery.browser.safari&&parseInt(jQuery.browser.version)<417?"(?:[\\w*_-]|\\\\.)":"(?:[\\w\u0128-\uFFFF*_-]|\\\\.)",quickChild=new RegExp("^>\\s*("+chars+"+)"),quickID=new RegExp("^("+chars+"+)(#)("+chars+"+)"),quickClass=new RegExp("^([#.]?)("+chars+"*)");jQuery.extend({expr:{"":function(a,i,m){return m[2]=="*"||jQuery.nodeName(a,m[2]);},"#":function(a,i,m){return a.getAttribute("id")==m[2];},":":{lt:function(a,i,m){return i<m[3]-0;},gt:function(a,i,m){return i>m[3]-0;},nth:function(a,i,m){return m[3]-0==i;},eq:function(a,i,m){return m[3]-0==i;},first:function(a,i){return i==0;},last:function(a,i,m,r){return i==r.length-1;},even:function(a,i){return i%2==0;},odd:function(a,i){return i%2;},"first-child":function(a){return a.parentNode.getElementsByTagName("*")[0]==a;},"last-child":function(a){return jQuery.nth(a.parentNode.lastChild,1,"previousSibling")==a;},"only-child":function(a){return!jQuery.nth(a.parentNode.lastChild,2,"previousSibling");},parent:function(a){return a.firstChild;},empty:function(a){return!a.firstChild;},contains:function(a,i,m){return(a.textContent||a.innerText||jQuery(a).text()||"").indexOf(m[3])>=0;},visible:function(a){return"hidden"!=a.type&&jQuery.css(a,"display")!="none"&&jQuery.css(a,"visibility")!="hidden";},hidden:function(a){return"hidden"==a.type||jQuery.css(a,"display")=="none"||jQuery.css(a,"visibility")=="hidden";},enabled:function(a){return!a.disabled;},disabled:function(a){return a.disabled;},checked:function(a){return a.checked;},selected:function(a){return a.selected||jQuery.attr(a,"selected");},text:function(a){return"text"==a.type;},radio:function(a){return"radio"==a.type;},checkbox:function(a){return"checkbox"==a.type;},file:function(a){return"file"==a.type;},password:function(a){return"password"==a.type;},submit:function(a){return"submit"==a.type;},image:function(a){return"image"==a.type;},reset:function(a){return"reset"==a.type;},button:function(a){return"button"==a.type||jQuery.nodeName(a,"button");},input:function(a){return/input|select|textarea|button/i.test(a.nodeName);},has:function(a,i,m){return jQuery.find(m[3],a).length;},header:function(a){return/h\d/i.test(a.nodeName);},animated:function(a){return jQuery.grep(jQuery.timers,function(fn){return a==fn.elem;}).length;}}},parse:[/^(\[) *@?([\w-]+) *([!*$^~=]*) *('?"?)(.*?)\4 *\]/,/^(:)([\w-]+)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/,new RegExp("^([:.#]*)("+chars+"+)")],multiFilter:function(expr,elems,not){var old,cur=[];while(expr&&expr!=old){old=expr;var f=jQuery.filter(expr,elems,not);expr=f.t.replace(/^\s*,\s*/,"");cur=not?elems=f.r:jQuery.merge(cur,f.r);}return cur;},find:function(t,context){if(typeof t!="string")return[t];if(context&&context.nodeType!=1&&context.nodeType!=9)return[];context=context||document;var ret=[context],done=[],last,nodeName;while(t&&last!=t){var r=[];last=t;t=jQuery.trim(t);var foundToken=false,re=quickChild,m=re.exec(t);if(m){nodeName=m[1].toUpperCase();for(var i=0;ret[i];i++)for(var c=ret[i].firstChild;c;c=c.nextSibling)if(c.nodeType==1&&(nodeName=="*"||c.nodeName.toUpperCase()==nodeName))r.push(c);ret=r;t=t.replace(re,"");if(t.indexOf(" ")==0)continue;foundToken=true;}else{re=/^([>+~])\s*(\w*)/i;if((m=re.exec(t))!=null){r=[];var merge={};nodeName=m[2].toUpperCase();m=m[1];for(var j=0,rl=ret.length;j<rl;j++){var n=m=="~"||m=="+"?ret[j].nextSibling:ret[j].firstChild;for(;n;n=n.nextSibling)if(n.nodeType==1){var id=jQuery.data(n);if(m=="~"&&merge[id])break;if(!nodeName||n.nodeName.toUpperCase()==nodeName){if(m=="~")merge[id]=true;r.push(n);}if(m=="+")break;}}ret=r;t=jQuery.trim(t.replace(re,""));foundToken=true;}}if(t&&!foundToken){if(!t.indexOf(",")){if(context==ret[0])ret.shift();done=jQuery.merge(done,ret);r=ret=[context];t=" "+t.substr(1,t.length);}else{var re2=quickID;var m=re2.exec(t);if(m){m=[0,m[2],m[3],m[1]];}else{re2=quickClass;m=re2.exec(t);}m[2]=m[2].replace(/\\/g,"");var elem=ret[ret.length-1];if(m[1]=="#"&&elem&&elem.getElementById&&!jQuery.isXMLDoc(elem)){var oid=elem.getElementById(m[2]);if((jQuery.browser.msie||jQuery.browser.opera)&&oid&&typeof oid.id=="string"&&oid.id!=m[2])oid=jQuery('[@id="'+m[2]+'"]',elem)[0];ret=r=oid&&(!m[3]||jQuery.nodeName(oid,m[3]))?[oid]:[];}else{for(var i=0;ret[i];i++){var tag=m[1]=="#"&&m[3]?m[3]:m[1]!=""||m[0]==""?"*":m[2];if(tag=="*"&&ret[i].nodeName.toLowerCase()=="object")tag="param";r=jQuery.merge(r,ret[i].getElementsByTagName(tag));}if(m[1]==".")r=jQuery.classFilter(r,m[2]);if(m[1]=="#"){var tmp=[];for(var i=0;r[i];i++)if(r[i].getAttribute("id")==m[2]){tmp=[r[i]];break;}r=tmp;}ret=r;}t=t.replace(re2,"");}}if(t){var val=jQuery.filter(t,r);ret=r=val.r;t=jQuery.trim(val.t);}}if(t)ret=[];if(ret&&context==ret[0])ret.shift();done=jQuery.merge(done,ret);return done;},classFilter:function(r,m,not){m=" "+m+" ";var tmp=[];for(var i=0;r[i];i++){var pass=(" "+r[i].className+" ").indexOf(m)>=0;if(!not&&pass||not&&!pass)tmp.push(r[i]);}return tmp;},filter:function(t,r,not){var last;while(t&&t!=last){last=t;var p=jQuery.parse,m;for(var i=0;p[i];i++){m=p[i].exec(t);if(m){t=t.substring(m[0].length);m[2]=m[2].replace(/\\/g,"");break;}}if(!m)break;if(m[1]==":"&&m[2]=="not")r=isSimple.test(m[3])?jQuery.filter(m[3],r,true).r:jQuery(r).not(m[3]);else if(m[1]==".")r=jQuery.classFilter(r,m[2],not);else if(m[1]=="["){var tmp=[],type=m[3];for(var i=0,rl=r.length;i<rl;i++){var a=r[i],z=a[jQuery.props[m[2]]||m[2]];if(z==null||/href|src|selected/.test(m[2]))z=jQuery.attr(a,m[2])||'';if((type==""&&!!z||type=="="&&z==m[5]||type=="!="&&z!=m[5]||type=="^="&&z&&!z.indexOf(m[5])||type=="$="&&z.substr(z.length-m[5].length)==m[5]||(type=="*="||type=="~=")&&z.indexOf(m[5])>=0)^not)tmp.push(a);}r=tmp;}else if(m[1]==":"&&m[2]=="nth-child"){var merge={},tmp=[],test=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(m[3]=="even"&&"2n"||m[3]=="odd"&&"2n+1"||!/\D/.test(m[3])&&"0n+"+m[3]||m[3]),first=(test[1]+(test[2]||1))-0,last=test[3]-0;for(var i=0,rl=r.length;i<rl;i++){var node=r[i],parentNode=node.parentNode,id=jQuery.data(parentNode);if(!merge[id]){var c=1;for(var n=parentNode.firstChild;n;n=n.nextSibling)if(n.nodeType==1)n.nodeIndex=c++;merge[id]=true;}var add=false;if(first==0){if(node.nodeIndex==last)add=true;}else if((node.nodeIndex-last)%first==0&&(node.nodeIndex-last)/first>=0)add=true;if(add^not)tmp.push(node);}r=tmp;}else{var fn=jQuery.expr[m[1]];if(typeof fn=="object")fn=fn[m[2]];if(typeof fn=="string")fn=eval("false||function(a,i){return "+fn+";}");r=jQuery.grep(r,function(elem,i){return fn(elem,i,m,r);},not);}}return{r:r,t:t};},dir:function(elem,dir){var matched=[],cur=elem[dir];while(cur&&cur!=document){if(cur.nodeType==1)matched.push(cur);cur=cur[dir];}return matched;},nth:function(cur,result,dir,elem){result=result||1;var num=0;for(;cur;cur=cur[dir])if(cur.nodeType==1&&++num==result)break;return cur;},sibling:function(n,elem){var r=[];for(;n;n=n.nextSibling){if(n.nodeType==1&&n!=elem)r.push(n);}return r;}});jQuery.event={add:function(elem,types,handler,data){if(elem.nodeType==3||elem.nodeType==8)return;if(jQuery.browser.msie&&elem.setInterval)elem=window;if(!handler.guid)handler.guid=this.guid++;if(data!=undefined){var fn=handler;handler=this.proxy(fn,function(){return fn.apply(this,arguments);});handler.data=data;}var events=jQuery.data(elem,"events")||jQuery.data(elem,"events",{}),handle=jQuery.data(elem,"handle")||jQuery.data(elem,"handle",function(){if(typeof jQuery!="undefined"&&!jQuery.event.triggered)return jQuery.event.handle.apply(arguments.callee.elem,arguments);});handle.elem=elem;jQuery.each(types.split(/\s+/),function(index,type){var parts=type.split(".");type=parts[0];handler.type=parts[1];var handlers=events[type];if(!handlers){handlers=events[type]={};if(!jQuery.event.special[type]||jQuery.event.special[type].setup.call(elem)===false){if(elem.addEventListener)elem.addEventListener(type,handle,false);else if(elem.attachEvent)elem.attachEvent("on"+type,handle);}}handlers[handler.guid]=handler;jQuery.event.global[type]=true;});elem=null;},guid:1,global:{},remove:function(elem,types,handler){if(elem.nodeType==3||elem.nodeType==8)return;var events=jQuery.data(elem,"events"),ret,index;if(events){if(types==undefined||(typeof types=="string"&&types.charAt(0)=="."))for(var type in events)this.remove(elem,type+(types||""));else{if(types.type){handler=types.handler;types=types.type;}jQuery.each(types.split(/\s+/),function(index,type){var parts=type.split(".");type=parts[0];if(events[type]){if(handler)delete events[type][handler.guid];else
for(handler in events[type])if(!parts[1]||events[type][handler].type==parts[1])delete events[type][handler];for(ret in events[type])break;if(!ret){if(!jQuery.event.special[type]||jQuery.event.special[type].teardown.call(elem)===false){if(elem.removeEventListener)elem.removeEventListener(type,jQuery.data(elem,"handle"),false);else if(elem.detachEvent)elem.detachEvent("on"+type,jQuery.data(elem,"handle"));}ret=null;delete events[type];}}});}for(ret in events)break;if(!ret){var handle=jQuery.data(elem,"handle");if(handle)handle.elem=null;jQuery.removeData(elem,"events");jQuery.removeData(elem,"handle");}}},trigger:function(type,data,elem,donative,extra){data=jQuery.makeArray(data);if(type.indexOf("!")>=0){type=type.slice(0,-1);var exclusive=true;}if(!elem){if(this.global[type])jQuery("*").add([window,document]).trigger(type,data);}else{if(elem.nodeType==3||elem.nodeType==8)return undefined;var val,ret,fn=jQuery.isFunction(elem[type]||null),event=!data[0]||!data[0].preventDefault;if(event){data.unshift({type:type,target:elem,preventDefault:function(){},stopPropagation:function(){},timeStamp:now()});data[0][expando]=true;}data[0].type=type;if(exclusive)data[0].exclusive=true;var handle=jQuery.data(elem,"handle");if(handle)val=handle.apply(elem,data);if((!fn||(jQuery.nodeName(elem,'a')&&type=="click"))&&elem["on"+type]&&elem["on"+type].apply(elem,data)===false)val=false;if(event)data.shift();if(extra&&jQuery.isFunction(extra)){ret=extra.apply(elem,val==null?data:data.concat(val));if(ret!==undefined)val=ret;}if(fn&&donative!==false&&val!==false&&!(jQuery.nodeName(elem,'a')&&type=="click")){this.triggered=true;try{elem[type]();}catch(e){}}this.triggered=false;}return val;},handle:function(event){var val,ret,namespace,all,handlers;event=arguments[0]=jQuery.event.fix(event||window.event);namespace=event.type.split(".");event.type=namespace[0];namespace=namespace[1];all=!namespace&&!event.exclusive;handlers=(jQuery.data(this,"events")||{})[event.type];for(var j in handlers){var handler=handlers[j];if(all||handler.type==namespace){event.handler=handler;event.data=handler.data;ret=handler.apply(this,arguments);if(val!==false)val=ret;if(ret===false){event.preventDefault();event.stopPropagation();}}}return val;},fix:function(event){if(event[expando]==true)return event;var originalEvent=event;event={originalEvent:originalEvent};var props="altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target timeStamp toElement type view wheelDelta which".split(" ");for(var i=props.length;i;i--)event[props[i]]=originalEvent[props[i]];event[expando]=true;event.preventDefault=function(){if(originalEvent.preventDefault)originalEvent.preventDefault();originalEvent.returnValue=false;};event.stopPropagation=function(){if(originalEvent.stopPropagation)originalEvent.stopPropagation();originalEvent.cancelBubble=true;};event.timeStamp=event.timeStamp||now();if(!event.target)event.target=event.srcElement||document;if(event.target.nodeType==3)event.target=event.target.parentNode;if(!event.relatedTarget&&event.fromElement)event.relatedTarget=event.fromElement==event.target?event.toElement:event.fromElement;if(event.pageX==null&&event.clientX!=null){var doc=document.documentElement,body=document.body;event.pageX=event.clientX+(doc&&doc.scrollLeft||body&&body.scrollLeft||0)-(doc.clientLeft||0);event.pageY=event.clientY+(doc&&doc.scrollTop||body&&body.scrollTop||0)-(doc.clientTop||0);}if(!event.which&&((event.charCode||event.charCode===0)?event.charCode:event.keyCode))event.which=event.charCode||event.keyCode;if(!event.metaKey&&event.ctrlKey)event.metaKey=event.ctrlKey;if(!event.which&&event.button)event.which=(event.button&1?1:(event.button&2?3:(event.button&4?2:0)));return event;},proxy:function(fn,proxy){proxy.guid=fn.guid=fn.guid||proxy.guid||this.guid++;return proxy;},special:{ready:{setup:function(){bindReady();return;},teardown:function(){return;}},mouseenter:{setup:function(){if(jQuery.browser.msie)return false;jQuery(this).bind("mouseover",jQuery.event.special.mouseenter.handler);return true;},teardown:function(){if(jQuery.browser.msie)return false;jQuery(this).unbind("mouseover",jQuery.event.special.mouseenter.handler);return true;},handler:function(event){if(withinElement(event,this))return true;event.type="mouseenter";return jQuery.event.handle.apply(this,arguments);}},mouseleave:{setup:function(){if(jQuery.browser.msie)return false;jQuery(this).bind("mouseout",jQuery.event.special.mouseleave.handler);return true;},teardown:function(){if(jQuery.browser.msie)return false;jQuery(this).unbind("mouseout",jQuery.event.special.mouseleave.handler);return true;},handler:function(event){if(withinElement(event,this))return true;event.type="mouseleave";return jQuery.event.handle.apply(this,arguments);}}}};jQuery.fn.extend({bind:function(type,data,fn){return type=="unload"?this.one(type,data,fn):this.each(function(){jQuery.event.add(this,type,fn||data,fn&&data);});},one:function(type,data,fn){var one=jQuery.event.proxy(fn||data,function(event){jQuery(this).unbind(event,one);return(fn||data).apply(this,arguments);});return this.each(function(){jQuery.event.add(this,type,one,fn&&data);});},unbind:function(type,fn){return this.each(function(){jQuery.event.remove(this,type,fn);});},trigger:function(type,data,fn){return this.each(function(){jQuery.event.trigger(type,data,this,true,fn);});},triggerHandler:function(type,data,fn){return this[0]&&jQuery.event.trigger(type,data,this[0],false,fn);},toggle:function(fn){var args=arguments,i=1;while(i<args.length)jQuery.event.proxy(fn,args[i++]);return this.click(jQuery.event.proxy(fn,function(event){this.lastToggle=(this.lastToggle||0)%i;event.preventDefault();return args[this.lastToggle++].apply(this,arguments)||false;}));},hover:function(fnOver,fnOut){return this.bind('mouseenter',fnOver).bind('mouseleave',fnOut);},ready:function(fn){bindReady();if(jQuery.isReady)fn.call(document,jQuery);else
jQuery.readyList.push(function(){return fn.call(this,jQuery);});return this;}});jQuery.extend({isReady:false,readyList:[],ready:function(){if(!jQuery.isReady){jQuery.isReady=true;if(jQuery.readyList){jQuery.each(jQuery.readyList,function(){this.call(document);});jQuery.readyList=null;}jQuery(document).triggerHandler("ready");}}});var readyBound=false;function bindReady(){if(readyBound)return;readyBound=true;if(document.addEventListener&&!jQuery.browser.opera)document.addEventListener("DOMContentLoaded",jQuery.ready,false);if(jQuery.browser.msie&&window==top)(function(){if(jQuery.isReady)return;try{document.documentElement.doScroll("left");}catch(error){setTimeout(arguments.callee,0);return;}jQuery.ready();})();if(jQuery.browser.opera)document.addEventListener("DOMContentLoaded",function(){if(jQuery.isReady)return;for(var i=0;i<document.styleSheets.length;i++)if(document.styleSheets[i].disabled){setTimeout(arguments.callee,0);return;}jQuery.ready();},false);if(jQuery.browser.safari){var numStyles;(function(){if(jQuery.isReady)return;if(document.readyState!="loaded"&&document.readyState!="complete"){setTimeout(arguments.callee,0);return;}if(numStyles===undefined)numStyles=jQuery("style, link[rel=stylesheet]").length;if(document.styleSheets.length!=numStyles){setTimeout(arguments.callee,0);return;}jQuery.ready();})();}jQuery.event.add(window,"load",jQuery.ready);}jQuery.each(("blur,focus,load,resize,scroll,unload,click,dblclick,"+"mousedown,mouseup,mousemove,mouseover,mouseout,change,select,"+"submit,keydown,keypress,keyup,error").split(","),function(i,name){jQuery.fn[name]=function(fn){return fn?this.bind(name,fn):this.trigger(name);};});var withinElement=function(event,elem){var parent=event.relatedTarget;while(parent&&parent!=elem)try{parent=parent.parentNode;}catch(error){parent=elem;}return parent==elem;};jQuery(window).bind("unload",function(){jQuery("*").add(document).unbind();});jQuery.fn.extend({_load:jQuery.fn.load,load:function(url,params,callback){if(typeof url!='string')return this._load(url);var off=url.indexOf(" ");if(off>=0){var selector=url.slice(off,url.length);url=url.slice(0,off);}callback=callback||function(){};var type="GET";if(params)if(jQuery.isFunction(params)){callback=params;params=null;}else{params=jQuery.param(params);type="POST";}var self=this;jQuery.ajax({url:url,type:type,dataType:"html",data:params,complete:function(res,status){if(status=="success"||status=="notmodified")self.html(selector?jQuery("<div/>").append(res.responseText.replace(/<script(.|\s)*?\/script>/g,"")).find(selector):res.responseText);self.each(callback,[res.responseText,status,res]);}});return this;},serialize:function(){return jQuery.param(this.serializeArray());},serializeArray:function(){return this.map(function(){return jQuery.nodeName(this,"form")?jQuery.makeArray(this.elements):this;}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password/i.test(this.type));}).map(function(i,elem){var val=jQuery(this).val();return val==null?null:val.constructor==Array?jQuery.map(val,function(val,i){return{name:elem.name,value:val};}):{name:elem.name,value:val};}).get();}});jQuery.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(i,o){jQuery.fn[o]=function(f){return this.bind(o,f);};});var jsc=now();jQuery.extend({get:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data=null;}return jQuery.ajax({type:"GET",url:url,data:data,success:callback,dataType:type});},getScript:function(url,callback){return jQuery.get(url,null,callback,"script");},getJSON:function(url,data,callback){return jQuery.get(url,data,callback,"json");},post:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data={};}return jQuery.ajax({type:"POST",url:url,data:data,success:callback,dataType:type});},ajaxSetup:function(settings){jQuery.extend(jQuery.ajaxSettings,settings);},ajaxSettings:{url:location.href,global:true,type:"GET",timeout:0,contentType:"application/x-www-form-urlencoded",processData:true,async:true,data:null,username:null,password:null,accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(s){s=jQuery.extend(true,s,jQuery.extend(true,{},jQuery.ajaxSettings,s));var jsonp,jsre=/=\?(&|$)/g,status,data,type=s.type.toUpperCase();if(s.data&&s.processData&&typeof s.data!="string")s.data=jQuery.param(s.data);if(s.dataType=="jsonp"){if(type=="GET"){if(!s.url.match(jsre))s.url+=(s.url.match(/\?/)?"&":"?")+(s.jsonp||"callback")+"=?";}else if(!s.data||!s.data.match(jsre))s.data=(s.data?s.data+"&":"")+(s.jsonp||"callback")+"=?";s.dataType="json";}if(s.dataType=="json"&&(s.data&&s.data.match(jsre)||s.url.match(jsre))){jsonp="jsonp"+jsc++;if(s.data)s.data=(s.data+"").replace(jsre,"="+jsonp+"$1");s.url=s.url.replace(jsre,"="+jsonp+"$1");s.dataType="script";window[jsonp]=function(tmp){data=tmp;success();complete();window[jsonp]=undefined;try{delete window[jsonp];}catch(e){}if(head)head.removeChild(script);};}if(s.dataType=="script"&&s.cache==null)s.cache=false;if(s.cache===false&&type=="GET"){var ts=now();var ret=s.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+ts+"$2");s.url=ret+((ret==s.url)?(s.url.match(/\?/)?"&":"?")+"_="+ts:"");}if(s.data&&type=="GET"){s.url+=(s.url.match(/\?/)?"&":"?")+s.data;s.data=null;}if(s.global&&!jQuery.active++)jQuery.event.trigger("ajaxStart");var remote=/^(?:\w+:)?\/\/([^\/?#]+)/;if(s.dataType=="script"&&type=="GET"&&remote.test(s.url)&&remote.exec(s.url)[1]!=location.host){var head=document.getElementsByTagName("head")[0];var script=document.createElement("script");script.src=s.url;if(s.scriptCharset)script.charset=s.scriptCharset;if(!jsonp){var done=false;script.onload=script.onreadystatechange=function(){if(!done&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){done=true;success();complete();head.removeChild(script);}};}head.appendChild(script);return undefined;}var requestDone=false;var xhr=window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();if(s.username)xhr.open(type,s.url,s.async,s.username,s.password);else
xhr.open(type,s.url,s.async);try{if(s.data)xhr.setRequestHeader("Content-Type",s.contentType);if(s.ifModified)xhr.setRequestHeader("If-Modified-Since",jQuery.lastModified[s.url]||"Thu, 01 Jan 1970 00:00:00 GMT");xhr.setRequestHeader("X-Requested-With","XMLHttpRequest");xhr.setRequestHeader("Accept",s.dataType&&s.accepts[s.dataType]?s.accepts[s.dataType]+", */*":s.accepts._default);}catch(e){}if(s.beforeSend&&s.beforeSend(xhr,s)===false){s.global&&jQuery.active--;xhr.abort();return false;}if(s.global)jQuery.event.trigger("ajaxSend",[xhr,s]);var onreadystatechange=function(isTimeout){if(!requestDone&&xhr&&(xhr.readyState==4||isTimeout=="timeout")){requestDone=true;if(ival){clearInterval(ival);ival=null;}status=isTimeout=="timeout"&&"timeout"||!jQuery.httpSuccess(xhr)&&"error"||s.ifModified&&jQuery.httpNotModified(xhr,s.url)&&"notmodified"||"success";if(status=="success"){try{data=jQuery.httpData(xhr,s.dataType,s.dataFilter);}catch(e){status="parsererror";}}if(status=="success"){var modRes;try{modRes=xhr.getResponseHeader("Last-Modified");}catch(e){}if(s.ifModified&&modRes)jQuery.lastModified[s.url]=modRes;if(!jsonp)success();}else
jQuery.handleError(s,xhr,status);complete();if(s.async)xhr=null;}};if(s.async){var ival=setInterval(onreadystatechange,13);if(s.timeout>0)setTimeout(function(){if(xhr){xhr.abort();if(!requestDone)onreadystatechange("timeout");}},s.timeout);}try{xhr.send(s.data);}catch(e){jQuery.handleError(s,xhr,null,e);}if(!s.async)onreadystatechange();function success(){if(s.success)s.success(data,status);if(s.global)jQuery.event.trigger("ajaxSuccess",[xhr,s]);}function complete(){if(s.complete)s.complete(xhr,status);if(s.global)jQuery.event.trigger("ajaxComplete",[xhr,s]);if(s.global&&!--jQuery.active)jQuery.event.trigger("ajaxStop");}return xhr;},handleError:function(s,xhr,status,e){if(s.error)s.error(xhr,status,e);if(s.global)jQuery.event.trigger("ajaxError",[xhr,s,e]);},active:0,httpSuccess:function(xhr){try{return!xhr.status&&location.protocol=="file:"||(xhr.status>=200&&xhr.status<300)||xhr.status==304||xhr.status==1223||jQuery.browser.safari&&xhr.status==undefined;}catch(e){}return false;},httpNotModified:function(xhr,url){try{var xhrRes=xhr.getResponseHeader("Last-Modified");return xhr.status==304||xhrRes==jQuery.lastModified[url]||jQuery.browser.safari&&xhr.status==undefined;}catch(e){}return false;},httpData:function(xhr,type,filter){var ct=xhr.getResponseHeader("content-type"),xml=type=="xml"||!type&&ct&&ct.indexOf("xml")>=0,data=xml?xhr.responseXML:xhr.responseText;if(xml&&data.documentElement.tagName=="parsererror")throw"parsererror";if(filter)data=filter(data,type);if(type=="script")jQuery.globalEval(data);if(type=="json")data=eval("("+data+")");return data;},param:function(a){var s=[];if(a.constructor==Array||a.jquery)jQuery.each(a,function(){s.push(encodeURIComponent(this.name)+"="+encodeURIComponent(this.value));});else
for(var j in a)if(a[j]&&a[j].constructor==Array)jQuery.each(a[j],function(){s.push(encodeURIComponent(j)+"="+encodeURIComponent(this));});else
s.push(encodeURIComponent(j)+"="+encodeURIComponent(jQuery.isFunction(a[j])?a[j]():a[j]));return s.join("&").replace(/%20/g,"+");}});jQuery.fn.extend({show:function(speed,callback){return speed?this.animate({height:"show",width:"show",opacity:"show"},speed,callback):this.filter(":hidden").each(function(){this.style.display=this.oldblock||"";if(jQuery.css(this,"display")=="none"){var elem=jQuery("<"+this.tagName+" />").appendTo("body");this.style.display=elem.css("display");if(this.style.display=="none")this.style.display="block";elem.remove();}}).end();},hide:function(speed,callback){return speed?this.animate({height:"hide",width:"hide",opacity:"hide"},speed,callback):this.filter(":visible").each(function(){this.oldblock=this.oldblock||jQuery.css(this,"display");this.style.display="none";}).end();},_toggle:jQuery.fn.toggle,toggle:function(fn,fn2){return jQuery.isFunction(fn)&&jQuery.isFunction(fn2)?this._toggle.apply(this,arguments):fn?this.animate({height:"toggle",width:"toggle",opacity:"toggle"},fn,fn2):this.each(function(){jQuery(this)[jQuery(this).is(":hidden")?"show":"hide"]();});},slideDown:function(speed,callback){return this.animate({height:"show"},speed,callback);},slideUp:function(speed,callback){return this.animate({height:"hide"},speed,callback);},slideToggle:function(speed,callback){return this.animate({height:"toggle"},speed,callback);},fadeIn:function(speed,callback){return this.animate({opacity:"show"},speed,callback);},fadeOut:function(speed,callback){return this.animate({opacity:"hide"},speed,callback);},fadeTo:function(speed,to,callback){return this.animate({opacity:to},speed,callback);},animate:function(prop,speed,easing,callback){var optall=jQuery.speed(speed,easing,callback);return this[optall.queue===false?"each":"queue"](function(){if(this.nodeType!=1)return false;var opt=jQuery.extend({},optall),p,hidden=jQuery(this).is(":hidden"),self=this;for(p in prop){if(prop[p]=="hide"&&hidden||prop[p]=="show"&&!hidden)return opt.complete.call(this);if(p=="height"||p=="width"){opt.display=jQuery.css(this,"display");opt.overflow=this.style.overflow;}}if(opt.overflow!=null)this.style.overflow="hidden";opt.curAnim=jQuery.extend({},prop);jQuery.each(prop,function(name,val){var e=new jQuery.fx(self,opt,name);if(/toggle|show|hide/.test(val))e[val=="toggle"?hidden?"show":"hide":val](prop);else{var parts=val.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),start=e.cur(true)||0;if(parts){var end=parseFloat(parts[2]),unit=parts[3]||"px";if(unit!="px"){self.style[name]=(end||1)+unit;start=((end||1)/e.cur(true))*start;self.style[name]=start+unit;}if(parts[1])end=((parts[1]=="-="?-1:1)*end)+start;e.custom(start,end,unit);}else
e.custom(start,val,"");}});return true;});},queue:function(type,fn){if(jQuery.isFunction(type)||(type&&type.constructor==Array)){fn=type;type="fx";}if(!type||(typeof type=="string"&&!fn))return queue(this[0],type);return this.each(function(){if(fn.constructor==Array)queue(this,type,fn);else{queue(this,type).push(fn);if(queue(this,type).length==1)fn.call(this);}});},stop:function(clearQueue,gotoEnd){var timers=jQuery.timers;if(clearQueue)this.queue([]);this.each(function(){for(var i=timers.length-1;i>=0;i--)if(timers[i].elem==this){if(gotoEnd)timers[i](true);timers.splice(i,1);}});if(!gotoEnd)this.dequeue();return this;}});var queue=function(elem,type,array){if(elem){type=type||"fx";var q=jQuery.data(elem,type+"queue");if(!q||array)q=jQuery.data(elem,type+"queue",jQuery.makeArray(array));}return q;};jQuery.fn.dequeue=function(type){type=type||"fx";return this.each(function(){var q=queue(this,type);q.shift();if(q.length)q[0].call(this);});};jQuery.extend({speed:function(speed,easing,fn){var opt=speed&&speed.constructor==Object?speed:{complete:fn||!fn&&easing||jQuery.isFunction(speed)&&speed,duration:speed,easing:fn&&easing||easing&&easing.constructor!=Function&&easing};opt.duration=(opt.duration&&opt.duration.constructor==Number?opt.duration:jQuery.fx.speeds[opt.duration])||jQuery.fx.speeds.def;opt.old=opt.complete;opt.complete=function(){if(opt.queue!==false)jQuery(this).dequeue();if(jQuery.isFunction(opt.old))opt.old.call(this);};return opt;},easing:{linear:function(p,n,firstNum,diff){return firstNum+diff*p;},swing:function(p,n,firstNum,diff){return((-Math.cos(p*Math.PI)/2)+0.5)*diff+firstNum;}},timers:[],timerId:null,fx:function(elem,options,prop){this.options=options;this.elem=elem;this.prop=prop;if(!options.orig)options.orig={};}});jQuery.fx.prototype={update:function(){if(this.options.step)this.options.step.call(this.elem,this.now,this);(jQuery.fx.step[this.prop]||jQuery.fx.step._default)(this);if(this.prop=="height"||this.prop=="width")this.elem.style.display="block";},cur:function(force){if(this.elem[this.prop]!=null&&this.elem.style[this.prop]==null)return this.elem[this.prop];var r=parseFloat(jQuery.css(this.elem,this.prop,force));return r&&r>-10000?r:parseFloat(jQuery.curCSS(this.elem,this.prop))||0;},custom:function(from,to,unit){this.startTime=now();this.start=from;this.end=to;this.unit=unit||this.unit||"px";this.now=this.start;this.pos=this.state=0;this.update();var self=this;function t(gotoEnd){return self.step(gotoEnd);}t.elem=this.elem;jQuery.timers.push(t);if(jQuery.timerId==null){jQuery.timerId=setInterval(function(){var timers=jQuery.timers;for(var i=0;i<timers.length;i++)if(!timers[i]())timers.splice(i--,1);if(!timers.length){clearInterval(jQuery.timerId);jQuery.timerId=null;}},13);}},show:function(){this.options.orig[this.prop]=jQuery.attr(this.elem.style,this.prop);this.options.show=true;this.custom(0,this.cur());if(this.prop=="width"||this.prop=="height")this.elem.style[this.prop]="1px";jQuery(this.elem).show();},hide:function(){this.options.orig[this.prop]=jQuery.attr(this.elem.style,this.prop);this.options.hide=true;this.custom(this.cur(),0);},step:function(gotoEnd){var t=now();if(gotoEnd||t>this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var done=true;for(var i in this.options.curAnim)if(this.options.curAnim[i]!==true)done=false;if(done){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(jQuery.css(this.elem,"display")=="none")this.elem.style.display="block";}if(this.options.hide)this.elem.style.display="none";if(this.options.hide||this.options.show)for(var p in this.options.curAnim)jQuery.attr(this.elem.style,p,this.options.orig[p]);}if(done)this.options.complete.call(this.elem);return false;}else{var n=t-this.startTime;this.state=n/this.options.duration;this.pos=jQuery.easing[this.options.easing||(jQuery.easing.swing?"swing":"linear")](this.state,n,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update();}return true;}};jQuery.extend(jQuery.fx,{speeds:{slow:600,fast:200,def:400},step:{scrollLeft:function(fx){fx.elem.scrollLeft=fx.now;},scrollTop:function(fx){fx.elem.scrollTop=fx.now;},opacity:function(fx){jQuery.attr(fx.elem.style,"opacity",fx.now);},_default:function(fx){fx.elem.style[fx.prop]=fx.now+fx.unit;}}});jQuery.fn.offset=function(){var left=0,top=0,elem=this[0],results;if(elem)with(jQuery.browser){var parent=elem.parentNode,offsetChild=elem,offsetParent=elem.offsetParent,doc=elem.ownerDocument,safari2=safari&&parseInt(version)<522&&!/adobeair/i.test(userAgent),css=jQuery.curCSS,fixed=css(elem,"position")=="fixed";if(elem.getBoundingClientRect){var box=elem.getBoundingClientRect();add(box.left+Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),box.top+Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));add(-doc.documentElement.clientLeft,-doc.documentElement.clientTop);}else{add(elem.offsetLeft,elem.offsetTop);while(offsetParent){add(offsetParent.offsetLeft,offsetParent.offsetTop);if(mozilla&&!/^t(able|d|h)$/i.test(offsetParent.tagName)||safari&&!safari2)border(offsetParent);if(!fixed&&css(offsetParent,"position")=="fixed")fixed=true;offsetChild=/^body$/i.test(offsetParent.tagName)?offsetChild:offsetParent;offsetParent=offsetParent.offsetParent;}while(parent&&parent.tagName&&!/^body|html$/i.test(parent.tagName)){if(!/^inline|table.*$/i.test(css(parent,"display")))add(-parent.scrollLeft,-parent.scrollTop);if(mozilla&&css(parent,"overflow")!="visible")border(parent);parent=parent.parentNode;}if((safari2&&(fixed||css(offsetChild,"position")=="absolute"))||(mozilla&&css(offsetChild,"position")!="absolute"))add(-doc.body.offsetLeft,-doc.body.offsetTop);if(fixed)add(Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));}results={top:top,left:left};}function border(elem){add(jQuery.curCSS(elem,"borderLeftWidth",true),jQuery.curCSS(elem,"borderTopWidth",true));}function add(l,t){left+=parseInt(l,10)||0;top+=parseInt(t,10)||0;}return results;};jQuery.fn.extend({position:function(){var left=0,top=0,results;if(this[0]){var offsetParent=this.offsetParent(),offset=this.offset(),parentOffset=/^body|html$/i.test(offsetParent[0].tagName)?{top:0,left:0}:offsetParent.offset();offset.top-=num(this,'marginTop');offset.left-=num(this,'marginLeft');parentOffset.top+=num(offsetParent,'borderTopWidth');parentOffset.left+=num(offsetParent,'borderLeftWidth');results={top:offset.top-parentOffset.top,left:offset.left-parentOffset.left};}return results;},offsetParent:function(){var offsetParent=this[0].offsetParent;while(offsetParent&&(!/^body|html$/i.test(offsetParent.tagName)&&jQuery.css(offsetParent,'position')=='static'))offsetParent=offsetParent.offsetParent;return jQuery(offsetParent);}});jQuery.each(['Left','Top'],function(i,name){var method='scroll'+name;jQuery.fn[method]=function(val){if(!this[0])return;return val!=undefined?this.each(function(){this==window||this==document?window.scrollTo(!i?val:jQuery(window).scrollLeft(),i?val:jQuery(window).scrollTop()):this[method]=val;}):this[0]==window||this[0]==document?self[i?'pageYOffset':'pageXOffset']||jQuery.boxModel&&document.documentElement[method]||document.body[method]:this[0][method];};});jQuery.each(["Height","Width"],function(i,name){var tl=i?"Left":"Top",br=i?"Right":"Bottom";jQuery.fn["inner"+name]=function(){return this[name.toLowerCase()]()+num(this,"padding"+tl)+num(this,"padding"+br);};jQuery.fn["outer"+name]=function(margin){return this["inner"+name]()+num(this,"border"+tl+"Width")+num(this,"border"+br+"Width")+(margin?num(this,"margin"+tl)+num(this,"margin"+br):0);};});})();

/** File: plugins/jquery-autocomplete.js */
/************************ PLUGIN: AUTOCOMPLETE ************************************************************************/
jQuery.autocomplete = function(input, options) {
	// Create a link to self
	var me = this;

	// Create jQuery object for input element
	var $input = $(input).attr("autocomplete", "off");

	// Apply inputClass if necessary
	if (options.inputClass) $input.addClass(options.inputClass);

	// Create results
	var results = document.createElement("div");
	// Create jQuery object for results
	var $results = $(results);
	$results.hide().addClass(options.resultsClass).css("position", "absolute");
	if( options.width > 0 ) $results.css("width", options.width);

	// Add to body element
	$("body").append(results);

	input.autocompleter = me;

	var timeout = null;
	var prev = "";
	var active = -1;
	var keyb = false;
	var hasFocus = false;
	var lastKeyPressCode = null;

	// if there is a data array supplied
	if( options.data != null ){
		var sFirstChar = "", stMatchSets = {}, row = [];

		// loop through the array and create a lookup structure
		for( var i=0; i < options.data.length; i++ ){
			// if row is a string, make an array otherwise just reference the array
			row = ((typeof options.data[i] == "string") ? [options.data[i]] : options.data[i]);

			// if the length is zero, don't add to list
			if( row[0].length > 0 ){
				// get the first character
				sFirstChar = row[0].substring(0, 1).toLowerCase();
				// if no lookup array for this character exists, look it up now
				if( !stMatchSets[sFirstChar] ) stMatchSets[sFirstChar] = [];
				// if the match is a string
				stMatchSets[sFirstChar].push(row);
			}
		}
	}

	$input
	.keydown(function(e) {
        // track last key pressed
		lastKeyPressCode = e.keyCode;
		switch(e.keyCode) {
			case 38: // up
				e.preventDefault();
				moveSelect(-1);
				break;
			case 40: // down
				e.preventDefault();
				moveSelect(1);
				break;
			case 9:  // tab
			case 13: // return
				if( selectCurrent() ){
					// make sure to blur off the current field
					$input.get(0).blur();
					e.preventDefault();
				}
				break;
			default:
				active = -1;
				if (timeout) clearTimeout(timeout);
				timeout = setTimeout(function(){onChange();}, options.delay);
				break;
		}
	})
	.focus(function(){
		// track whether the field has focus, we shouldn't process any results if the field no longer has focus
		hasFocus = true;
	})
	.blur(function() {
		// track whether the field has focus
		hasFocus = false;
		hideResults();
	});

	hideResultsNow();

	function onChange() {
        // ignore if the following keys are pressed: [del] [shift] [capslock]
		if( lastKeyPressCode == 46 || (lastKeyPressCode > 8 && lastKeyPressCode < 32) ) return $results.hide();
		var v = $input.val();
		if (v == prev) return;
		prev = v;
		if (v.length >= options.minChars) {
            $input.addClass(options.loadingClass);
			requestData(v);
		} else {
			$input.removeClass(options.loadingClass);
			$results.hide();
		}
	};

 	function moveSelect(step) {

		var lis = $("li", results);
		if (!lis) return;

		active += step;

		if (active < 0) {
			active = 0;
		} else if (active >= lis.size()) {
			active = lis.size() - 1;
		}

		lis.removeClass("ac_over");

		$(lis[active]).addClass("ac_over");

		// Weird behaviour in IE
		// if (lis[active] && lis[active].scrollIntoView) {
		// 	lis[active].scrollIntoView(false);
		// }

	};

	function selectCurrent() {
		var li = $("li.ac_over", results)[0];
		if (!li) {
			var $li = $("li", results);
			if (options.selectOnly) {
				if ($li.length == 1) li = $li[0];
			} else if (options.selectFirst) {
				li = $li[0];
			}
		}
		if (li) {
			selectItem(li);
			return true;
		} else {
			return false;
		}
	};

	function selectItem(li) {
        if (!li) {
			li = document.createElement("li");
			li.extra = [];
			li.selectValue = "";
		}
		var v = $.trim(li.selectValue ? li.selectValue : li.innerHTML);
		input.lastSelected = v;
		prev = v;
		$results.html("");
		$input.val(v);
        $($input).parent().parent().parent().parent().parent().parent('form').submit();
        hideResultsNow();
		if (options.onItemSelect) setTimeout(function() { options.onItemSelect(li) }, 1);
	};

	// selects a portion of the input string
	function createSelection(start, end){
		// get a reference to the input element
		var field = $input.get(0);
		if( field.createTextRange ){
			var selRange = field.createTextRange();
			selRange.collapse(true);
			selRange.moveStart("character", start);
			selRange.moveEnd("character", end);
			selRange.select();
		} else if( field.setSelectionRange ){
			field.setSelectionRange(start, end);
		} else {
			if( field.selectionStart ){
				field.selectionStart = start;
				field.selectionEnd = end;
			}
		}
		field.focus();
	};

	// fills in the input box w/the first match (assumed to be the best match)
	function autoFill(sValue){
		// if the last user key pressed was backspace, don't autofill
		if( lastKeyPressCode != 8 ){
			// fill in the value (keep the case the user has typed)
			$input.val($input.val() + sValue.substring(prev.length));
			// select the portion of the value not typed by the user (so the next character will erase)
			createSelection(prev.length, sValue.length);
		}
	};

	function showResults() {

        var topCPMIframe = $('#top_cpm_iframe').get(0);
        hideTopFlashAd(topCPMIframe);

        // get the position of the input field right now (in case the DOM is shifted)
		var pos = findPos(input);
		// either use the specified width, or autocalculate based on form element
		var iWidth = (options.width > 0) ? options.width : $input.width();
		// reposition
        $results.prepend("<div id='ac_title'>Search suggestions</div>");
        $results.append("<div id='ac_disable'><a href='#' onclick='disableAC();'>disable</div>");

        $results.css({
			width: parseInt(iWidth) + "px",
			top: (pos.y + input.offsetHeight) + "px",
			left: pos.x + "px"
    	}).show();
    };

    function hideTopFlashAd(topCPMIframe)
    {
        if (topCPMIframe!=undefined&&topCPMIframe!=null)
        {
            if (jQuery.browser.msie)
            {
                var flashArr = topCPMIframe.document.getElementsByTagName('object');
                if (flashArr != undefined && flashArr.length > 0)
                {
                    for (i = 0; i < flashArr.length; i++)
                    {
                        var embd = flashArr[i];
//                        flashObjContainer.push(embd);
                        var rplc = embd.cloneNode(true);
                        var param = document.createElement("param");
                        param.setAttribute("name", "wmode");
                        param.setAttribute("value", "opaque");
                        rplc.appendChild(param);
                        embd.parentNode.replaceChild(rplc, embd);
                    }
                }
            }
            else
            {
                var d = topCPMIframe.document||topCPMIframe.contentDocument
                    ||(topCPMIframe.contentWindow&&topCPMIframe.contentWindow.document)||null;
                if (d!=undefined && d!=null)
                {
                    var flashArr = topCPMIframe.contentDocument.getElementsByTagName('embed');
                    if (flashArr != undefined && flashArr.length > 0)
                    {
                        for (i = 0; i < flashArr.length; i++)
                        {
                            var embd = flashArr[i];
//                            flashObjContainer.push(embd);
                            var rplc = embd.cloneNode(true);
                            rplc.setAttribute('wmode', 'opaque');
                            embd.parentNode.replaceChild(rplc, embd);
                        }
                    }
                }
            }
            try
            {
                var nestedIframes = topCPMIframe.getElementsByTagName('iframe');
                if (nestedIframes!=undefined&&nestedIframes!=null)
                {
                    for (i=0; i<nestedIframes.length;++i)
                        hideTopFlashAd(nestedIframes[i]);
                }
            }
            catch(ex)
            {
            }
        }
    }

    function hideResults() {
		if (timeout) clearTimeout(timeout);
		timeout = setTimeout(hideResultsNow, 200);
	};

	function hideResultsNow() {
		if (timeout) clearTimeout(timeout);
		$input.removeClass(options.loadingClass);
		if ($results.is(":visible")) {
			$results.hide();
		}
		if (options.mustMatch) {
			var v = $input.val();
			if (v != input.lastSelected) {
				selectItem(null);
			}
		}
	};

	function receiveData(q, data) {
		if (data) {
			$input.removeClass(options.loadingClass);
			results.innerHTML = "";

			// if the field no longer has focus or if there are no matches, do not display the drop down
			if( !hasFocus || data.length == 0 ) return hideResultsNow();

			if ($.browser.msie) {
				// we put a styled iframe behind the calendar so HTML SELECT elements don't show through
				$results.append(document.createElement('iframe'));
			}
			results.appendChild(dataToDom(data));
			// autofill in the complete box w/the first match as long as the user hasn't entered in more data
			if( options.autoFill && ($input.val().toLowerCase() == q.toLowerCase()) ) autoFill(data[0][0]);
			showResults();
		} else {
			hideResultsNow();
		}
	};

	function parseData(data) {
		if (!data) return null;
		var parsed = [];
		var rows = data.split(options.lineSeparator);
		for (var i=0; i < rows.length; i++) {
			var row = $.trim(rows[i]);
			if (row) {
				parsed[parsed.length] = row.split(options.cellSeparator);
			}
		}
		return parsed;
	};

	function dataToDom(data) {
		var ul = document.createElement("ul");
		var num = data.length;

		// limited results to a max number
		if( (options.maxItemsToShow > 0) && (options.maxItemsToShow < num) ) num = options.maxItemsToShow;

		for (var i=0; i < num; i++) {
			var row = data[i];
			if (!row) continue;
			var li = document.createElement("li");
			if (options.formatItem) {
				li.innerHTML = options.formatItem(row, i, num);
				li.selectValue = row[0];
			} else {
				li.innerHTML = row[0];
				li.selectValue = row[0];
			}
			var extra = null;
			if (row.length > 1) {
				extra = [];
				for (var j=1; j < row.length; j++) {
					extra[extra.length] = row[j];
				}
			}
			li.extra = extra;
			ul.appendChild(li);
			$(li).hover(
				function() { $("li", ul).removeClass("ac_over"); $(this).addClass("ac_over"); active = $("li", ul).indexOf($(this).get(0)); },
				function() { $(this).removeClass("ac_over"); }
			).click(function(e) { e.preventDefault(); e.stopPropagation(); selectItem(this) });
		}
		return ul;
	};

	function requestData(q) {
		if (!options.matchCase) q = q.toLowerCase();
		// if an AJAX url has been supplied, try loading the data now
		if( (typeof options.url == "string") && (options.url.length > 0) ){
			$.get(makeUrl(q), function(data) {
				data = parseData(data);
				receiveData(q, data);
			});
		// if there's been no data found, remove the loading class
		} else {
			$input.removeClass(options.loadingClass);
		}
	};

	function makeUrl(q) {
		var url = options.url + "?q=" + encodeURI(q);
		for (var i in options.extraParams) {
			url += "&" + i + "=" + encodeURI(options.extraParams[i]);
		}
		return url;
	};

	function matchSubset(s, sub) {
		if (!options.matchCase) s = s.toLowerCase();
		var i = s.indexOf(sub);
		if (i == -1) return false;
		return i == 0 || options.matchContains;
	};

	this.setExtraParams = function(p) {
		options.extraParams = p;
	};

	this.findValue = function(){
		var q = $input.val();

		if (!options.matchCase) q = q.toLowerCase();
		var data;
        if( (typeof options.url == "string") && (options.url.length > 0) ){
			$.get(makeUrl(q), function(data) {
				data = parseData(data)
				findValueCallback(q, data);
			});
		} else {
			// no matches
			findValueCallback(q, null);
		}
	}

	function findValueCallback(q, data){
		if (data) $input.removeClass(options.loadingClass);

		var num = (data) ? data.length : 0;
		var li = null;

		for (var i=0; i < num; i++) {
			var row = data[i];

			if( row[0].toLowerCase() == q.toLowerCase() ){
				li = document.createElement("li");
				if (options.formatItem) {
					li.innerHTML = options.formatItem(row, i, num);
					li.selectValue = row[0];
				} else {
					li.innerHTML = row[0];
					li.selectValue = row[0];
				}
				var extra = null;
				if( row.length > 1 ){
					extra = [];
					for (var j=1; j < row.length; j++) {
						extra[extra.length] = row[j];
					}
				}
				li.extra = extra;
			}
		}

		if( options.onFindValue ) setTimeout(function() { options.onFindValue(li) }, 1);
    }

	function findPos(obj) {
		var curleft = obj.offsetLeft || 0;
		var curtop = obj.offsetTop || 0;
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
		return {x:curleft,y:curtop};
	}

}

jQuery.fn.autocomplete = function(url, options, data) {
	// Make sure options exists
	options = options || {};
	// Set url as option
	options.url = url;
	// set some bulk local data
	options.data = ((typeof data == "object") && (data.constructor == Array)) ? data : null;

	// Set default values for required options
	options.inputClass = options.inputClass || "ac_input";
	options.resultsClass = options.resultsClass || "ac_results";
	options.lineSeparator = options.lineSeparator || "\n";
	options.cellSeparator = options.cellSeparator || "|";
	options.minChars = options.minChars || 1;
	options.delay = options.delay || 400;
	options.matchCase = options.matchCase || 0;
	options.matchSubset = options.matchSubset || 1;
	options.matchContains = options.matchContains || 0;
	options.mustMatch = options.mustMatch || 0;
	options.extraParams = options.extraParams || {};
	options.loadingClass = options.loadingClass || "ac_loading";
	options.selectFirst = options.selectFirst || false;
	options.selectOnly = options.selectOnly || false;
	options.maxItemsToShow = options.maxItemsToShow || -1;
	options.autoFill = options.autoFill || false;
	options.width = parseInt(options.width, 10) || 0;

	this.each(function() {
		var input = this;
		new jQuery.autocomplete(input, options);
	});

	// Don't break the chain
	return this;
}

jQuery.fn.autocompleteArray = function(data, options) {
	return this.autocomplete(null, options, data);
}

jQuery.fn.indexOf = function(e){
	for( var i=0; i<this.length; i++ ){
		if( this[i] == e ) return i;
	}
	return -1;
};
/************************ END PLUGIN: AUTOCOMPLETE *******************************************************************/


/** File: plugins/jquery-cookie.js */
/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.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;
                }
            }
        }
        return cookieValue;
    }
};

/** File: plugins/jquery-dimensions.js */
/* Copyright (c) 2007 Paul Bakaus (paul.bakaus@googlemail.com) and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2007-12-20 08:43:48 -0600 (Thu, 20 Dec 2007) $
 * $Rev: 4257 $
 *
 * Version: 1.2
 *
 * Requires: jQuery 1.2+
 */
(function($){$.dimensions={version:'1.2'};$.each(['Height','Width'],function(i,name){$.fn['inner'+name]=function(){if(!this[0])return;var torl=name=='Height'?'Top':'Left',borr=name=='Height'?'Bottom':'Right';return this.is(':visible')?this[0]['client'+name]:num(this,name.toLowerCase())+num(this,'padding'+torl)+num(this,'padding'+borr);};$.fn['outer'+name]=function(options){if(!this[0])return;var torl=name=='Height'?'Top':'Left',borr=name=='Height'?'Bottom':'Right';options=$.extend({margin:false},options||{});var val=this.is(':visible')?this[0]['offset'+name]:num(this,name.toLowerCase())+num(this,'border'+torl+'Width')+num(this,'border'+borr+'Width')+num(this,'padding'+torl)+num(this,'padding'+borr);return val+(options.margin?(num(this,'margin'+torl)+num(this,'margin'+borr)):0);};});$.each(['Left','Top'],function(i,name){$.fn['scroll'+name]=function(val){if(!this[0])return;return val!=undefined?this.each(function(){this==window||this==document?window.scrollTo(name=='Left'?val:$(window)['scrollLeft'](),name=='Top'?val:$(window)['scrollTop']()):this['scroll'+name]=val;}):this[0]==window||this[0]==document?self[(name=='Left'?'pageXOffset':'pageYOffset')]||$.boxModel&&document.documentElement['scroll'+name]||document.body['scroll'+name]:this[0]['scroll'+name];};});$.fn.extend({position:function(){var left=0,top=0,elem=this[0],offset,parentOffset,offsetParent,results;if(elem){offsetParent=this.offsetParent();offset=this.offset();parentOffset=offsetParent.offset();offset.top-=num(elem,'marginTop');offset.left-=num(elem,'marginLeft');parentOffset.top+=num(offsetParent,'borderTopWidth');parentOffset.left+=num(offsetParent,'borderLeftWidth');results={top:offset.top-parentOffset.top,left:offset.left-parentOffset.left};}return results;},offsetParent:function(){var offsetParent=this[0].offsetParent;while(offsetParent&&(!/^body|html$/i.test(offsetParent.tagName)&&$.css(offsetParent,'position')=='static'))offsetParent=offsetParent.offsetParent;return $(offsetParent);}});function num(el,prop){return parseInt($.curCSS(el.jquery?el[0]:el,prop,true))||0;};})(jQuery);

/** File: plugins/jquery-history.js */
/************************ PLUGIN: HISTORY ************************************************************************/
/*
 * jQuery history plugin
 *
 * Copyright (c) 2006 Taku Sano (Mikage Sawatari)
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Modified by Lincoln Cooper to add Safari support and only call the callback once during initialization
 * for msie when no initial hash supplied.
 */


jQuery.extend({
	historyCurrentHash: undefined,

	historyCallback: undefined,

	historyInit: function(callback){
		jQuery.historyCallback = callback;
		var current_hash = location.hash;

		jQuery.historyCurrentHash = current_hash;
		if(jQuery.browser.msie) {
			// To stop the callback firing twice during initilization if no hash present
			if (jQuery.historyCurrentHash == '') {
			jQuery.historyCurrentHash = '#';
		}

			// add hidden iframe for IE
			$("body").prepend('<iframe id="jQuery_history" style="display: none;"></iframe>');
			var ihistory = $("#jQuery_history")[0];
			var iframe = ihistory.contentWindow.document;
			iframe.open();
			iframe.close();
			iframe.location.hash = current_hash;
		}
		else if ($.browser.safari) {
			// etablish back/forward stacks
			jQuery.historyBackStack = [];
			jQuery.historyBackStack.length = history.length;
			jQuery.historyForwardStack = [];

			jQuery.isFirst = true;
		}
		jQuery.historyCallback(current_hash.replace(/^#/, ''));
		setInterval(jQuery.historyCheck, 100);
	},

	historyAddHistory: function(hash) {
		// This makes the looping function do something
		jQuery.historyBackStack.push(hash);

		jQuery.historyForwardStack.length = 0; // clear forwardStack (true click occured)
		this.isFirst = true;
	},

	historyCheck: function(){
		if(jQuery.browser.msie) {
			// On IE, check for location.hash of iframe
			var ihistory = $("#jQuery_history")[0];
			var iframe = ihistory.contentDocument || ihistory.contentWindow.document;
			var current_hash = iframe.location.hash;
			if(current_hash != jQuery.historyCurrentHash) {

				location.hash = current_hash;
				jQuery.historyCurrentHash = current_hash;
				jQuery.historyCallback(current_hash.replace(/^#/, ''));

			}
		} else if ($.browser.safari) {
			if (!jQuery.dontCheck) {
				var historyDelta = history.length - jQuery.historyBackStack.length;

				if (historyDelta) { // back or forward button has been pushed
					jQuery.isFirst = false;
					if (historyDelta < 0) { // back button has been pushed
						// move items to forward stack
						for (var i = 0; i < Math.abs(historyDelta); i++) jQuery.historyForwardStack.unshift(jQuery.historyBackStack.pop());
					} else { // forward button has been pushed
						// move items to back stack
						for (var i = 0; i < historyDelta; i++) jQuery.historyBackStack.push(jQuery.historyForwardStack.shift());
					}
					var cachedHash = jQuery.historyBackStack[jQuery.historyBackStack.length - 1];
					if (cachedHash != undefined) {
						jQuery.historyCurrentHash = location.hash;
						jQuery.historyCallback(cachedHash);
					}
				} else if (jQuery.historyBackStack[jQuery.historyBackStack.length - 1] == undefined && !jQuery.isFirst) {
					// back button has been pushed to beginning and URL already pointed to hash (e.g. a bookmark)
					// document.URL doesn't change in Safari
					if (document.URL.indexOf('#') >= 0) {
						jQuery.historyCallback(document.URL.split('#')[1]);
					} else {
						var current_hash = location.hash;
						jQuery.historyCallback('');
					}
					jQuery.isFirst = true;
				}
			}
		} else {
			// otherwise, check for location.hash
			var current_hash = location.hash;
			if(current_hash != jQuery.historyCurrentHash) {
				jQuery.historyCurrentHash = current_hash;
				jQuery.historyCallback(current_hash.replace(/^#/, ''));
			}
		}
	},
	historyLoad: function(hash){
		var newhash;

		if (jQuery.browser.safari) {
			newhash = hash;
		}
		else {
			newhash = '#' + hash;
			location.hash = newhash;
		}
		jQuery.historyCurrentHash = newhash;

		if(jQuery.browser.msie) {
			var ihistory = $("#jQuery_history")[0];
			var iframe = ihistory.contentWindow.document;
			iframe.open();
			iframe.close();
			iframe.location.hash = newhash;
			jQuery.historyCallback(hash);
		}
		else if (jQuery.browser.safari) {
			jQuery.dontCheck = true;
			// Manually keep track of the history values for Safari
			this.historyAddHistory(hash);

			// Wait a while before allowing checking so that Safari has time to update the "history" object
			// correctly (otherwise the check loop would detect a false change in hash).
			var fn = function() {jQuery.dontCheck = false;};
			window.setTimeout(fn, 200);
			jQuery.historyCallback(hash);
			// N.B. "location.hash=" must be the last line of code for Safari as execution stops afterwards.
			//      By explicitly using the "location.hash" command (instead of using a variable set to "location.hash") the
			//      URL in the browser and the "history" object are both updated correctly.
			location.hash = newhash;
		}
		else {
		  jQuery.historyCallback(hash);
		}
	}
});

/************************ END PLUGIN: HISTORY ************************************************************************/


/** File: plugins/jquery-form-plugin.js */
/*
 * jQuery Form Plugin
 * version: 2.18 (06-JAN-2009)
 * @requires jQuery v1.2.2 or later
 *
 * Examples and documentation at: http://malsup.com/jquery/form/
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id: jquery-form-plugin.js,v 1.1.2.1 2009/10/21 15:48:38 ballawala Exp $
 */
;(function($) {

/*
    Usage Note:
    -----------
    Do not use both ajaxSubmit and ajaxForm on the same form.  These
    functions are intended to be exclusive.  Use ajaxSubmit if you want
    to bind your own submit handler to the form.  For example,

    $(document).ready(function() {
        $('#myForm').bind('submit', function() {
            $(this).ajaxSubmit({
                target: '#output'
            });
            return false; // <-- important!
        });
    });

    Use ajaxForm when you want the plugin to manage all the event binding
    for you.  For example,

    $(document).ready(function() {
        $('#myForm').ajaxForm({
            target: '#output'
        });
    });

    When using ajaxForm, the ajaxSubmit function will be invoked for you
    at the appropriate time.
*/

/**
 * ajaxSubmit() provides a mechanism for immediately submitting
 * an HTML form using AJAX.
 */
$.fn.ajaxSubmit = function(options) {
    // fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
    if (!this.length) {
        log('ajaxSubmit: skipping submit process - no element selected');
        return this;
    }

    if (typeof options == 'function')
        options = { success: options };

    options = $.extend({
        url:  this.attr('action') || window.location.toString(),
        type: this.attr('method') || 'GET'
    }, options || {});

    // hook for manipulating the form data before it is extracted;
    // convenient for use with rich editors like tinyMCE or FCKEditor
    var veto = {};
    this.trigger('form-pre-serialize', [this, options, veto]);
    if (veto.veto) {
        log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
        return this;
    }

    // provide opportunity to alter form data before it is serialized
    if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
        log('ajaxSubmit: submit aborted via beforeSerialize callback');
        return this;
    }

    var a = this.formToArray(options.semantic);
    if (options.data) {
        options.extraData = options.data;
        for (var n in options.data) {
          if(options.data[n] instanceof Array) {
            for (var k in options.data[n])
              a.push( { name: n, value: options.data[n][k] } )
          }
          else
             a.push( { name: n, value: options.data[n] } );
        }
    }

    // give pre-submit callback an opportunity to abort the submit
    if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
        log('ajaxSubmit: submit aborted via beforeSubmit callback');
        return this;
    }

    // fire vetoable 'validate' event
    this.trigger('form-submit-validate', [a, this, options, veto]);
    if (veto.veto) {
        log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
        return this;
    }

    var q = $.param(a);

    if (options.type.toUpperCase() == 'GET') {
        options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
        options.data = null;  // data is null for 'get'
    }
    else
        options.data = q; // data is the query string for 'post'

    var $form = this, callbacks = [];
    if (options.resetForm) callbacks.push(function() { $form.resetForm(); });
    if (options.clearForm) callbacks.push(function() { $form.clearForm(); });

    // perform a load on the target only if dataType is not provided
    if (!options.dataType && options.target) {
        var oldSuccess = options.success || function(){};
        callbacks.push(function(data) {
            $(options.target).html(data).each(oldSuccess, arguments);
        });
    }
    else if (options.success)
        callbacks.push(options.success);

    options.success = function(data, status) {
        for (var i=0, max=callbacks.length; i < max; i++)
            callbacks[i].apply(options, [data, status, $form]);
    };

    // are there files to upload?
    var files = $('input:file', this).fieldValue();
    var found = false;
    for (var j=0; j < files.length; j++)
        if (files[j])
            found = true;

    // options.iframe allows user to force iframe mode
   if (options.iframe || found) {
       // hack to fix Safari hang (thanks to Tim Molendijk for this)
       // see:  http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
       if ($.browser.safari && options.closeKeepAlive)
           $.get(options.closeKeepAlive, fileUpload);
       else
           fileUpload();
       }
   else
       $.ajax(options);

    // fire 'notify' event
    this.trigger('form-submit-notify', [this, options]);
    return this;


    // private function for handling file uploads (hat tip to YAHOO!)
    function fileUpload() {
        var form = $form[0];

        if ($(':input[name=submit]', form).length) {
            alert('Error: Form elements must not be named "submit".');
            return;
        }

        var opts = $.extend({}, $.ajaxSettings, options);
		var s = jQuery.extend(true, {}, $.extend(true, {}, $.ajaxSettings), opts);

        var id = 'jqFormIO' + (new Date().getTime());
        var $io = $('<iframe id="' + id + '" name="' + id + '" />');
        var io = $io[0];

        if ($.browser.msie || $.browser.opera)
            io.src = 'javascript:false;document.write("");';
        $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });

        var xhr = { // mock object
            aborted: 0,
            responseText: null,
            responseXML: null,
            status: 0,
            statusText: 'n/a',
            getAllResponseHeaders: function() {},
            getResponseHeader: function() {},
            setRequestHeader: function() {},
            abort: function() {
                this.aborted = 1;
                $io.attr('src','about:blank'); // abort op in progress
            }
        };

        var g = opts.global;
        // trigger ajax global events so that activity/block indicators work like normal
        if (g && ! $.active++) $.event.trigger("ajaxStart");
        if (g) $.event.trigger("ajaxSend", [xhr, opts]);

		if (s.beforeSend && s.beforeSend(xhr, s) === false) {
			s.global && jQuery.active--;
			return;
        }
        if (xhr.aborted)
            return;

        var cbInvoked = 0;
        var timedOut = 0;

        // add submitting element to data if we know it
        var sub = form.clk;
        if (sub) {
            var n = sub.name;
            if (n && !sub.disabled) {
                options.extraData = options.extraData || {};
                options.extraData[n] = sub.value;
                if (sub.type == "image") {
                    options.extraData[name+'.x'] = form.clk_x;
                    options.extraData[name+'.y'] = form.clk_y;
                }
            }
        }

        // take a breath so that pending repaints get some cpu time before the upload starts
        setTimeout(function() {
            // make sure form attrs are set
            var t = $form.attr('target'), a = $form.attr('action');
            $form.attr({
                target:   id,
                method:   'POST',
                action:   opts.url
            });

            // ie borks in some cases when setting encoding
            if (! options.skipEncodingOverride) {
                $form.attr({
                    encoding: 'multipart/form-data',
                    enctype:  'multipart/form-data'
                });
            }

            // support timout
            if (opts.timeout)
                setTimeout(function() { timedOut = true; cb(); }, opts.timeout);

            // add "extra" data to form if provided in options
            var extraInputs = [];
            try {
                if (options.extraData)
                    for (var n in options.extraData)
                        extraInputs.push(
                            $('<input type="hidden" name="'+n+'" value="'+options.extraData[n]+'" />')
                                .appendTo(form)[0]);

                // add iframe to doc and submit the form
                $io.appendTo('body');
                io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
                form.submit();
            }
            finally {
                // reset attrs and remove "extra" input elements
                $form.attr('action', a);
                t ? $form.attr('target', t) : $form.removeAttr('target');
                $(extraInputs).remove();
            }
        }, 10);

        function cb() {
            if (cbInvoked++) return;

            io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);

            var operaHack = 0;
            var ok = true;
            try {
                if (timedOut) throw 'timeout';
                // extract the server response from the iframe
                var data, doc;

                doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;

                if (doc.body == null && !operaHack && $.browser.opera) {
                    // In Opera 9.2.x the iframe DOM is not always traversable when
                    // the onload callback fires so we give Opera 100ms to right itself
                    operaHack = 1;
                    cbInvoked--;
                    setTimeout(cb, 100);
                    return;
                }

                xhr.responseText = doc.body ? doc.body.innerHTML : null;
                xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
                xhr.getResponseHeader = function(header){
                    var headers = {'content-type': opts.dataType};
                    return headers[header];
                };

                if (opts.dataType == 'json' || opts.dataType == 'script') {
                    var ta = doc.getElementsByTagName('textarea')[0];
                    xhr.responseText = ta ? ta.value : xhr.responseText;
                }
                else if (opts.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) {
                    xhr.responseXML = toXml(xhr.responseText);
                }
                data = $.httpData(xhr, opts.dataType);
            }
            catch(e){
                ok = false;
                $.handleError(opts, xhr, 'error', e);
            }

            // ordering of these callbacks/triggers is odd, but that's how $.ajax does it
            if (ok) {
                opts.success(data, 'success');
                if (g) $.event.trigger("ajaxSuccess", [xhr, opts]);
            }
            if (g) $.event.trigger("ajaxComplete", [xhr, opts]);
            if (g && ! --$.active) $.event.trigger("ajaxStop");
            if (opts.complete) opts.complete(xhr, ok ? 'success' : 'error');

            // clean up
            setTimeout(function() {
                $io.remove();
                xhr.responseXML = null;
            }, 100);
        };

        function toXml(s, doc) {
            if (window.ActiveXObject) {
                doc = new ActiveXObject('Microsoft.XMLDOM');
                doc.async = 'false';
                doc.loadXML(s);
            }
            else
                doc = (new DOMParser()).parseFromString(s, 'text/xml');
            return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc : null;
        };
    };
};

/**
 * ajaxForm() provides a mechanism for fully automating form submission.
 *
 * The advantages of using this method instead of ajaxSubmit() are:
 *
 * 1: This method will include coordinates for <input type="image" /> elements (if the element
 *    is used to submit the form).
 * 2. This method will include the submit element's name/value data (for the element that was
 *    used to submit the form).
 * 3. This method binds the submit() method to the form for you.
 *
 * The options argument for ajaxForm works exactly as it does for ajaxSubmit.  ajaxForm merely
 * passes the options argument along after properly binding events for submit elements and
 * the form itself.
 */
$.fn.ajaxForm = function(options) {
    return this.ajaxFormUnbind().bind('submit.form-plugin',function() {
        $(this).ajaxSubmit(options);
        return false;
    }).each(function() {
        // store options in hash
        $(":submit,input:image", this).bind('click.form-plugin',function(e) {
            var form = this.form;
            form.clk = this;
            if (this.type == 'image') {
                if (e.offsetX != undefined) {
                    form.clk_x = e.offsetX;
                    form.clk_y = e.offsetY;
                } else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin
                    var offset = $(this).offset();
                    form.clk_x = e.pageX - offset.left;
                    form.clk_y = e.pageY - offset.top;
                } else {
                    form.clk_x = e.pageX - this.offsetLeft;
                    form.clk_y = e.pageY - this.offsetTop;
                }
            }
            // clear form vars
            setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 10);
        });
    });
};

// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
$.fn.ajaxFormUnbind = function() {
    this.unbind('submit.form-plugin');
    return this.each(function() {
        $(":submit,input:image", this).unbind('click.form-plugin');
    });

};

/**
 * formToArray() gathers form element data into an array of objects that can
 * be passed to any of the following ajax functions: $.get, $.post, or load.
 * Each object in the array has both a 'name' and 'value' property.  An example of
 * an array for a simple login form might be:
 *
 * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
 *
 * It is this array that is passed to pre-submit callback functions provided to the
 * ajaxSubmit() and ajaxForm() methods.
 */
$.fn.formToArray = function(semantic) {
    var a = [];
    if (this.length == 0) return a;

    var form = this[0];
    var els = semantic ? form.getElementsByTagName('*') : form.elements;
    if (!els) return a;
    for(var i=0, max=els.length; i < max; i++) {
        var el = els[i];
        var n = el.name;
        if (!n) continue;

        if (semantic && form.clk && el.type == "image") {
            // handle image inputs on the fly when semantic == true
            if(!el.disabled && form.clk == el)
                a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
            continue;
        }

        var v = $.fieldValue(el, true);
        if (v && v.constructor == Array) {
            for(var j=0, jmax=v.length; j < jmax; j++)
                a.push({name: n, value: v[j]});
        }
        else if (v !== null && typeof v != 'undefined')
            a.push({name: n, value: v});
    }

    if (!semantic && form.clk) {
        // input type=='image' are not found in elements array! handle them here
        var inputs = form.getElementsByTagName("input");
        for(var i=0, max=inputs.length; i < max; i++) {
            var input = inputs[i];
            var n = input.name;
            if(n && !input.disabled && input.type == "image" && form.clk == input)
                a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
        }
    }
    return a;
};

/**
 * Serializes form data into a 'submittable' string. This method will return a string
 * in the format: name1=value1&amp;name2=value2
 */
$.fn.formSerialize = function(semantic) {
    //hand off to jQuery.param for proper encoding
    return $.param(this.formToArray(semantic));
};

/**
 * Serializes all field elements in the jQuery object into a query string.
 * This method will return a string in the format: name1=value1&amp;name2=value2
 */
$.fn.fieldSerialize = function(successful) {
    var a = [];
    this.each(function() {
        var n = this.name;
        if (!n) return;
        var v = $.fieldValue(this, successful);
        if (v && v.constructor == Array) {
            for (var i=0,max=v.length; i < max; i++)
                a.push({name: n, value: v[i]});
        }
        else if (v !== null && typeof v != 'undefined')
            a.push({name: this.name, value: v});
    });
    //hand off to jQuery.param for proper encoding
    return $.param(a);
};

/**
 * Returns the value(s) of the element in the matched set.  For example, consider the following form:
 *
 *  <form><fieldset>
 *      <input name="A" type="text" />
 *      <input name="A" type="text" />
 *      <input name="B" type="checkbox" value="B1" />
 *      <input name="B" type="checkbox" value="B2"/>
 *      <input name="C" type="radio" value="C1" />
 *      <input name="C" type="radio" value="C2" />
 *  </fieldset></form>
 *
 *  var v = $(':text').fieldValue();
 *  // if no values are entered into the text inputs
 *  v == ['','']
 *  // if values entered into the text inputs are 'foo' and 'bar'
 *  v == ['foo','bar']
 *
 *  var v = $(':checkbox').fieldValue();
 *  // if neither checkbox is checked
 *  v === undefined
 *  // if both checkboxes are checked
 *  v == ['B1', 'B2']
 *
 *  var v = $(':radio').fieldValue();
 *  // if neither radio is checked
 *  v === undefined
 *  // if first radio is checked
 *  v == ['C1']
 *
 * The successful argument controls whether or not the field element must be 'successful'
 * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
 * The default value of the successful argument is true.  If this value is false the value(s)
 * for each element is returned.
 *
 * Note: This method *always* returns an array.  If no valid value can be determined the
 *       array will be empty, otherwise it will contain one or more values.
 */
$.fn.fieldValue = function(successful) {
    for (var val=[], i=0, max=this.length; i < max; i++) {
        var el = this[i];
        var v = $.fieldValue(el, successful);
        if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length))
            continue;
        v.constructor == Array ? $.merge(val, v) : val.push(v);
    }
    return val;
};

/**
 * Returns the value of the field element.
 */
$.fieldValue = function(el, successful) {
    var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
    if (typeof successful == 'undefined') successful = true;

    if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
        (t == 'checkbox' || t == 'radio') && !el.checked ||
        (t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
        tag == 'select' && el.selectedIndex == -1))
            return null;

    if (tag == 'select') {
        var index = el.selectedIndex;
        if (index < 0) return null;
        var a = [], ops = el.options;
        var one = (t == 'select-one');
        var max = (one ? index+1 : ops.length);
        for(var i=(one ? index : 0); i < max; i++) {
            var op = ops[i];
            if (op.selected) {
                // extra pain for IE...
                var v = $.browser.msie && !(op.attributes['value'].specified) ? op.text : op.value;
                if (one) return v;
                a.push(v);
            }
        }
        return a;
    }
    return el.value;
};

/**
 * Clears the form data.  Takes the following actions on the form's input fields:
 *  - input text fields will have their 'value' property set to the empty string
 *  - select elements will have their 'selectedIndex' property set to -1
 *  - checkbox and radio inputs will have their 'checked' property set to false
 *  - inputs of type submit, button, reset, and hidden will *not* be effected
 *  - button elements will *not* be effected
 */
$.fn.clearForm = function() {
    return this.each(function() {
        $('input,select,textarea', this).clearFields();
    });
};

/**
 * Clears the selected form elements.
 */
$.fn.clearFields = $.fn.clearInputs = function() {
    return this.each(function() {
        var t = this.type, tag = this.tagName.toLowerCase();
        if (t == 'text' || t == 'password' || tag == 'textarea')
            this.value = '';
        else if (t == 'checkbox' || t == 'radio')
            this.checked = false;
        else if (tag == 'select')
            this.selectedIndex = -1;
    });
};

/**
 * Resets the form data.  Causes all form elements to be reset to their original value.
 */
$.fn.resetForm = function() {
    return this.each(function() {
        // guard against an input with the name of 'reset'
        // note that IE reports the reset function as an 'object'
        if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType))
            this.reset();
    });
};

/**
 * Enables or disables any matching elements.
 */
$.fn.enable = function(b) {
    if (b == undefined) b = true;
    return this.each(function() {
        this.disabled = !b
    });
};

/**
 * Checks/unchecks any matching checkboxes or radio buttons and
 * selects/deselects and matching option elements.
 */
$.fn.selected = function(select) {
    if (select == undefined) select = true;
    return this.each(function() {
        var t = this.type;
        if (t == 'checkbox' || t == 'radio')
            this.checked = select;
        else if (this.tagName.toLowerCase() == 'option') {
            var $sel = $(this).parent('select');
            if (select && $sel[0] && $sel[0].type == 'select-one') {
                // deselect all other options
                $sel.find('option').selected(false);
            }
            this.selected = select;
        }
    });
};

// helper fn for console logging
// set $.fn.ajaxSubmit.debug to true to enable debug logging
function log() {
    if ($.fn.ajaxSubmit.debug && window.console && window.console.log)
        window.console.log('[jquery.form] ' + Array.prototype.join.call(arguments,''));
};

})(jQuery);


/** File: pronto3/common/plugins/rc-text-truncate.js */
(function($){
    $.fn.RCTextLimit = function(numDisplayRef,limit) {
        $(numDisplayRef).html(limit - this[0].value.length);
        this.keypress(function(e) {
        if(this.value.length > limit) e.preventDefault();
        }).keyup(function(e){
            if(this.value.length > limit) {
                this.value = this.value.substring(0,limit);
                if(numDisplayRef) $(numDisplayRef).html(0);
            }
            else {
                if(numDisplayRef) $(numDisplayRef).html(limit - this.value.length);
            }
        });
    }     
})(jQuery);

/** File: autocomplete_init.js */
// initialize autocomplete
$(document).ready(function() {
    var hideAC = $.cookie('disableProntoAC');
    if (hideAC != 'true') {
        $("input#inputQuery").autocomplete(
            "/ajaxSuggest",
            {
                delay:10,
                minChars:1,
                matchSubset:1,
                matchContains:1,
                cacheLength:1,
                onItemSelect:selectItem,
                onFindValue:findValue,
                autoFill:false
            }
        );
        $("input#bottomquery").autocomplete(
            "/ajaxSuggest",
            {
                delay:10,
                minChars:1,
                matchSubset:1,
                matchContains:1,
                cacheLength:1,
                onItemSelect:selectItem,
                onFindValue:findValue,
                autoFill:false
            }
        );
    }
});
function findValue(li) {
    var sValue = li.selectValue;
}
function selectItem(li) {
    findValue(li);
}
function disableAC() {
    $("input#inputQuery").unbind("keydown");
    $("input#bottomquery").unbind("keydown");
    $.cookie('disableProntoAC', 'true', {path: '/'});
}


/** File: community/star_rating.js */
/* star rating */
/*
var StarTypes = new function() {
  function StarType() {
    this.unselectedBackgroundPosition = "0 0px";
    this.supportsHalf = false;
  }

  this.CURRENT_USER = new StarType();
  this.CURRENT_USER.selectedBackgroundPosition = "0 -600px";

  this.AVERAGE = new StarType();
  this.AVERAGE.selectedBackgroundPosition = "0 -100px";
//  this.AVERAGE.halfSelectedBackgroundPosition = "0 -150px";
  this.AVERAGE.supportsHalf = true;

  this.FEATURED = new StarType();
  this.FEATURED.selectedBackgroundPosition = "0 -250px";

  this.names = ["CURRENT_USER", "AVERAGE", "FEATURED"];
};*/

function fromPrototype(o) { function F() {}; F.prototype = o; return new F(); }

function newItemKey(itemKeyFields) {
  var itemKey = fromPrototype(itemKeyFields);
  itemKey.toString = function() {
      if (this.itemType == "brand")
        return "brand_" + this.brandKey;
      if (this.itemType == "merchant")
        return "merchant_" + this.merchantId;
      if (this.itemType == "product")
        return "product_" + this.prontoProductId;
      if (this.itemType == "bookmark")
        return "bookmark_" + this.bookmarkId;
      return "unknown";
    };
  itemKey.equals = function(other) {
    return other && this.toString() == other.toString();
  }
  return itemKey;
}

var initialStarStates = new Object();

function setInitialStarState(starContainerId, starPos, ratings) {
  initialStarStates[starContainerId] = {starPos: starPos, ratings: ratings};
}

function getProp(starContainerId, prop) {
  return $("#" + starContainerId + "_" + prop).val();
  return inputs.length > 0 ? inputs.val() : "";
}

function setProp(starContainerId, prop, val) {
  $("#" + starContainerId + "_" + prop).val(val);
}

function setNewUserSelection(reviewId, itemKey, starInfoObj, starRef) {
//    var starPosition = starRef.attr("style");

    var rating = starInfoObj.rating;
  if (itemKey) {

      $("div.starContainerItem_" + itemKey).each(function() {
      var starContainer = $(this);
      var starContainerId = starContainer.attr("id");
      var state = initialStarStates[starContainerId];
      if(starContainer.children(".FEATURED").size() > 0)
          var starPosition = "background-position:" + starInfoObj.xScroll + "px" + " " + (-300 + starInfoObj.yScroll) + "px";
      else
         var starPosition = "background-position:" + starInfoObj.xScroll + "px" + " " + starInfoObj.yScroll + "px";
          
      if (rating == -1)  {
        // if rating is -1 then backfill with average rating position          
          var avgRating = $("#" + starContainerId).children(".average_rating").attr('value');
          // to calculate the position of the average rating
          var pos = -(100 + ((2 * (avgRating - Math.floor(avgRating) == 0 ? avgRating : (avgRating - Math.floor(avgRating) >= 0.5 ? Math.floor(avgRating) + 0.5 : Math.floor(avgRating))))-1)*50)
          state.starPos = "background-position: 0pt " + pos + "px;";
          }
        else {
        state.starPos = starPosition;
      }
        state.ratings = rating;
        drawInitialRating(starContainerId);
    });


 }
  if (reviewId) {
    if (rating <= 0)
      $("div.reviewContainer_" + reviewId).remove();


      $("div.starContainerReview_" + reviewId).each(function() {
      var starContainer = $(this);
      var starContainerId = starContainer.attr("id");
      var state = initialStarStates[starContainerId];
      if(starContainer.children(".FEATURED").size() > 0)
            var starPosition = "background-position:" + starInfoObj.xScroll + "px" + " " + (-300 + starInfoObj.yScroll) + "px";
      else
            var starPosition = "background-position:" + starInfoObj.xScroll + "px" + " " + starInfoObj.yScroll + "px";

      if (rating == -1)  {
          var avgRating = $("#" + starContainerId).children(".average_rating").attr('value');
          var pos = -(100 + ((2 * (avgRating - Math.floor(avgRating) == 0 ? avgRating : (avgRating - Math.floor(avgRating) >= 0.5 ? Math.floor(avgRating) + 0.5 : Math.floor(avgRating))))-1)*50)
          state.starPos = "background-position: 0pt " + pos + "px;";
          }
        else {
        state.starPos = starPosition;
      }
          
      state.ratings = rating;
      drawInitialRating(starContainerId);
    });


  }
}

function getItemKey(starContainerId) {
  var itemKeyJSON = getProp(starContainerId, "item_key");
  if (itemKeyJSON)
    return newItemKey(eval('(' + itemKeyJSON + ')'));
  return null;
}

var itemProperties = new function() {
  this.getCurrentUserHasReview = function(itemKey) { return this[itemKey + "_currentUserHasReview"]; };
  this.setCurrentUserHasReview = function(itemKey, value) { this[itemKey + "_currentUserHasReview"] = (value ? true : false); };
  this.getCurrentStarPosition = function(itemKey) {return this[itemKey + "_starPosition"]};
  this.setCurrentStarPosition = function(itemKey, value) {this[itemKey + "_starPosition"] = value;};  
};

function loadInitialStarStates() {
  var starContainers = $("div.starContainer");
  starContainers.each(function() {
    var starContainer = $(this);
    var starContainerId = starContainer.attr("id");
    function getRatingProp(prop) {
      var rating = parseFloat(getProp(starContainerId, prop));
      return isNaN(rating) ? 0 : rating;
    }
    var starType = getProp(starContainerId, "star_type");
    var ratings = new Object();

    var itemKey = getItemKey(starContainerId);
    if (itemKey && getProp(starContainerId, "current_user_has_reviewed_it") == "true") {
      itemProperties.setCurrentUserHasReview(itemKey, true);
    }
    var starImage = $(this).children('img.ratingImage');
   var starPos = $(starImage).attr('style')
    setInitialStarState(starContainerId, starPos, getInitialRating(starPos));
  });
}

$(loadInitialStarStates); 

function drawInitialRating(starContainerId) {
  var initialState = initialStarStates[starContainerId];

  if (initialState) {

      $("#" + starContainerId).children(".ratingImage").attr("style",initialState.starPos)
  }
}

var pageLoaded = false;
$(function(){pageLoaded=true;});

function removeRatingReview(linkRef,itemKeyParams, rating, reviewId) {
    itemKey = newItemKey(itemKeyParams);
    submitStarRatingTask(itemKey, rating, null, null, null, null);
    $(linkRef).parents('.rReviewsEachItem').css('display','none');
}

function pickStar(itemKeyParams, e, starRef, productRefreshDiv, view, listingsViewType, reviewId, suppressRegisterForm,itemKeyStrEncoding, imgRoot) {
  itemKey = newItemKey(itemKeyParams);
  var starInfoObj = new Object;
  starInfoObj =  getStarInfo(e,starRef);
  var rating = starInfoObj.rating;
   var starContainerId = starRef.parents(".starContainer").attr("id");
    var state = initialStarStates[starContainerId];
    var currentUserRating = state.ratings;
  if (rating == -1 && (currentUserRating > 0)) {
        var itemKey = newItemKey(itemKeyParams);
        if (itemProperties.getCurrentUserHasReview(itemKey)) {
            starRef.parents(".starContainer").css("display","none");
            if(starRef.parents(".starContainer").siblings('.confirmReviewDelete').size() > 0) {
                starRef.parents(".starContainer").siblings('.confirmReviewDelete').css("display","block");
            }
            else{
             var popup = "<div  class='confirmReviewDelete'><h3>are you sure?</h3>Your review will be removed"
                 popup += " <div class='buttons'>"
                 popup += "<a href='#' onclick='return false;' class='linkYes'>"
                 popup += "<img src='" + imgRoot + "images2_5/shared/blank.gif' width='31px' height='16px' alt='yes' class='btnYes'/></a>"
                 popup += "<a href='#' onclick='$(this).parents(\".buttons\").parents(\".confirmReviewDelete\").css(\"display\",\"none\");$(this).parents(\".confirmReviewDelete\").siblings(\".starContainer\").css(\"display\",\"block\");return false;'>";
                 popup += "<img src='" + imgRoot + "images2_5/shared/blank.gif' width='31px' height='16px' alt='no' class='btnNo'/></a>"
                 popup  += "</div></div>"
//                starRef.parents("a").parents(".starContainer").append(popup);
//                starRef.parents(".starContainer").parent().append(popup);
                $(popup).insertAfter(starRef.parents(".starContainer"));
                starRef.parents(".starContainer").siblings('.confirmReviewDelete').children('.buttons').children('.linkYes').click(function() {
        //            confirmRetractStar(itemKeyParams ,-1,starRef, productRefreshDiv , view ,  listingsViewType , reviewId, itemKeyStrEncoding);return false;
                    starRef.parents(".starContainer").css("display", "block");                    
                    starRef.parents(".starContainer").siblings('.confirmReviewDelete').css("display","none");
                    setNewUserSelection(reviewId, itemKey, starInfoObj,starRef);
                    submitStarRatingTask(itemKey, rating, productRefreshDiv, view, listingsViewType, suppressRegisterForm);
                    return false;
                 })
                }
              }
            else {
                    setNewUserSelection(reviewId, itemKey, starInfoObj,starRef);
                    submitStarRatingTask(itemKey, rating, productRefreshDiv, view, listingsViewType, suppressRegisterForm);
        }
        }
    else if(rating != -1){
        setNewUserSelection(reviewId, itemKey, starInfoObj,starRef);
        submitStarRatingTask(itemKey, rating, productRefreshDiv, view, listingsViewType, suppressRegisterForm);
      }
}

var starRatingTasks = new Array();
var numTasks = 0;

function submitStarRatingTask(itemKey, rating, productRefreshDiv, view, listingsViewType, suppressRegisterForm) {
   var task = {itemKey: itemKey, rating: rating, productRefreshDiv: productRefreshDiv,
               view: view, listingsViewType: listingsViewType, suppressRegisterForm: suppressRegisterForm};
   if (numTasks++ <= 0)
     // Don't bother enqueueing the task. Just go.
     updateStarRating(task);
   else {
     // Look for an earlier selection on the same itemKey.
     for (var i = 0; i < starRatingTasks.length; i++)
       if (starRatingTasks[i].itemKey.equals(itemKey)) {
         starRatingTasks[i] = task;
         return;
       }
     starRatingTasks.push(task);
   }
}

function updateStarRating(task) {
  var reviewParams = fromPrototype(task.itemKey);
  reviewParams.rating = task.rating;
  reviewParams.submitRating = true;
  reviewParams.suppressRegisterForm = task.suppressRegisterForm;

  updateItemReview(
          reviewParams,
          function() {
            if (task.itemKey.itemType == 'product' && task.productRefreshDiv && task.view) {
               if ($("div." + task.productRefreshDiv).html()) {
                 var asyncURL = "/community/productAsynchDataRetrieval.do?prontoProductId=" + task.itemKey.prontoProductId
                                 + "&view=" + task.view
                                 + "&listingsViewType=" + task.listingsViewType;
                 $("div." + task.productRefreshDiv).each(function() {$(this).load(asyncURL, {}, loadInitialStarStates);});
               }
            }
            if (starRatingTasks.length > 0)
              updateStarRating(starRatingTasks.shift());
            numTasks = starRatingTasks.length;
          },
          // on lightbox, clear the task queue
          function() { starRatingTasks = []; numTasks = 0; });
}

function showItemReviewFormHelper(divId, itemKeyParams,callbackDivRef, callback, currentUrl, action) {
  var dialogDiv = $("div#" + divId + " div.itemreviewdialog");
  if (dialogDiv.length > 0) {
    var msgDiv = $("div#" + divId + " div.itemreviewsubmitmessage");
    msgDiv.html('');
    msgDiv.hide();
    dialogDiv.show();
    callback(callbackDivRef)
  } else {
    var urlParams = fromPrototype(itemKeyParams);
    urlParams.context = "itemReviewDialog";
    urlParams.parentUrl = currentUrl;
    $("div#"+divId).load(action, urlParams, function() {loadInitialStarStates(); callback(callbackDivRef);});
  }
}

function showItemReviewForm(divId, itemKeyParams,callbackDivRef, callback, currentUrl) {
    showItemReviewFormHelper(divId,itemKeyParams,callbackDivRef, callback, currentUrl,
        "/community/itemReviewShowDialog.do");
}

function showBookmarkEditForm(divId, itemKeyParams,callbackDivRef, callback, currentUrl) {
    showItemReviewFormHelper(divId,itemKeyParams,callbackDivRef, callback, currentUrl,
        "/community/bmBlueBox.do");
}

function getTagTexts(dialogId) {
  var tagTexts = new Array();
  $("#" + dialogId + "_dialog").find(".tagContainer").find(".tagText").each(function() {
    var tagText = $(this).text();
    if (tagText)
      tagTexts.push(tagText);
  });
  return tagTexts;
}

function validateEditCopyListItemReviewData(formId) {
    var hasErrors = false;

    //  for each rating and review element in the form.
    $(".listEachItem").each(function() {
        var state = initialStarStates[$(this).find(".starContainer").attr("id")];
        var rating = state.ratings;
        var reviewText = $(this).find(".reviewText").attr('value');
        var tagText = $(this).find(".tagValues").attr('value');
        var tagArr;
        if (tagText == "" || tagText == undefined)
            tagArr = [];
        else
            tagArr = tagText.split(',');

        var msgEltText = validateItemReviewForm(rating, reviewText, tagArr, tagText, false);
        var errorDiv = $(this).find(".errorMsg");
        if (msgEltText) {
            hasErrors = true;
            errorDiv.html(msgEltText);
            errorDiv.css("display", "block");
        }
        else {
            errorDiv.css("display", "none");
        }

    });
    // end for

    if (hasErrors) {
        var formMsgElt = $(".aggregateError");
        formMsgElt.html("Please correct the errors below before continuing.");
        formMsgElt.css("display", "block");
    }

    return !hasErrors;
}

function submitItemReviewForm(dialogId, starContainerId, itemKeyParams, reviewId, itemKeyStrEncoding, parentUrl) {
  var state = initialStarStates[starContainerId];
//  var rating = state ? state.ratings.CURRENT_USER : 0;
    var rating = state.ratings;
    var reviewText = $("#" + dialogId + "_item_review_text_area").val();
  var tagArray = getTagTexts(dialogId);
  var tagText = tagArray.join(",");

  var msgEltText = validateItemReviewForm(rating,reviewText,tagArray,tagText,true);

  var msgElt = $("#" + dialogId + "_message");
  if (msgEltText) {
    msgElt.text(msgEltText);
    msgElt.show();
    return;
  }
  msgElt.hide();

  var reviewParams = fromPrototype(itemKeyParams);
  reviewParams.reviewText = reviewText;
  reviewParams.rating = rating;
  var itemKey = newItemKey(itemKeyParams);
  itemProperties.setCurrentUserHasReview(itemKey, (reviewParams.reviewText && !reviewParams.reviewText.match(/^\s+$/)));
  reviewParams.submitRating = true;
  reviewParams.submitReviewText = true;
  reviewParams.tags = tagText;
  reviewParams.returnUrl = parentUrl;
  updateItemReview(reviewParams,
    function() {
//        $("#" + dialogId + "_dialog").html("<div class='listErrorMsg'>Thank you for submitting your review.</div");
        refTab = $("#" + dialogId + "_dialog").parents('.lblueContainer').children(".lblueTabContainer").children().children("a.reviewTab");
        $("div#" + dialogId + "_submitmessage").html("Thank you for submitting your review.");
        $("div#" + dialogId + "_submitmessage").show();
        setTimeout(function(){deselectBlueTab(refTab)},3000);
        hideDialogDiv(dialogId);
    });
    var reviewDivIdentifier=itemKeyStrEncoding + '_' + reviewId;
    if (reviewParams.reviewText) {
        $(".review_" + reviewDivIdentifier).html(escTextForRedisplay(reviewParams.reviewText));
        $(".review_main_" + reviewDivIdentifier).fadeIn();
    } else {
        $(".review_" + reviewDivIdentifier).html('');
        $(".review_main_" + reviewDivIdentifier).fadeOut();
    }
}

function submitBookmarkUpdateForm(dialogId, starContainerId, itemKeyParams, reviewId, itemKeyStrEncoding) {
    var state = initialStarStates[starContainerId];
//    var rating = state ? state.ratings.CURRENT_USER : 0;
    var rating = state.ratings;
    var reviewText = $("#" + dialogId + "_item_review_text_area").val();
    var tagArray = getTagTexts(dialogId);
    var tagText = tagArray.join(",");
    var description = $("#" + dialogId + "_bm_description_text_area").val();
    var priceText = $("#" + dialogId + "_bm_price_text_area").val();
    var titleText = $("#" + dialogId + "_bm_title_text_area").val();

    var msgEltText = validateBookmarkUpdateForm(rating,reviewText,tagArray,tagText,description,priceText,titleText);

    var msgElt = $("#" + dialogId + "_message");
    if (msgEltText) {
        msgElt.text(msgEltText);
        msgElt.show();
        return;
    }
    msgElt.hide();

    var reviewParams = fromPrototype(itemKeyParams);
    reviewParams.reviewText = reviewText;
    reviewParams.rating = rating;
    reviewParams.descriptions = description;
    reviewParams.prices = priceText;
    reviewParams.titles = titleText;
    var itemKey = newItemKey(itemKeyParams);
    itemProperties.setCurrentUserHasReview(itemKey, (reviewParams.reviewText && !reviewParams.reviewText.match(/^\s+$/)));
//    reviewParams.submitRating = true;
//    reviewParams.submitReviewText = true;
    reviewParams.tags = tagText;
    updateBookmark(reviewParams,
    function() {
        refTab = $("#" + dialogId + "_dialog").parents('.lblueContainer').children(".lblueTabContainer").children().children("a.lbSecond");
        $("div#" + dialogId + "_submitmessage").html("Bookmark successfully updated.");
        $("div#" + dialogId + "_submitmessage").show();
        setTimeout(function(){deselectBlueTab(refTab)},3000);
        hideDialogDiv(dialogId);
    });
    var reviewDivIdentifier=itemKeyStrEncoding + '_' + reviewId;
    if (reviewParams.reviewText) {
        $(".review_" + reviewDivIdentifier).html(escTextForRedisplay(reviewParams.reviewText));
        $(".review_main_" + reviewDivIdentifier).fadeIn();
    } else {
        $(".review_" + reviewDivIdentifier).html('');
        $(".review_main_" + reviewDivIdentifier).fadeOut();
    }
//    $(".bmDescription" + itemKeyParams.bookmarkId).html(escTextForRedisplay(description));
    // FIXMEROYCE - refresh title
//    $(".bmPrice" + itemKeyParams.bookmarkId).html(escTextForRedisplay(priceText));
}

function escTextForRedisplay(s)
{
    if (s)
        return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")
            .replace(/\n/g, "<br />");
    return s;
}

function validateItemReviewForm(rating,reviewText,tagArray,tagText,requireRating)
{
    var msgEltText = "";
    if ( (!rating || rating <= 0) && (reviewText || requireRating))
        return "A rating is required to save a review.";
    else if (reviewText && reviewText.length > 1500)
        return "The maximum character count for review text is 1500.";
    else if (tagArray && tagArray.length > 10)
        return "The maximum number of tags is 10.";
    else if (tagText && tagText.length > 520)
        return "The maximum character count for tags is 520."
    return "";
}

function validateBookmarkUpdateForm(rating,reviewText,tagArray,tagText,description,priceText,titleText)
{
    var msgEltText = "";

    var COUNT_ERROR_PREFIX="The maximum character count for a bookmark ";

    if ((!rating || rating <= 0) && reviewText)
        return "A rating is required to save a review."
    else if (reviewText && reviewText.length > 1500)
        return COUNT_ERROR_PREFIX+"review is 1500.";
    else if (tagArray.length > 10)
        return "The maximum number of tags allowed is 10.";
    else if (tagText.length > 520)
        return "The maximum character count for bookmark tags is 520."
    else if (description && description.length > 2500)
        return COUNT_ERROR_PREFIX+"description is 2500.";
    else if (priceText && priceText.length > 100)
        return COUNT_ERROR_PREFIX+"price is 100.";
    else if (titleText && titleText.length > 100)
        return COUNT_ERROR_PREFIX+"title is 100.";

    return "";
}

function hideDialogDiv(dialogId) {
  var dialogDiv = $("div#" + dialogId + "_dialog");
  dialogDiv.hide();
  dialogDiv.parents("div.reviewdialog_outer_container").find("a.reviewdialog_link").show();
}

function submitReviewFeedback(divId, reviewId, feedbackType) {
  $.post("/community/reviewFeedback.do", {reviewId: reviewId, feedbackType: feedbackType});
  var div = $("div#" + divId);
  if (feedbackType == 'agrees')
    div.html("<span class=\"yesuseful\">Thanks for your feedback, we're glad you found this comment helpful.</span>");
  else
    div.html("<span class=\"notuseful\">Thanks for letting us know that you didn't find this comment helpful.</span>");
}

var REVIEW_PARAMS_TO_COPY = ["itemType", "prontoProductId", "brandKey", "merchantId", "rating", "reviewText", "submitRating", "submitReviewText", "tags","bookmarkId"];

function updateItemReview(reviewParams, onsuccess, onlb) {
  var urlParams = new Object();
  for (var i = 0; i < REVIEW_PARAMS_TO_COPY.length; i++)
    if (reviewParams[REVIEW_PARAMS_TO_COPY[i]]) {
      urlParams[REVIEW_PARAMS_TO_COPY[i]] = reviewParams[REVIEW_PARAMS_TO_COPY[i]];
    }

  // Force these to boolean type
  if (reviewParams.suppressRegisterForm)
    urlParams.suppressRegisterForm = true;
  if (reviewParams.updateRatingOnly)
    urlParams.updateRatingOnly = true;
  if (reviewParams.updateReviewTextOnly)
    urlParams.updateReviewTextOnly = true;

  // Add globabl returnUrl
  urlParams.returnUrl = thisPageURL;

  function fullCallback(data) {
    // Defined in lists.js
    // Allows for lightbox instead of calling onsuccess directly.
    asyncFormSubmitCallback(data, onsuccess, null, onlb);
  }

  $.post("/community/itemReview.do", urlParams, fullCallback);
}

var BOOKMARK_PARAMS_TO_COPY = ["itemType", "rating", "reviewText", "tags",
    "bookmarkId", "titles", "descriptions", "prices", "submitRating",
    "submitReviewText", ];

function updateBookmark(bookmarkParams, onsuccess) {
  var urlParams = new Object();
  for (var i = 0; i < BOOKMARK_PARAMS_TO_COPY.length; i++)
    if (bookmarkParams[BOOKMARK_PARAMS_TO_COPY[i]]) {
      urlParams[BOOKMARK_PARAMS_TO_COPY[i]] = bookmarkParams[BOOKMARK_PARAMS_TO_COPY[i]];
    }

  // Force these to boolean type
  if (bookmarkParams.suppressRegisterForm)
    urlParams.suppressRegisterForm = true;
  if (bookmarkParams.updateRatingOnly)
    urlParams.updateRatingOnly = true;
  if (bookmarkParams.updateReviewTextOnly)
    urlParams.updateReviewTextOnly = true;

  // Add globabl returnUrl
  urlParams.returnUrl = thisPageURL;

  function fullCallback(data) {
    // Defined in lists.js
    // Allows for lightbox instead of calling onsuccess directly.
    asyncFormSubmitCallback(data, onsuccess);
  }

  $.post("/user/saveBookmarklet.do", urlParams, fullCallback);
}



function hoverStars(e,divRef) {
    try
    {
        var starContainerId = divRef.parents(".starContainer").attr("id");
        var state = initialStarStates[starContainerId];
        var currentUserRating = state.ratings;
        var starInfo = new Object;
        starInfo =  getStarInfo(e,divRef);
        var tempVar = "" + starInfo.xScroll + "px " + starInfo.yScroll + "px"
        var tempBG = divRef.attr('id')
        if((starInfo.rating != -1 ) || (starInfo.rating == -1 && (currentUserRating > 0)))
            document.getElementById(tempBG).style.backgroundPosition = tempVar;
        }
    catch(err){
    }
}

function getInitialRating(style) {
    style = ($.trim(style)).toLowerCase();
    var initArr = style.split(" ");
    var initYScroll = initArr[initArr.length - 1];
    if(initYScroll.charAt(initYScroll.length - 1) == ";")
        initYScroll = initYScroll.substring(0,initYScroll.length - 1);
    initYScroll.replace(/px/, "");
    initYScroll = parseInt(initYScroll);
    if(initYScroll == -800)
        return 5;
    else if(initYScroll == -800)
        return 5;
    else if(initYScroll == -750)
        return 4;
    else if(initYScroll == -700)
        return 3;
    else if(initYScroll == -650)
        return  2;
    else if(initYScroll == -600)
        return 1
    else return 0;
    
}

function getStarInfo(e,divRef) {
    var posX = 0;
        var posy = 0;
        if (!e) var e = window.event;
        if (e.pageX || e.pageY)
        {
           posX = e.pageX;
           posy = e.pageY;
        }
     else if (e.clientX || e.clientY)
        {
           posX = e.clientX;
           posy = e.clientY;
        }
          posX = posX - divRef.offset().left;

        var starInfo = new Object;
        if(posX < 17)
        {
            starInfo.rating = 1;
            starInfo.xScroll = 0;
            starInfo.yScroll = -600;
        }
        else if (posX > 17 && posX < 34)
        {
            starInfo.rating = 2;
            starInfo.xScroll = 0;
            starInfo.yScroll = -650;
        }
        else if (posX > 34 && posX < 51)
        {
            starInfo.rating = 3;
            starInfo.xScroll = 0;
            starInfo.yScroll = -700;
        }

        else if (posX > 51 && posX < 68)
        {
            starInfo.rating = 4;
            starInfo.xScroll = 0;
            starInfo.yScroll = -750;
        }

        else if (posX > 68 && posX < 85)
        {
            starInfo.rating = 5;
            starInfo.xScroll = 0;
            starInfo.yScroll = -800;
        }

        else if (posX > 85 && posX < 120)
        {
            starInfo.rating = -1;
            starInfo.xScroll = 0;
            starInfo.yScroll = -850;
        }
        return starInfo;

}

/** File: community/captcha.js */
var RECAPTCHA_JS_URL = "http://api.recaptcha.net/js/recaptcha_ajax.js";
  var RECAPTCHA_PUBLIC_KEY = "6LewhgMAAAAAAGOjUcSE42Mey1HUqMletbZ6Op0p"

  var loadedCaptchaJS = false;
  var captchaDivCounter = 0;

  //Protect against double submit.
  var captchaLastSubmitTime = 0;
  var captchaLastResponse = "";

  /**
   * Params:
   * 
   * parentForm (required): the form the captcha lives in
   * ajax (optional): if true, parentForm is taken over for AJAX
   *   captcha validation
   * successCallback (optional): if ajax, this is called after
   *   the user successfully solves the captcha
   * setFocus (optional): if true, place focus in the CAPTCHA
   *   response input
   */
  function fillCaptcha( params ) {
    var captchaForm = params.parentForm

    var captchaDiv = captchaForm.find("div.captcha_div");
    var divId = captchaDiv.attr("id");
    if (!divId) {
      divId = "captcha_div_" + (captchaDivCounter++);
      captchaDiv.attr("id", divId);
    }

    function onsubmitCaptcha() {
      var thisTime = new Date().getTime();
      if (thisTime - captchaLastSubmitTime < 5000
            && Recaptcha.get_response() == captchaLastResponse)
        // same within 5 seconds
        return false;
      captchaLastSubmitTime = thisTime;
      captchaLastResponse = Recaptcha.get_response();
      function onCorrectResponse() {
        destroyCaptcha(captchaForm);
        if (params.successCallback)
          params.successCallback();
      }
      function onIncorrectResponse() {
        Recaptcha.reload();
        captchaForm.find(".error_message").text("response was incorrect").show();
        Recaptcha.focus_response_field();
      }
      _validateCaptcha(onCorrectResponse, onIncorrectResponse);
      return false;
    }
    function afterLoadedJS() {
      Recaptcha.create(RECAPTCHA_PUBLIC_KEY,
          divId, {
             theme: "clean",
             callback: 
               function(){
                  if (params.ajax) {
                    captchaForm.bind("submit", onsubmitCaptcha);
                    captchaForm.show();
                  }
                  if (params.setFocus)
                    Recaptcha.focus_response_field();
              }
          });
    }
    if (loadedCaptchaJS)
      afterLoadedJS();
    else {
      $.getScript(RECAPTCHA_JS_URL,
           function() {loadedCaptchaJS = true; afterLoadedJS();});
    }
  }

  function destroyCaptcha(captchaForm) {
    captchaForm.find(".error_message").text("").hide();
    captchaForm.hide();
    Recaptcha.destroy();
  }

  function _validateCaptcha(successCallback, failureCallback) {
    var postData = {recaptcha_challenge_field: Recaptcha.get_challenge(), recaptcha_response_field: Recaptcha.get_response()};
    function handleResponse(result) {
      if (result.succeeded)
        successCallback();
      else
        failureCallback(result.errorCode);
    };
    $.post("/community/captchaValidation.do", postData, handleResponse, "json");
  }

  function _initWithCaptchaAsNeeded() {
    $('.initWithCaptcha').each(function() { fillCaptcha({parentForm: $(this)}); });
  }

  $(_initWithCaptchaAsNeeded);

/** File: community/contest.js */
function bombIt(bombAnchor, targetUserId, currentNumVotes) {
  var url = $(bombAnchor).attr("href");
  function doVote() {
    $.post(url, {targetUserId: targetUserId}, function(data) {
      var bombElt = $(bombAnchor).parents(".bomb");
      if (data.indexOf("fail") >= 0) {
        bombElt.find(".alreadyvotedmsg").text("Sorry, you have already voted on this image today. You can only vote on the same picture once per day.");
        showExploded(bombElt);
      } else if (data.indexOf("captcha") >= 0) {
        showCaptcha(bombElt.find(".captchabg"));
//        bombElt.find(".notexploded").hide();
        fillCaptcha({
          parentForm: bombElt.find(".captcha_form"),
          ajax: true,
          successCallback: doVote,
          setFocus: true});
      } else { // success
        voteSuccess(bombElt, targetUserId, currentNumVotes);
      }
    }, "text");
  }
  doVote();
}

function voteSuccess(bombElt, targetUserId, currentNumVotes) {
  var newNumVotes = currentNumVotes + 1;
  var newVoteText = newNumVotes + " vote" + (newNumVotes == 1 ? "" : "s");
  $(".contestentryvotes_" + targetUserId).text(newVoteText);
  showExploded(bombElt);
    closeCaptcha(bombElt.find(".captchabg"));
}

function showExploded(bombElt) {
    bombElt.find(".notexploded").css('display','none');
    bombElt.find(".exploded").css('display','block');
    bombElt.find("img.exploded").attr('style','_margin-left:50px;');
}

function postContestComment(form, toUserId) {
  var url = $(form).attr("action");
  var commentText = $("#commentText").val();
  $.post(url, {commentText: commentText}, function(){
    window.location.reload();
  }, "text");
}

function deleteContestComment(commentId, commentDivId) {
  deleteComment(commentId, function() {if (commentDivId) $('#' + commentDivId).hide();});
}

function showDetailsBtn(divRef) {
    /*if ((detailsBtnRef).parents('.eachGridProduct').children('productPopup').css('display') == 'none')
           detailsBtnRef = divRef.children('.seeDetails');    */
    detailsBtnRef = divRef.children('.seeDetails');
    if(detailsBtnRef.css('display' != 'none'))
        detailsBtnRef.fadeIn(100);

//    divRef.children('.seeDetails').fadeIn();
}


var openContestPopup = undefined;

function openContestPopup2(caller, refDiv) {
  if(openContestPopup != undefined && openContestPopup != null) {
        if(openContestPopup.parents('.eachEntry').attr('id') != refDiv.parents('.eachEntry').attr('id')) {
            openContestPopup.css("display",'none');
            hideContestDetailsBtn(openContestPopup.parents('.eachEntry'));
            refDiv.css('display','block');
            openContestPopup = refDiv;
        }
        else {
            if(openContestPopup.css('display') == 'block') {
                openContestPopup.css("display",'none');
                hideContestDetailsBtn(openContestPopup.parents('.eachEntry'));
            }
            else {
            refDiv.css('display','block');
            }
        }
    }
    else {
        refDiv.css('display','block');
        openContestPopup = refDiv;
    }

    var productGridRef = caller.parents('.eachEntry');
    var positionGridProduct = productGridRef.position();
    var positionGridWidth = productGridRef.width();
    var popupWidth = 170;

    var winWidth = $(window).width();
       refDiv.css("left",(positionGridProduct.left + positionGridWidth +"px" ));
    	refDiv.css("top",(positionGridProduct.top+30)+"px");
//    if(positionGridProduct.left + positionGridWidth + popupWidth < winWidth) {
//        refDiv.css("left",(positionGridProduct.left + positionGridWidth +"px" ));
//        refDiv.find('.leftArrow').css('display','block');
//    }
//    else {
//        refDiv.css("left",(positionGridProduct.left-popupWidth  )+"px");
//        refDiv.find('.rightArrow').css('display','block');
//    }


//	refDiv.css("top",(positionGridProduct.top-12)+"px");
}


function hideContestDetailsBtn(containerRef) {
    detailsBtnRef = containerRef.find('.seeDetails');
    if ((detailsBtnRef).parents('.eachEntry').children('.contestPopup').css('display') == 'none')
        detailsBtnRef.fadeOut(100);
}



function showCaptcha(ref) {
    var pageSizeCaptcha = getPageSize();
    var pageScrollCaptcha =   getPageScroll();

    var pageWidth1 = pageSizeCaptcha[0];
    var pageHeight1 = pageSizeCaptcha[1];
    var windowWidth1 = pageSizeCaptcha[2];
    var windowHeight1 = pageSizeCaptcha[3];
    var yScroll1 = pageScrollCaptcha[1];

    var bgImgHeight = 245;
    var bgImgWidth =  500;
//     var verticalPlacement = ($(window).height() / 2) - (bgImgHeight/2);
    var verticalPlacement = (windowHeight1)/2 - (bgImgHeight/2);
    verticalPlacement += yScroll1;
         var horizontalPlacement = ((windowWidth1) / 2 - bgImgWidth/2) ;
         if($.browser.mozilla)
            $("#lightbox_bg").css("width", "" + $(window).innerWidth() - 18 + "px");
         else
             $("#lightbox_bg").css("width", "" + $(window).innerWidth() + "px");

   $("#lightbox_bg").css("opacity","0.75");
   $("#lightbox_bg").css("height", "" +  pageHeight1 + "px");
//    $("#lightbox_bg").css("height", "100%");
    $("#lightbox_bg").css("display", "block");
   ref.css("top", ""+ verticalPlacement+ "px");
   ref.css("left", ""+ horizontalPlacement+ "px");
   ref.css("opacity","1");
   ref.css("display","block");
   if(typeof document.body.style.maxHeight == "undefined") {// IE6 or other older browser
             hideSelectBoxes();
   }

}


function closeCaptcha(ref) {
    $("#lightbox_bg").css("opacity","0");
    $("#lightbox_bg").css("display", "none");
    ref.css("display","none");
    showSelectBoxes();
}











function checkFieldContest(folder,field) {

            //var illegalPassChars = /\W/;
            var illegalPassChars = /\s/;
            var illegalNameChars = /[^a-zA-Z\s\'\-]/;
            var illegalChars = /[\(\)\<\>\,\;\:\\\/\"\[\]]/;
            var emailFilter = /^.+@.+\..+$/;
            var validZip = /(^\d{5}$)|(^\d{5}-\d{4}$)|(^[A-Za-z]\d[A-Za-z]\s\d[A-Za-z]\d$)|(^[A-Za-z]\d[A-Za-z]\d[A-Za-z]\d$)/;
            switch(field) {

                case 'firstname':
                     if(document.getElementById('firstname'))
                        var val = document.getElementById('firstname').value.trim();
                    else
                        return;
                    if(val == '') {
                        document.getElementById('check_firstname').style.background = 'url(' + folder + 'css2_5/images/holiday/worstFashion/cross.gif) top left no-repeat';
                        document.getElementById('error_firstname').innerHTML = 'First Name is required';
                    } else if(illegalNameChars.test(val)) {
                        document.getElementById('check_firstname').style.background = 'url(' + folder + 'css2_5/images/holiday/worstFashion/cross.gif) top left no-repeat';
                        document.getElementById('error_firstname').innerHTML = 'First Name has invalid characters';
                    } else {
                        document.getElementById('check_firstname').style.background = 'url(' + folder + 'css2_5/images/holiday/worstFashion/check.gif) top left no-repeat';
                        document.getElementById('error_firstname').innerHTML = '';
                        numerrors--;
                    }
                    break;
                case 'lastname':
                        if(document.getElementById('lastname'))
                            var val = document.getElementById('lastname').value.trim();
                        else
                            return;
                    if(val == '') {
                        document.getElementById('check_lastname').style.background = 'url(' + folder + 'css2_5/images/holiday/worstFashion/cross.gif) top left no-repeat';
                        document.getElementById('error_lastname').innerHTML = 'Last Name is required';
                    } else if(illegalNameChars.test(val)) {
                        document.getElementById('check_lastname').style.background = 'url(' + folder + 'css2_5/images/holiday/worstFashion/cross.gif) top left no-repeat';
                        document.getElementById('error_lastname').innerHTML = 'Last Name has invalid characters';
                    } else {
                        document.getElementById('check_lastname').style.background = 'url(' + folder + 'css2_5/images/holiday/worstFashion/check.gif) top left no-repeat';
                        document.getElementById('error_lastname').innerHTML = '';
                        numerrors--;
                    }
                    break;
                case 'email':
                        if(document.getElementById('email'))
                            var val = document.getElementById('email').value.trim();
                        else
                            return;
                    if(val == '') {
                        document.getElementById('check_email').style.background = 'url(' + folder + 'css2_5/images/holiday/worstFashion/cross.gif) top left no-repeat';
                        document.getElementById('error_email').innerHTML = 'Email Address is required';
                    } else if(!(emailFilter.test(val))) {
                        document.getElementById('check_email').style.background = 'url(' + folder + 'css2_5/images/holiday/worstFashion/cross.gif) top left no-repeat';
                        document.getElementById('error_email').innerHTML = 'Please enter a valid email address';
                    } else if(val.match(illegalChars)) {
                        document.getElementById('check_email').style.background = 'url(' + folder + 'css2_5/images/holiday/worstFashion/cross.gif) top left no-repeat';
                        document.getElementById('error_email').innerHTML = 'The email address contains illegal characters';
                    } else {
                        asyncFormErrorCheckContest('email', val,folder,'error_email','check_email')
                        document.getElementById('check_email').style.background = 'url(' + folder + 'css2_5/images/holiday/worstFashion/check.gif) top left no-repeat';
                        document.getElementById('error_email').innerHTML = '';
                        numerrors--;
                    }
                    break;
             case 'login_email':
                      if(document.getElementById('login_email'))
                            var val = document.getElementById('login_email').value.trim();
                        else
                            return;
                    if(val == '') {
                        document.getElementById('check_login_email').style.background = 'url(' + folder + 'css2_5/images/holiday/worstFashion/cross.gif) top left no-repeat';
                        document.getElementById('error_login_email').innerHTML = 'Email Address is required';
                    } else if(!(emailFilter.test(val))) {
                        document.getElementById('check_login_email').style.background = 'url(' + folder + 'css2_5/images/holiday/worstFashion/cross.gif) top left no-repeat';
                        document.getElementById('error_login_email').innerHTML = 'Please enter a valid email address';
                    } else if(val.match(illegalChars)) {
                        document.getElementById('check_login_email').style.background = 'url(' + folder + 'css2_5/images/holiday/worstFashion/cross.gif) top left no-repeat';
                        document.getElementById('error_login_email').innerHTML = 'The email address contains illegal characters';
                    } else {
                        asyncFormErrorCheckContest('login_email', val,folder,'error_login_email','check_login_email')
                        document.getElementById('check_login_email').style.background = 'url(' + folder + 'css2_5/images/holiday/worstFashion/check.gif) top left no-repeat';
                        document.getElementById('error_login_email').innerHTML = '';
                        numerrors--;
                    }
                    break;
                case 'pass':
                        if(document.getElementById('password'))
                            var val = document.getElementById('password').value.trim();
                        else
                            return;
                    if(val.length < 5) {
                        document.getElementById('check_pass').style.background = 'url(' + folder + 'css2_5/images/holiday/worstFashion/cross.gif) top left no-repeat';
                        document.getElementById('error_pass').innerHTML = 'Password must be at least 5 characters';
                    } else if(illegalPassChars.test(val)) {
                        document.getElementById('check_pass').style.background = 'url(' + folder + 'css2_5/images/holiday/worstFashion/cross.gif) top left no-repeat';
                        document.getElementById('error_pass').innerHTML = 'Password has invalid characters';
                    } else {
                        document.getElementById('check_pass').style.background = 'url(' + folder + 'css2_5/images/holiday/worstFashion/check.gif) top left no-repeat';
                        document.getElementById('error_pass').innerHTML = '';
                        numerrors--;
                    }
                    break;
                case 'pass2':
                    if(document.getElementById('password').value == document.getElementById('password2').value) {
                        document.getElementById('check_pass2').style.background = 'url(' + folder + 'css2_5/community/images/icon_ok.gif) top left no-repeat';
                        document.getElementById('error_pass2').innerHTML = '';
                        numerrors--;
                    } else {
                        document.getElementById('check_pass2').style.background = 'url(' + folder + 'css2_5/images/holiday/worstFashion/cross.gif) top left no-repeat';
                        document.getElementById('error_pass2').innerHTML = 'Passwords do not match';
                    }
                    break;
                case 'postalCode':
                    if(document.getElementById('postalCode'))
                        var val = document.getElementById('postalCode').value.trim();
                    else
                        return;
                    //if(!validZip.test(val)) {
                    //    document.getElementById('check_postalCode').style.background = 'url(' + folder + 'css2_5/community/images/icon_error.gif) top left no-repeat';
                    //    document.getElementById('error_postalCode').innerHTML = 'Invalid Zip Code';
                    //} else {
                        asyncFormErrorCheckContest('zipcode', val,folder,'error_postalCode','check_postalCode')
                        document.getElementById('check_postalCode').style.background = 'url(' + folder + 'css2_5/images/holiday/worstFashion/check.gif) top left no-repeat';
                        document.getElementById('error_postalCode').innerHTML = '';
                        numerrors++;
                    //}
                    break;
                case 'birthdayMonth':
                       var bdayMonth = $("#birthdayMonth").val();
                       if( bdayMonth >= 1 && bdayMonth <=12 || $.trim(bdayMonth) == '') {
                            document.getElementById('check_birthday').style.background = 'url(' + folder + 'css2_5/images/holiday/worstFashion/check.gif) top left no-repeat';
                            document.getElementById('error_birthdayMonth').innerHTML = '';
                            numerrors--;
                       }
                        else {
                            document.getElementById('check_birthday').style.background = 'url(' + folder + 'css2_5/images/holiday/worstFashion/cross.gif) top left no-repeat';
                            document.getElementById('error_birthdayMonth').innerHTML = 'Month must be an integer.';
                       }
                    break;

                case 'birthdayDay':
                           var bdayDay = $("#birthdayDay").val();
                           if( bdayDay >= 1 && bdayDay <=31 && bdayDay != '' || $.trim(bdayDay) == '') {
                                document.getElementById('check_birthday').style.background = 'url(' + folder + 'css2_5/images/holiday/worstFashion/check.gif) top left no-repeat';
                                document.getElementById('error_birthdayDay').innerHTML = '';
                                numerrors--;
                           }
                            else {
                                document.getElementById('check_birthday').style.background = 'url(' + folder + 'css2_5/images/holiday/worstFashion/cross.gif) top left no-repeat';
                                document.getElementById('error_birthdayDay').innerHTML = 'Day must be an integer.';
                           }
                        break;

                case 'birthdayYear':
                       var bdayYear = $("#birthdayYear").val();
                       if( bdayYear >= 0 && bdayYear <=99 && bdayYear != ''  || $.trim(bdayYear) == '') {
                            document.getElementById('check_birthday').style.background = 'url(' + folder + 'css2_5/images/holiday/worstFashion/check.gif) top left no-repeat';
                            document.getElementById('error_birthdayYear').innerHTML = '';
                            numerrors--;
                       }
                        else {
                            document.getElementById('check_birthday').style.background = 'url(' + folder + 'css2_5/images/holiday/worstFashion/cross.gif) top left no-repeat';
                            document.getElementById('error_birthdayYear').innerHTML = 'Year must be an integer.';
                       }
                    break;
                case 'birthday':
                       var bdayYear = $("#birthdayYear").val();
                       var bdayMonth = $("#birthdayMonth").val();
                       var bdayDay = $("#birthdayDay").val();
                                if((bdayYear >= 0 && bdayYear <=99 && bdayYear != ''  || $.trim(bdayYear) == '') && ( bdayDay >= 1 && bdayDay <=31 && bdayDay != '' || $.trim(bdayDay) == '') &&  ( bdayMonth >= 1 && bdayMonth <=12 || $.trim(bdayMonth) == '')){              document.getElementById('check_birthday').style.background = 'url(' + folder + 'css2_5/community/images/icon_ok.gif) top left no-repeat';
                                     document.getElementById('error_birthdayYear').innerHTML = '';
                                     numerrors--;
                                }
                                 else {
                                     document.getElementById('check_birthday').style.background = 'url(' + folder + 'css2_5/images/holiday/worstFashion/cross.gif) top left no-repeat';
                                     document.getElementById('error_birthdayMonth').innerHTML = 'Input must be an integer.';
                                }
                             break;


            case 'gender':
                            document.getElementById('check_gender').style.background = 'url(' + folder + 'css2_5/images/holiday/worstFashion/check.gif) top left no-repeat';
                    break;
            }
        }


function asyncFormErrorCheckContest(key, val,imgFolder,msgDiv,bgDiv) {

    var isValid;
   $.get("/community/async/isValid.do?key=" + key + "&value=" + val , function(xmlResponse) {
       if (document.implementation.createDocument){
         var domParser = new DOMParser();
        xml_doc = domParser.parseFromString(xmlResponse,"text/xml");
        }
       else if (window.ActiveXObject){
           xml_doc = new ActiveXObject("Microsoft.XMLDOM")
           xml_doc.async="false";
           xml_doc.loadXML(xmlResponse);
       }
        isValid = xml_doc.documentElement.getElementsByTagName('isValid')[0].firstChild.data;
        if(isValid == "false") {
            document.getElementById(bgDiv).style.background = 'url(' + imgFolder + 'css2_5/images/holiday/worstFashion/cross.gif) top left no-repeat';
           $('div#' + msgDiv).html(xml_doc.documentElement.getElementsByTagName('displayMessage')[0].firstChild.data);
            numerrors++;
        }
    });
}


/** File: community/comment.js */
function deleteComment(commentId, onSuccess) {
  $.post("/community/prot/deleteComment.do", {commentId: commentId}, onSuccess);
}


/** File: community/light_box.js */
// -----------------------------------------------------------------------------------
//
//  Pronto Lightbox Javascript
//  by Eric Hwang
//
// -----------------------------------------------------------------------------------
//  functions hideSelectBoxes, showSelectBoxes, getPageSize, getPageScroll from Lightbox v2.03
//   Lightbox v2.03
//   by Lokesh Dhakar - http://www.huddletogether.com
//   4/9/06
//
//   For more information on this script, visit:
//   http://huddletogether.com/projects/lightbox2/
//
//   Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
//   
//   Credit also due to those who have helped, inspired, and made their code available to the public.
//   Including: Scott Upton(uptonic.com), Peter-Paul Koch(quirksmode.org), Thomas Fuchs(mir.aculo.us), and others.
//
// -----------------------------------------------------------------------------------

var animInterval = 50; // amount of time between frames of animation in milliseconds
var baseTrans = 0; // opacity to fade out to
var currentObj = null; // current lightbox object being displayed
var loginTimeout = null;

// Look into re-using light box objects if they have the same dimenions (ie.
//  make 3 vars called smallLightBoxObj, mediumLightBoxObj, largeLightBoxObj.)
//  I think this would be possible but might mess up forwarding from one light box
//  to another. Not sure of the memory/performance implications of lots of light box vars either.
var bgFade = new lbObj('lightbox_bg', 'bgFade', '100%', '100%', 40, 40);
var registerObj = new lbObj('register', 'registerObj', 468, 513,  100, 100);
var loginObj = new lbObj('login', 'loginObj', 418, 245, 100, 100);
var forgotpasswordObj = new lbObj('forgotpassword', 'forgotpasswordObj', 418, 245, 100, 100);
var unconfirmeddisplayObj = new lbObj('unconfirmeddisplay', 'unconfirmeddisplayObj', 418, 245, 100, 100);
var forgotpasswordemailObj = new lbObj('forgotpasswordemail', 'forgotpasswordemailObj', 418, 245, 100, 100);
var friendrequestObj = new lbObj('friendrequest', 'friendrequestObj', 418, 245, 100, 100);
var friendrequestMsgObj = new lbObj('friendrequestMsg', 'friendrequestMsgObj', 418, 245, 100, 100);
var composemessageObj = new lbObj('composemessage', 'composemessageObj', 418, 245, 100, 100);
var confirmationObj = new lbObj('confirmation', 'confirmationObj', 418, 245, 100, 100);
var feedbackObj = new lbObj('feedback', 'feedbackObj', 418, 350, 100, 100);
var selectfromfriendsObj = new lbObj('selectfromfriends','selectfromfriendsObj',368,468,100,100);
var yourtipObj = new lbObj('yourtip','yourtipObj',418,268,100,100);

var discovertext1Obj = new lbObj('discovertext1', 'discovertext1Obj', 418, 115, 20, 100);
var discovertext2Obj = new lbObj('discovertext2', 'discovertext2Obj', 418, 115, 20, 100);
discovertext1Obj.opacity = 100;

var sharetext1Obj = new lbObj('sharetext1', 'sharetext1Obj', 418, 115, 20, 100);
var sharetext2Obj = new lbObj('sharetext2', 'sharetext2Obj', 418, 115, 20, 100);
sharetext1Obj.opacity = 100;

var comparetext1Obj = new lbObj('comparetext1', 'comparetext1Obj', 418, 115, 20, 100);
var comparetext2Obj = new lbObj('comparetext2', 'comparetext2Obj', 418, 115, 20, 100);
comparetext1Obj.opacity = 100;

// map all the lightbox object to the div ids so we can get the lightbox object using that id
var lbObjContainer = {
    Set : function(id, obj) {this[id] = obj;},
    Get : function(id, obj) {return this[id];}
}
lbObjContainer.Set('register', registerObj);
lbObjContainer.Set('login', loginObj);
lbObjContainer.Set('forgotpassword', forgotpasswordObj);
lbObjContainer.Set('unconfirmeddisplay', unconfirmeddisplayObj);
lbObjContainer.Set('forgotpasswordemail', forgotpasswordemailObj);
lbObjContainer.Set('friendrequest', friendrequestObj);
lbObjContainer.Set('friendrequestMsg', friendrequestMsgObj);
lbObjContainer.Set('composemessage', composemessageObj);
lbObjContainer.Set('confirmation', confirmationObj);
lbObjContainer.Set('feedback', feedbackObj);
lbObjContainer.Set('selectfromfriends', selectfromfriendsObj);
lbObjContainer.Set('yourtip', yourtipObj);
//-----------------------------------------------------------//

var mainDivId;

document.onkeypress = processKey;

// if user presses ESC key, hide light box
function processKey(e) {
    var key = (window.event) ? window.event.keyCode : e.keyCode;
     var esc = (window.event) ? 27 : e.DOM_VK_ESCAPE // MSIE : Firefox
    if(key == esc) {
        if(currentObj != null && currentObj.state == 'in' && currentObj.opacity == 100)
               lbHide();
        if(typeof(openDir) != "undefined")
            ptmPopDown();
    } else if(key == '13' && currentObj != null && currentObj.name == 'loginObj' && currentObj.opacity == 100) {
        $('#loginRCForm').submit()
    }
    else if(key == '13' && currentObj != null && currentObj.name == 'registerObj' && currentObj.opacity == 100) {
        $('#registerRCForm').submit()
    }else if(key == '13' && currentObj != null && currentObj.name == 'forgotpasswordemailObj' && currentObj.opacity == 100) {
        lbHide();
    }
} 

function hideSelectBoxes(){
     var selects = document.getElementsByTagName("select");
     for (i = 0; i != selects.length; i++) {
          selects[i].style.visibility = "hidden";
     }
}

function showSelectBoxes(){
     var selects = document.getElementsByTagName("select");
     for (i = 0; i != selects.length; i++) {
          selects[i].style.visibility = "visible";
     }
}

function getPageSize(){

     var xScroll, yScroll;

     if (window.innerHeight && window.scrollMaxY) {    
          xScroll = document.body.scrollWidth;
          yScroll = window.innerHeight + window.scrollMaxY;
     } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
          xScroll = document.body.scrollWidth;
          yScroll = document.body.scrollHeight;
     } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
          xScroll = document.body.offsetWidth;
          yScroll = document.body.offsetHeight;
     }

     var windowWidth, windowHeight;
     if (self.innerHeight) {  // all except Explorer
          windowWidth = self.innerWidth;
          windowHeight = self.innerHeight;
     } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
          windowWidth = document.documentElement.clientWidth;
          windowHeight = document.documentElement.clientHeight;
     } else if (document.body) { // other Explorers
          windowWidth = document.body.clientWidth;
          windowHeight = document.body.clientHeight;
     }    

     // for small pages with total height less then height of the viewport
     if(yScroll < windowHeight){
          pageHeight = windowHeight;
     } else { 
          pageHeight = yScroll;
     }

     // for small pages with total width less then width of the viewport
     if(xScroll < windowWidth){    
          pageWidth = windowWidth;
     } else {
          pageWidth = xScroll;
     }

     arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
     return arrayPageSize;
}    

function getPageScroll(){

     var yScroll;

     if (self.pageYOffset) {
          yScroll = self.pageYOffset;
     } else if (document.documentElement && document.documentElement.scrollTop){      // Explorer 6 Strict
          yScroll = document.documentElement.scrollTop;
     } else if (document.body) {// all other Explorers
          yScroll = document.body.scrollTop;
     }

     arrayPageScroll = new Array('',yScroll) 
     return arrayPageScroll;
}

// center lightObj's position in the browser window
function lbSetPosition(lightObj) {
     var obj = document.getElementById(lightObj.divid);
     var pageSize = getPageSize();
     var pageScroll = getPageScroll();       
     var boxLeft = (pageSize[0] - lightObj.width) / 2;
     var boxTop = (pageSize[3] - lightObj.height) / 2;
     if(boxTop < 0) boxTop = 0;
     boxTop += pageScroll[1];
     obj.style.left = boxLeft + 'px';
     obj.style.top = boxTop + 'px';
}

// set lightbox background to cover entire page
function lbSetBg() {
     var pageSize = getPageSize();
     var obj = document.getElementById(bgFade.divid);
     bgFade.state = 'in';
     obj.style.height = pageSize[1] + 'px';
     obj.style.display = 'block';
}

// fade lightObj1 out, and then fade lightObj2 in
function lbDoFadeOutIn(lightObj1, lightObj2) {
     lbDoFadeOut(lightObj1, 'lbDoFadeIn(' + lightObj2.name + ')');
}

// fade lightObj1 out while fading lightObj2 in
function lbDoCrossFade(lightObj1, lightObj2) {
     lbDoFadeOut(lightObj1);
     lbDoFadeIn(lightObj2);
}

// fade lightObj in, followed by command (optional) after it has been faded in
function lbDoFadeIn(lightObj, command) {
    var obj = document.getElementById(lightObj.divid);
     lightObj.state = 'in';
     if(lightObj.opacity + lightObj.delta <= lightObj.target) {
          lbSetPosition(lightObj);
          obj.style.display = 'block';
          if(command)
               lbFadeIn(lightObj, command);
          else
               lbFadeIn(lightObj);
     }
}

// fade lightObj out, followed by command (optional) after it has been faded out
function lbDoFadeOut(lightObj, command) {
    var obj = document.getElementById(lightObj.divid);
     lightObj.state = 'out';
     if(lightObj.opacity >= baseTrans + lightObj.delta) {
        if(lightObj.name == 'registerObj' || lightObj.name == 'loginObj' || lightObj.name == 'cpObj' || lightObj.name == 'forgotpasswordObj' || lightObj.name == 'forgotpasswordemailObj' || lightObj.name == 'composemessageObj' || lightObj.name == 'confirmationObj' || lightObj.name == 'unconfirmeddisplayObj' || lightObj.name == 'friendrequestObj' || lightObj.name == 'feedbackObj') {
            if(document.getElementById(lightObj.divid + 'bg') != null)
                document.getElementById(lightObj.divid + 'bg').style.filter = "none";
          }
          if(command)
               lbFadeOut(lightObj, command);
          else
               lbFadeOut(lightObj);
     }
}

// fade fobj in
function lbFadeIn(fobj, command) {
     if(fobj.state != "out") {
          var obj = document.getElementById(fobj.divid);
        currentObj = fobj;
          if(fobj.opacity + fobj.delta < fobj.target) {
               fobj.opacity += fobj.delta;
               obj.style.opacity = (fobj.opacity / 100); 
               obj.style.MozOpacity = (fobj.opacity / 100); 
               obj.style.KhtmlOpacity = (fobj.opacity / 100); 
               obj.style.filter = "alpha(opacity=" + fobj.opacity + ")";
               if(command)
                    setTimeout('lbFadeIn(' + fobj.name + ',\'' + command + '\') ', animInterval);
               else
                    setTimeout('lbFadeIn(' + fobj.name + ', null) ', animInterval);
          } else {
            fobj.opacity = fobj.target;
               obj.style.opacity = fobj.target / 100; 
               obj.style.MozOpacity = fobj.target / 100; 
               obj.style.KhtmlOpacity = fobj.target / 100; 
               obj.style.filter = "alpha(opacity=" + fobj.target + ")";
            if(fobj.target == 100 && (fobj.name == 'registerObj' || fobj.name == 'loginObj' || fobj.name == 'cpObj' || fobj.name == 'forgotpasswordObj' || fobj.name == 'forgotpasswordemailObj' || fobj.name == 'composemessageObj' || fobj.name == 'confirmationObj' || fobj.name == 'unconfirmeddisplayObj' || fobj.name == 'friendrequestObj' || fobj.name == 'feedbackObj' || fobj.name == 'selectfromfriendsObj') ) {
                obj.style.filter = "none";
                if(fobj.name == 'feedbackObj') {
                    document.getElementById(fobj.divid + 'bg').style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader (src='/css-local/main/css2_5/community/images/bg_whatsnew.png',sizingMethod='scale')";
                }
                else {
                    document.getElementById(fobj.divid + 'bg').style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader (src='/css-local/main/css2_5/community/images/bg_" + fobj.divid + ".png',sizingMethod='scale')";
                }
            } else if(fobj.target == 100 && fobj.name == 'friendrequestMsgObj' ) {
                obj.style.filter = "none";
                document.getElementById('friendrequestbg').style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader (src='/css-local/main/css2_5/community/images/bg_friendrequest.png',sizingMethod='scale')";
            }
            if(fobj.name == 'loginObj') {
                document.getElementById('login_email').focus();
            } else if(fobj.name == 'registerObj') {
                document.getElementById('firstname').focus();
            }  else if(fobj.name == 'forgotpasswordObj') {
                document.getElementById('login_email').focus();
            } else if(fobj.name == 'composemessageObj') {
				if('#message_comments_private')
					$('#message_comments_private').focus();
            } else if(fobj.name == 'yourtipObj') {
                document.getElementById('tipText').focus();
            } else if(fobj.name == 'confirmationObj') {
                setTimeout('lbHide()', 3000);
            }else if(fobj.name == 'friendrequestMsgObj') {
                setTimeout('lbHide()', 3000);
            }
            if(typeof(openDir) != "undefined")
                ptmPopDown('noshow');

            if(command) {
                    eval(command);
               }
          }
     }
}

// fade fobj out
function lbFadeOut(fobj, command) {
    if(fobj.state != "in") {
        var obj = document.getElementById(fobj.divid);
        if(obj != null) {
            if(fobj.opacity > baseTrans + fobj.delta) {
                fobj.opacity -= fobj.delta;
                obj.style.opacity = (fobj.opacity / 100);
                obj.style.MozOpacity = (fobj.opacity / 100);
                obj.style.KhtmlOpacity = (fobj.opacity / 100);
                obj.style.filter = "alpha(opacity=" + fobj.opacity + ")";
                if(command)
                    setTimeout('lbFadeOut(' + fobj.name + ',\'' + command + '\') ', animInterval);
                else
                    setTimeout('lbFadeOut(' + fobj.name + ', null) ', animInterval);
            } else {
                fobj.opacity = baseTrans;
                obj.style.opacity = (baseTrans / 100);
                obj.style.MozOpacity = (baseTrans / 100);
                obj.style.KhtmlOpacity = (baseTrans / 100);
                obj.style.filter = "alpha(opacity=" + baseTrans + ")";
                obj.style.display = 'none';
                if(command) {
                    eval(command);
                }
            }
        } else {
            fobj.opacity = 0;
        }
    }
}

// show lightbox with lightObj
function lbShow(lightObj) {
    if(typeof document.body.style.maxHeight == "undefined") // IE6 or other older browser, hide select boxes
          hideSelectBoxes();
     lbSetBg();
    lbFadeIn(bgFade, 'lbDoFadeIn(' + lightObj.name + ')');
}

// hide lightbox
function lbHide(lightObj) {
    if(typeof document.body.style.maxHeight == "undefined") // IE6 or other older browser, show hidden select boxes
          showSelectBoxes();
     if(lightObj)
          lbDoFadeOut(lightObj);
     else
          lbDoFadeOut(currentObj);
    lbDoFadeOut(bgFade);
}

/*
 *  Create a lightbox object
 *  id: ID of div containing lightbox
 *  name: name of the lbObj we are creating
 *  width: width of lightbox
 *  height: height of lightbox
 *  delta: adjusts how much to fade in each step
 *  target: opacity to fade to
 *  fadeIn(): fade the lbObj in
 *  fadeOut(): fade the lbObj out
 *  fadeOutIn(o): fade lbObj out, and then fade object o in
 *  crossFade(o): fade lbObj out while fading object o in
 */
function lbObj(id, name, width, height, delta, target) {
     this.divid = id;
     this.name = name;
     this.width = width;
     this.height = height;    
     this.delta = delta;
     this.opacity = 0;
     this.target = target;
     this.state = 'out';
     
     this.fadeIn = function () {
          lbDoFadeIn(this);
     }
     
     this.fadeOut = function () {
          lbDoFadeOut(this);
     }
     
     this.fadeOutIn = function (o) {
          lbDoFadeOutIn(this, o);
     }
     
     this.crossFade = function (o) {
          lbDoCrossFade(this, o);
     }
}

//function processFormRequireNotBlank(formName, path, notBlankInputId, parameterName1, parameterValue1,refreshDiv,view) {
//	if ( !$("#"+notBlankInputId).val() )
//		return false;
//	return processForm(formName, path, parameterName1, parameterValue1,refreshDiv,view);
//}

function processForm(formRef,parameterName1, parameterValue1,refreshDiv,view,listingsViewType,errorDiv) {
    var returnString = "";
        formElements=formRef.elements;
        path=$(formRef).attr('action');
        if(path.charAt(path.length-1) == '?') path = path.substr(0,path.length-1);
        var params = new Object();
        for(var i=formElements.length-1;i>=0; --i ){
            params[formElements[i].name] = formElements[i].value;
         }
        if(parameterName1 != undefined && parameterValue1 != undefined ) {
            params[parameterName1] = parameterValue1;
        }
        params['isLightbox'] = 'true';
    
         currObj =  lbObjContainer.Get($("div#lightboxContainer > div").attr("id"));
         if(currObj)
            currObj.fadeOut();

         // ehwang: commented this out because it was causing safari to crash if form submitted w/ keyboard for some strange reason
         //$('div#lightboxContainer').empty();
         $.post(path, params, function(data){
            $('div#lightboxContainer').html(data);
         //to handle the different return cases
             var loadedDivId;
             loadedDivId = $("div#lightboxContainer > div").attr("id");
             tempObj =  lbObjContainer.Get(loadedDivId);

             // if the div id is success then refresh the parent page and hide the light box
             if (loadedDivId == 'success') {
                 if(refreshDiv != null && refreshDiv.length > 0 && view != null & view.length > 0) {
                     if ($("div#" + refreshDiv).html()) {
                        $("div#" + refreshDiv).empty();
                        $("div#" + refreshDiv).load("/community/productAsynchDataRetrieval.do?prontoProductId=" +refreshDiv + "&view=" + view + "&listingsViewType=" + listingsViewType);
                     }
                     if ($("div#sl_" + refreshDiv).html()) {
                        $("div#sl_" + refreshDiv).empty();
                        $("div#sl_" + refreshDiv).load("/community/productAsynchDataRetrieval.do?prontoProductId=" +refreshDiv + "&view=" + view + "&listingsViewType=" + listingsViewType);
                     }

                    lbHide();
                 }
                 else {
                     reloadCurrentPage();
                 }
             }
             else if(loadedDivId == 'forward') {
                 window.location = $("div#forward").attr("url");
             }
             else {
                if(tempObj) {
                // if there is another lightbox object returned then show it
                    if (bgFade.state == 'out')
                        lbShow(tempObj);
                    else {
                        if(tempObj.opacity + tempObj.delta >= tempObj.target) tempObj.opacity = 0;
                        tempObj.fadeIn();
                    }
                }
                else {
                    //if the returned string starts with "msg:" then find a error div under in the form and display the
                    //message (message disappears after 10 seconds).
                    if(data.substring(0,4) == "msg:"){
                        var errDiv = $(formRef).find(".errorDiv");
                        if(errorDiv != null)
                            errDiv = errorDiv;    
                        errDiv.html(data.substring(4));
                        //errDiv.css("width", "350px");
//                        setTimeout(function(){
//                            errDiv.html("");
//                        },10000)

                    }
                    else{ // if there was no lightbox object returned then the page returned should be should be loaded
                        // this never really worked, so just reload the page instead
                        reloadCurrentPage();
        //            $('div#lightboxContainer').empty();
//                        document.write(data);
                    }
                }
             }
        });
    }

function reloadCurrentPage() {
    var link = "" + parent.location;
    var poundIndex = link.indexOf("#");
    if (poundIndex > 0)
        link = link.substring(0, link.indexOf("#"));
    window.location = link;
}

function processSynchronousGet(path, parameterName1, parameterValue1,noAction) {
    var returnString = "";
    if (parameterName1 != undefined && parameterValue1 != undefined) {
        if (formElements.length == 0) {
            returnString += "?"
        }
        else {
            returnString += "&"
        }
        returnString += escape(parameterName1) + "=" + escape(parameterValue1);
    }

   $.ajax({
        url: path+returnString,
        async: false
        });
}


function processGet(path, parameterName1, parameterValue1,noAction) {
    var returnString = "";
    if (parameterName1 != undefined && parameterValue1 != undefined) {
        if (formElements.length == 0) {
            returnString += "?"
        }
        else {
            returnString += "&"
        }
        returnString += escape(parameterName1) + "=" + escape(parameterValue1);
    }
    
    $.get(path + returnString, null, function() {
        if(!noAction) {
            window.location = parent.location
            lbHide();
            }
    });
}

function processGetForwardOnReturn(path, returnUrl) {
    $.get(path, null, function() {
        window.location = returnUrl;
    });
}

function openLightBox(link, lightboxObj,refreshDiv,view,listingsViewType) {
        oldObj =  lbObjContainer.Get($("div#lightboxContainer > div").attr("id"));
      $(document).ready(function() {
          if(oldObj != undefined) {
             oldObj.fadeOut()
              }
        $("div#lightboxContainer").empty();
        if(refreshDiv != null && view != null)
            link = link + "&refreshDiv=" + refreshDiv + "&view=" + view;
        if(listingsViewType != null)
            link = link + "&listingsViewType=" + listingsViewType;
        $('div#lightboxContainer').load(link,null, function() {
        lightboxObj = lbObjContainer.Get($("div#lightboxContainer > div").attr("id"));
            divid = $("div#lightboxContainer > div").attr("id");
          if ((oldObj == undefined) || bgFade.state == 'out') {
             lbShow(lightboxObj);
              }
          else {
            lightboxObj.fadeIn();
              }
         });
        });
}


function hoverOnEffect(obj) {
    id = $(obj).attr('id');
    $('#'+id).css('background-position', '0 -14px');
}

function hoverOffEffect(obj) {
     id = $(obj).attr('id');
    $('#'+id).css('background-position', '0 0');
}


function formatPathname(pathname) {
    if(pathname.charAt(0) != '/')
        pathname = '/' + pathname;
    return pathname
}

var checkAll = false;
function toggleCheckAll(checkList) {
    for (i = 0;i < checkList.length; i++) {
        checkList[i].checked = !checkAll;
    }
    checkAll = !checkAll;
}

function processLink(aLink, removeBlock, refreshPage){
    $.get(aLink.attr("href"), function(response){
        if(response == "success"){
            removeBlock.css("display","none");
        }
    });
    if(refreshPage){
        window.location.reload(true);
    }
    return false;
}

function ajaxifyLogout(caller){
	$.get(caller.attr('href'), function(){
        window.location='/welcome/index.do';
    } );
    return false;
}

/** File: community/light_box_element_utils.js */
	function clearField(obj, phrase) {
		if(obj.value == phrase) {
			obj.value = '';
			obj.style.color = '#333333';
		}
	}


    String.prototype.trim = function() {
            return (this.replace(/^\s+/, '')).replace(/\s+$/, '');
        }

    var numerrors = 9;
    var docheck = true;;
    function checkField(folder,field) {

            //var illegalPassChars = /\W/;
            var illegalPassChars = /\s/;
            var illegalNameChars = /[^a-zA-Z\s\'\-]/;
            var illegalChars = /[\(\)\<\>\,\;\:\\\/\"\[\]]/;
            var emailFilter = /^.+@.+\..+$/;
            var validZip = /(^\d{5}$)|(^\d{5}-\d{4}$)|(^[A-Za-z]\d[A-Za-z]\s\d[A-Za-z]\d$)|(^[A-Za-z]\d[A-Za-z]\d[A-Za-z]\d$)/;
            switch(field) {

                case 'firstname':
                     if(document.getElementById('firstname'))
                        var val = document.getElementById('firstname').value.trim();
                    else
                        return;
                    if(val == '') {
                        document.getElementById('check_firstname').style.background = 'url(' + folder + 'css2_5/community/images/icon_error.gif) top left no-repeat';
                        document.getElementById('error_firstname').innerHTML = 'First Name is required';
                    } else if(illegalNameChars.test(val)) {
                        document.getElementById('check_firstname').style.background = 'url(' + folder + 'css2_5/community/images/icon_error.gif) top left no-repeat';
                        document.getElementById('error_firstname').innerHTML = 'First Name has invalid characters';
                    } else {
                        document.getElementById('check_firstname').style.background = 'url(' + folder + 'css2_5/community/images/icon_ok.gif) top left no-repeat';
                        document.getElementById('error_firstname').innerHTML = '';
                        numerrors--;
                    }
                    break;
                case 'lastname':
                        if(document.getElementById('lastname'))
                            var val = document.getElementById('lastname').value.trim();
                        else
                            return;
                    if(val == '') {
                        document.getElementById('check_lastname').style.background = 'url(' + folder + 'css2_5/community/images/icon_error.gif) top left no-repeat';
                        document.getElementById('error_lastname').innerHTML = 'Last Name is required';
                    } else if(illegalNameChars.test(val)) {
                        document.getElementById('check_lastname').style.background = 'url(' + folder + 'css2_5/community/images/icon_error.gif) top left no-repeat';
                        document.getElementById('error_lastname').innerHTML = 'Last Name has invalid characters';
                    } else {
                        document.getElementById('check_lastname').style.background = 'url(' + folder + 'css2_5/community/images/icon_ok.gif) top left no-repeat';
                        document.getElementById('error_lastname').innerHTML = '';
                        numerrors--;
                    }
                    break;
                case 'email':
                        if(document.getElementById('email'))
                            var val = document.getElementById('email').value.trim();
                        else
                            return;
                    if(val == '') {
                        document.getElementById('check_email').style.background = 'url(' + folder + 'css2_5/community/images/icon_error.gif) top left no-repeat';
                        document.getElementById('error_email').innerHTML = 'Email Address is required';
                    } else if(!(emailFilter.test(val))) {
                        document.getElementById('check_email').style.background = 'url(' + folder + 'css2_5/community/images/icon_error.gif) top left no-repeat';
                        document.getElementById('error_email').innerHTML = 'Please enter a valid email address';
                    } else if(val.match(illegalChars)) {
                        document.getElementById('check_email').style.background = 'url(' + folder + 'css2_5/community/images/icon_error.gif) top left no-repeat';
                        document.getElementById('error_email').innerHTML = 'The email address contains illegal characters';
                    } else {
                        asyncFormErrorCheck('email', val,folder,'error_email','check_email')
                        document.getElementById('check_email').style.background = 'url(' + folder + 'css2_5/community/images/icon_ok.gif) top left no-repeat';
                        document.getElementById('error_email').innerHTML = '';
                        numerrors--;
                    }
                    break;
             case 'login_email':
                      if(document.getElementById('login_email'))
                            var val = document.getElementById('login_email').value.trim();
                        else
                            return;
                    if(val == '') {
                        document.getElementById('check_login_email').style.background = 'url(' + folder + 'css2_5/community/images/icon_error.gif) top left no-repeat';
                        document.getElementById('error_login_email').innerHTML = 'Email Address is required';
                    } else if(!(emailFilter.test(val))) {
                        document.getElementById('check_login_email').style.background = 'url(' + folder + 'css2_5/community/images/icon_error.gif) top left no-repeat';
                        document.getElementById('error_login_email').innerHTML = 'Please enter a valid email address';
                    } else if(val.match(illegalChars)) {
                        document.getElementById('check_login_email').style.background = 'url(' + folder + 'css2_5/community/images/icon_error.gif) top left no-repeat';
                        document.getElementById('error_login_email').innerHTML = 'The email address contains illegal characters';
                    } else {
                        asyncFormErrorCheck('login_email', val,folder,'error_login_email','check_login_email')
                        document.getElementById('check_login_email').style.background = 'url(' + folder + 'css2_5/community/images/icon_ok.gif) top left no-repeat';
                        document.getElementById('error_login_email').innerHTML = '';
                        numerrors--;
                    }
                    break;
                case 'pass':
                        if($('#loginform #password')){
							var val = $('#loginform #password').val().trim();
						}
                        else if(document.getElementById('password')){
                            var val = document.getElementById('password').value.trim();							
						}
                        else
                            return;
                    if(val.length < 5) {
                        document.getElementById('check_pass').style.background = 'url(' + folder + 'css2_5/community/images/icon_error.gif) top left no-repeat';
                        document.getElementById('error_pass').innerHTML = 'Password must be at least 5 characters';
                    } else if(illegalPassChars.test(val)) {
                        document.getElementById('check_pass').style.background = 'url(' + folder + 'css2_5/community/images/icon_error.gif) top left no-repeat';
                        document.getElementById('error_pass').innerHTML = 'Password has invalid characters';
                    } else {
						document.getElementById('check_pass').style.background = 'url(' + folder + 'css2_5/community/images/icon_ok.gif) top left no-repeat';
                        document.getElementById('error_pass').innerHTML = '';
                        numerrors--;
                    }
                    break;
                case 'pass2':
                    if(document.getElementById('password').value == document.getElementById('password2').value) {
                        document.getElementById('check_pass2').style.background = 'url(' + folder + 'css2_5/community/images/icon_ok.gif) top left no-repeat';
                        document.getElementById('error_pass2').innerHTML = '';
                        numerrors--;
                    } else {
                        document.getElementById('check_pass2').style.background = 'url(' + folder + 'css2_5/community/images/icon_error.gif) top left no-repeat';
                        document.getElementById('error_pass2').innerHTML = 'Passwords do not match';
                    }
                    break;
                case 'postalCode':
                    if(document.getElementById('postalCode'))
                        var val = document.getElementById('postalCode').value.trim();
                    else
                        return;
                    //if(!validZip.test(val)) {
                    //    document.getElementById('check_postalCode').style.background = 'url(' + folder + 'css2_5/community/images/icon_error.gif) top left no-repeat';
                    //    document.getElementById('error_postalCode').innerHTML = 'Invalid Zip Code';
                    //} else {
                        asyncFormErrorCheck('zipcode', val,folder,'error_postalCode','check_postalCode')
                        document.getElementById('check_postalCode').style.background = 'url(' + folder + 'css2_5/community/images/icon_ok.gif) top left no-repeat';
                        document.getElementById('error_postalCode').innerHTML = '';
                        numerrors++;
                    //}
                    break;
                case 'birthdayMonth':
                       var bdayMonth = $("#birthdayMonth").val();
                       if( bdayMonth >= 1 && bdayMonth <=12 || $.trim(bdayMonth) == '') {
                            document.getElementById('check_birthday').style.background = 'url(' + folder + 'css2_5/community/images/icon_ok.gif) top left no-repeat';
                            document.getElementById('error_birthdayMonth').innerHTML = '';
                            numerrors--;
                       }
                        else {
                            document.getElementById('check_birthday').style.background = 'url(' + folder + 'css2_5/community/images/icon_error.gif) top left no-repeat';
                            document.getElementById('error_birthdayMonth').innerHTML = 'Month must be an integer.';
                       }
                    break;

                case 'birthdayDay':
                           var bdayDay = $("#birthdayDay").val();
                           if( bdayDay >= 1 && bdayDay <=31 && bdayDay != '' || $.trim(bdayDay) == '') {
                                document.getElementById('check_birthday').style.background = 'url(' + folder + 'css2_5/community/images/icon_ok.gif) top left no-repeat';
                                document.getElementById('error_birthdayDay').innerHTML = '';
                                numerrors--;
                           }
                            else {
                                document.getElementById('check_birthday').style.background = 'url(' + folder + 'css2_5/community/images/icon_error.gif) top left no-repeat';
                                document.getElementById('error_birthdayDay').innerHTML = 'Day must be an integer.';
                           }
                        break;

                case 'birthdayYear':
                       var bdayYear = $("#birthdayYear").val();
                       if( bdayYear >= 0 && bdayYear <=99 && bdayYear != ''  || $.trim(bdayYear) == '') {
                            document.getElementById('check_birthday').style.background = 'url(' + folder + 'css2_5/community/images/icon_ok.gif) top left no-repeat';
                            document.getElementById('error_birthdayYear').innerHTML = '';
                            numerrors--;
                       }
                        else {
                            document.getElementById('check_birthday').style.background = 'url(' + folder + 'css2_5/community/images/icon_error.gif) top left no-repeat';
                            document.getElementById('error_birthdayYear').innerHTML = 'Year must be an integer.';
                       }
                    break;
                case 'birthday':
                       var bdayYear = $("#birthdayYear").val();
                       var bdayMonth = $("#birthdayMonth").val();
                       var bdayDay = $("#birthdayDay").val();
                                if((bdayYear >= 0 && bdayYear <=99 && bdayYear != ''  || $.trim(bdayYear) == '') && ( bdayDay >= 1 && bdayDay <=31 && bdayDay != '' || $.trim(bdayDay) == '') &&  ( bdayMonth >= 1 && bdayMonth <=12 || $.trim(bdayMonth) == '')){              document.getElementById('check_birthday').style.background = 'url(' + folder + 'css2_5/community/images/icon_ok.gif) top left no-repeat';
                                     document.getElementById('error_birthdayMonth').innerHTML = '';
                                     numerrors--;
                                }
                                 else {
                                     document.getElementById('check_birthday').style.background = 'url(' + folder + 'css2_5/community/images/icon_error.gif) top left no-repeat';
                                     document.getElementById('error_birthdayMonth').innerHTML = 'Input must be an integer.';
                                }
                             break;


            case 'gender':
                            document.getElementById('check_gender').style.background = 'url(' + folder + 'css2_5/community/images/icon_ok.gif) top left no-repeat';
                    break;
            }
        }

function clearBDate(ref) {
     if($(ref).val() == 'DD' || $(ref).val() == 'MM' || $(ref).val() == 'YY') {
        $("#birthdayDay").val('');
        $("#birthdayDay").css('color','#333');
        $("#birthdayMonth").val('');
        $("#birthdayMonth").css('color','#333');
        $("#birthdayYear").val('');
        $("#birthdayYear").css('color','#333');
   }
}
    
function asyncFormErrorCheck(key, val,imgFolder,msgDiv,bgDiv) {

    var isValid;
   $.get("/community/async/isValid.do?key=" + key + "&value=" + val , function(xmlResponse) {
       if (document.implementation.createDocument){
         var domParser = new DOMParser();
        xml_doc = domParser.parseFromString(xmlResponse,"text/xml");
        }
       else if (window.ActiveXObject){
           xml_doc = new ActiveXObject("Microsoft.XMLDOM")
           xml_doc.async="false";
           xml_doc.loadXML(xmlResponse);
       }
        isValid = xml_doc.documentElement.getElementsByTagName('isValid')[0].firstChild.data;
        if(isValid == "false") {
            document.getElementById(bgDiv).style.background = 'url(' + imgFolder + 'css2_5/community/images/icon_error.gif) top left no-repeat';
           $('div#' + msgDiv).html(xml_doc.documentElement.getElementsByTagName('displayMessage')[0].firstChild.data);
            numerrors++;
        }
    });
}
    
//Email check for marketing reg flow email address submit */
function clearInputDefaultValue(inputRef, defaultValue) {
    if(inputRef.val() == defaultValue) {
        inputRef.val('');
    }
}

        //      /*function init() {
	//	if(document.getElementById('hidden_brand').value == 'checked') {
	//		document.getElementById('check_brand').style.background = 'url(images/checkbox_checked.gif) top left no-repeat';
	//	}
	//	if(document.getElementById('hidden_store').value == 'checked') {
	//		document.getElementById('check_store').style.background = 'url(images/checkbox_checked.gif) top left no-repeat';
	//	}
	//	}*/


// ============================================================
// PUT THINGS HERE BECAUSE I DON'T KNOW WHERE ELSE TO PUT THEM?
function enableShopCatDropDown() {
	$('#siteNavShopCategories').click(function() {
		if ($('body').hasClass('shopCatDDOff')) {
			$('body').removeClass('shopCatDDOff').addClass('shopCatDDOn');
		}
		else if ($('body').hasClass('shopCatDDOn')) {
			$('body').removeClass('shopCatDDOn').addClass('shopCatDDOff');
		}
		else {
			$('body').addClass('shopCatDDOn');
		}
		return false;
	});
}
$(document).ready(function(){
	//  ADD AND REMOVE PROMPT TEXT AND CLASS TO FORM FIELDS
	var promptTextTitle = $('.js_promptText').attr("title");
	$('.js_promptText').val(promptTextTitle);
	$('.js_promptText').focus(function() {
		if($('.js_promptText').val() == promptTextTitle) {
			$('.js_promptText').val("");
		}
		if($('js_promptText').attr('class', 'promptText'))
			$('.js_promptText').removeClass('promptText');
	});
});

/** File: tracking/voltage.js */
function voltageRevenueEvent(ttp,tid,cnt,val) {
	prot='';
	if (window.location.protocol) prot=window.location.protocol;
	if (prot=='') prot='https:'
	ran=Math.round(Math.random()*100000000);
    if (tid=='0' && ttp=='asl_lead') {
        log=prot +'//tracking.voltagesearch.com/image.gif?aid=210'+'&ttp='+ escape(ttp) +'&cnt='+ escape(cnt) +'&val='+ escape(val) +'&sRng='+ ran;
    }
    else {
        log=prot +'//tracking.voltagesearch.com/image.gif?aid=210&tid='+ escape(tid) +'&ttp='+ escape(ttp) +'&cnt='+ escape(cnt) +'&val='+ escape(val) +'&sRng='+ ran;
    }

	var v = document.getElementById('voltage_revenue_pixel');
    if (typeof(v) != "undefined")
    {
		v.src = log;
    }
}



/** File: pronto3/common/ga.js */
var _gat=new Object({c:"length",lb:"4.3.1",m:"cookie",b:undefined,cb:function(d,a){this.zb=d;this.Nb=a},r:"__utma=",W:"__utmb=",ma:"__utmc=",Ta:"__utmk=",na:"__utmv=",oa:"__utmx=",Sa:"GASO=",X:"__utmz=",lc:"http://www.google-analytics.com/__utm.gif",mc:"https://ssl.google-analytics.com/__utm.gif",Wa:"utmcid=",Ya:"utmcsr=",$a:"utmgclid=",Ua:"utmccn=",Xa:"utmcmd=",Za:"utmctr=",Va:"utmcct=",Hb:false,_gasoDomain:undefined,_gasoCPath:undefined,e:window,a:document,k:navigator,t:function(d){var a=1,c=0,h,
o;if(!_gat.q(d)){a=0;for(h=d[_gat.c]-1;h>=0;h--){o=d.charCodeAt(h);a=(a<<6&268435455)+o+(o<<14);c=a&266338304;a=c!=0?a^c>>21:a}}return a},C:function(d,a,c){var h=_gat,o="-",k,l,s=h.q;if(!s(d)&&!s(a)&&!s(c)){k=h.w(d,a);if(k>-1){l=d.indexOf(c,k);if(l<0)l=d[h.c];o=h.F(d,k+h.w(a,"=")+1,l)}}return o},Ea:function(d){var a=false,c=0,h,o;if(!_gat.q(d)){a=true;for(h=0;h<d[_gat.c];h++){o=d.charAt(h);c+="."==o?1:0;a=a&&c<=1&&(0==h&&"-"==o||_gat.P(".0123456789",o))}}return a},d:function(d,a){var c=encodeURIComponent;
return c instanceof Function?(a?encodeURI(d):c(d)):escape(d)},J:function(d,a){var c=decodeURIComponent,h;d=d.split("+").join(" ");if(c instanceof Function)try{h=a?decodeURI(d):c(d)}catch(o){h=unescape(d)}else h=unescape(d);return h},Db:function(d){return d&&d.hash?_gat.F(d.href,_gat.w(d.href,"#")):""},q:function(d){return _gat.b==d||"-"==d||""==d},Lb:function(d){return d[_gat.c]>0&&_gat.P(" \n\r\t",d)},P:function(d,a){return _gat.w(d,a)>-1},h:function(d,a){d[d[_gat.c]]=a},T:function(d){return d.toLowerCase()},
z:function(d,a){return d.split(a)},w:function(d,a){return d.indexOf(a)},F:function(d,a,c){c=_gat.b==c?d[_gat.c]:c;return d.substring(a,c)},uc:function(){var d=_gat.b,a=window;if(a&&a.gaGlobal&&a.gaGlobal.hid)d=a.gaGlobal.hid;else{d=Math.round(Math.random()*2147483647);a.gaGlobal=a.gaGlobal?a.gaGlobal:{};a.gaGlobal.hid=d}return d},wa:function(){return Math.round(Math.random()*2147483647)},Gc:function(){return(_gat.wa()^_gat.vc())*2147483647},vc:function(){var d=_gat.k,a=_gat.a,c=_gat.e,h=a[_gat.m]?
a[_gat.m]:"",o=c.history[_gat.c],k,l,s=[d.appName,d.version,d.language?d.language:d.browserLanguage,d.platform,d.userAgent,d.javaEnabled()?1:0].join("");if(c.screen)s+=c.screen.width+"x"+c.screen.height+c.screen.colorDepth;else if(c.java){l=java.awt.Toolkit.getDefaultToolkit().getScreenSize();s+=l.screen.width+"x"+l.screen.height}s+=h;s+=a.referrer?a.referrer:"";k=s[_gat.c];while(o>0)s+=o--^k++;return _gat.t(s)}});_gat.hc=function(){var d=this,a=_gat.cb;function c(h,o){return new a(h,o)}d.db="utm_campaign";d.eb="utm_content";d.fb="utm_id";d.gb="utm_medium";d.hb="utm_nooverride";d.ib="utm_source";d.jb="utm_term";d.kb="gclid";d.pa=0;d.I=0;d.wb="15768000";d.Tb="1800";d.ea=[];d.ga=[];d.Ic="cse";d.Gb="q";d.ab="google";d.fa=[c(d.ab,d.Gb),c("yahoo","p"),c("msn","q"),c("bing","q"),c("aol","query"),c("aol","encquery"),c("lycos","query"),c("ask","q"),c("altavista","q"),c("netscape","query"),c("cnn","query"),c("looksmart","qt"),c("about",
"terms"),c("mamma","query"),c("alltheweb","q"),c("gigablast","q"),c("voila","rdata"),c("virgilio","qs"),c("live","q"),c("baidu","wd"),c("alice","qs"),c("yandex","text"),c("najdi","q"),c("aol","q"),c("club-internet","query"),c("mama","query"),c("seznam","q"),c("search","q"),c("wp","szukaj"),c("onet","qt"),c("netsprint","q"),c("google.interia","q"),c("szukacz","q"),c("yam","k"),c("pchome","q"),c("kvasir","searchExpr"),c("sesam","q"),c("ozu","q"),c("terra","query"),c("nostrum","query"),c("mynet","q"),
c("ekolay","q"),c("search.ilse","search_for")];d.B=undefined;d.Kb=false;d.p="/";d.ha=100;d.Da="/__utm.gif";d.ta=1;d.ua=1;d.G="|";d.sa=1;d.qa=1;d.pb=1;d.g="auto";d.D=1;d.Ga=1000;d.Yc=10;d.nc=10;d.Zc=0.2};_gat.Y=function(d,a){var c,h,o,k,l,s,q,f=this,n=_gat,w=n.q,x=n.c,g,z=a;f.a=d;function B(i){var b=i instanceof Array?i.join("."):"";return w(b)?"-":b}function A(i,b){var e=[],j;if(!w(i)){e=n.z(i,".");if(b)for(j=0;j<e[x];j++)if(!n.Ea(e[j]))e[j]="-"}return e}function p(){return u(63072000000)}function u(i){var b=new Date,e=new Date(b.getTime()+i);return"expires="+e.toGMTString()+"; "}function m(i,b){f.a[n.m]=i+"; path="+z.p+"; "+b+f.Cc()}function r(i,b,e){var j=f.V,t,v;for(t=0;t<j[x];t++){v=j[t][0];
v+=w(b)?b:b+j[t][4];j[t][2](n.C(i,v,e))}}f.Jb=function(){return n.b==g||g==f.t()};f.Ba=function(){return l?l:"-"};f.Wb=function(i){l=i};f.Ma=function(i){g=n.Ea(i)?i*1:"-"};f.Aa=function(){return B(s)};f.Na=function(i){s=A(i)};f.Hc=function(){return g?g:"-"};f.Cc=function(){return w(z.g)?"":"domain="+z.g+";"};f.ya=function(){return B(c)};f.Ub=function(i){c=A(i,1)};f.K=function(){return B(h)};f.La=function(i){h=A(i,1)};f.za=function(){return B(o)};f.Vb=function(i){o=A(i,1)};f.Ca=function(){return B(k)};
f.Xb=function(i){k=A(i);for(var b=0;b<k[x];b++)if(b<4&&!n.Ea(k[b]))k[b]="-"};f.Dc=function(){return q};f.Uc=function(i){q=i};f.pc=function(){c=[];h=[];o=[];k=[];l=n.b;s=[];g=n.b};f.t=function(){var i="",b;for(b=0;b<f.V[x];b++)i+=f.V[b][1]();return n.t(i)};f.Ha=function(i){var b=f.a[n.m],e=false;if(b){r(b,i,";");f.Ma(f.t());e=true}return e};f.Rc=function(i){r(i,"","&");f.Ma(n.C(i,n.Ta,"&"))};f.Wc=function(){var i=f.V,b=[],e;for(e=0;e<i[x];e++)n.h(b,i[e][0]+i[e][1]());n.h(b,n.Ta+f.t());return b.join("&")};
f.bd=function(i,b){var e=f.V,j=z.p,t;f.Ha(i);z.p=b;for(t=0;t<e[x];t++)if(!w(e[t][1]()))e[t][3]();z.p=j};f.dc=function(){m(n.r+f.ya(),p())};f.Pa=function(){m(n.W+f.K(),u(z.Tb*1000))};f.ec=function(){m(n.ma+f.za(),"")};f.Ra=function(){m(n.X+f.Ca(),u(z.wb*1000))};f.fc=function(){m(n.oa+f.Ba(),p())};f.Qa=function(){m(n.na+f.Aa(),p())};f.cd=function(){m(n.Sa+f.Dc(),"")};f.V=[[n.r,f.ya,f.Ub,f.dc,"."],[n.W,f.K,f.La,f.Pa,""],[n.ma,f.za,f.Vb,f.ec,""],[n.oa,f.Ba,f.Wb,f.fc,""],[n.X,f.Ca,f.Xb,f.Ra,"."],[n.na,
f.Aa,f.Na,f.Qa,"."]]};_gat.jc=function(d){var a=this,c=_gat,h=d,o,k=function(l){var s=(new Date).getTime(),q;q=(s-l[3])*(h.Zc/1000);if(q>=1){l[2]=Math.min(Math.floor(l[2]*1+q),h.nc);l[3]=s}return l};a.O=function(l,s,q,f,n,w,x){var g,z=h.D,B=q.location;if(!o)o=new c.Y(q,h);o.Ha(f);g=c.z(o.K(),".");if(g[1]<500||n){if(w)g=k(g);if(n||!w||g[2]>=1){if(!n&&w)g[2]=g[2]*1-1;g[1]=g[1]*1+1;l="?utmwv="+_gat.lb+"&utmn="+c.wa()+(c.q(B.hostname)?"":"&utmhn="+c.d(B.hostname))+(h.ha==100?"":"&utmsp="+c.d(h.ha))+l;if(0==z||2==z){var A=
new Image(1,1);A.src=h.Da+l;var p=2==z?function(){}:x||function(){};A.onload=p}if(1==z||2==z){var u=new Image(1,1);u.src=("https:"==B.protocol?c.mc:c.lc)+l+"&utmac="+s+"&utmcc="+a.wc(q,f);u.onload=x||function(){}}}}o.La(g.join("."));o.Pa()};a.wc=function(l,s){var q=[],f=[c.r,c.X,c.na,c.oa],n,w=l[c.m],x;for(n=0;n<f[c.c];n++){x=c.C(w,f[n]+s,";");if(!c.q(x))c.h(q,f[n]+x+";")}return c.d(q.join("+"))}};_gat.i=function(){this.la=[]};_gat.i.bb=function(d,a,c,h,o,k){var l=this;l.cc=d;l.Oa=a;l.L=c;l.sb=h;l.Pb=o;l.Qb=k};_gat.i.bb.prototype.S=function(){var d=this,a=_gat.d;return"&"+["utmt=item","utmtid="+a(d.cc),"utmipc="+a(d.Oa),"utmipn="+a(d.L),"utmiva="+a(d.sb),"utmipr="+a(d.Pb),"utmiqt="+a(d.Qb)].join("&")};_gat.i.$=function(d,a,c,h,o,k,l,s){var q=this;q.v=d;q.ob=a;q.bc=c;q.ac=h;q.Yb=o;q.ub=k;q.$b=l;q.xb=s;q.ca=[]};_gat.i.$.prototype.mb=function(d,a,c,h,o){var k=this,l=k.Eb(d),s=k.v,q=_gat;if(q.b==
l)q.h(k.ca,new q.i.bb(s,d,a,c,h,o));else{l.cc=s;l.Oa=d;l.L=a;l.sb=c;l.Pb=h;l.Qb=o}};_gat.i.$.prototype.Eb=function(d){var a,c=this.ca,h;for(h=0;h<c[_gat.c];h++)a=d==c[h].Oa?c[h]:a;return a};_gat.i.$.prototype.S=function(){var d=this,a=_gat.d;return"&"+["utmt=tran","utmtid="+a(d.v),"utmtst="+a(d.ob),"utmtto="+a(d.bc),"utmttx="+a(d.ac),"utmtsp="+a(d.Yb),"utmtci="+a(d.ub),"utmtrg="+a(d.$b),"utmtco="+a(d.xb)].join("&")};_gat.i.prototype.nb=function(d,a,c,h,o,k,l,s){var q=this,f=_gat,n=q.xa(d);if(f.b==
n){n=new f.i.$(d,a,c,h,o,k,l,s);f.h(q.la,n)}else{n.ob=a;n.bc=c;n.ac=h;n.Yb=o;n.ub=k;n.$b=l;n.xb=s}return n};_gat.i.prototype.xa=function(d){var a,c=this.la,h;for(h=0;h<c[_gat.c];h++)a=d==c[h].v?c[h]:a;return a};_gat.gc=function(d){var a=this,c="-",h=_gat,o=d;a.Ja=screen;a.qb=!self.screen&&self.java?java.awt.Toolkit.getDefaultToolkit():h.b;a.a=document;a.e=window;a.k=navigator;a.Ka=c;a.Sb=c;a.tb=c;a.Ob=c;a.Mb=1;a.Bb=c;function k(){var l,s,q,f,n="ShockwaveFlash",w="$version",x=a.k?a.k.plugins:h.b;if(x&&x[h.c]>0)for(l=0;l<x[h.c]&&!q;l++){s=x[l];if(h.P(s.name,"Shockwave Flash"))q=h.z(s.description,"Shockwave Flash ")[1]}else{n=n+"."+n;try{f=new ActiveXObject(n+".7");q=f.GetVariable(w)}catch(g){}if(!q)try{f=
new ActiveXObject(n+".6");q="WIN 6,0,21,0";f.AllowScriptAccess="always";q=f.GetVariable(w)}catch(z){}if(!q)try{f=new ActiveXObject(n);q=f.GetVariable(w)}catch(z){}if(q){q=h.z(h.z(q," ")[1],",");q=q[0]+"."+q[1]+" r"+q[2]}}return q?q:c}a.xc=function(){var l;if(self.screen){a.Ka=a.Ja.width+"x"+a.Ja.height;a.Sb=a.Ja.colorDepth+"-bit"}else if(a.qb)try{l=a.qb.getScreenSize();a.Ka=l.width+"x"+l.height}catch(s){}a.Ob=h.T(a.k&&a.k.language?a.k.language:(a.k&&a.k.browserLanguage?a.k.browserLanguage:c));a.Mb=
a.k&&a.k.javaEnabled()?1:0;a.Bb=o?k():c;a.tb=h.d(a.a.characterSet?a.a.characterSet:(a.a.charset?a.a.charset:c))};a.Xc=function(){return"&"+["utmcs="+h.d(a.tb),"utmsr="+a.Ka,"utmsc="+a.Sb,"utmul="+a.Ob,"utmje="+a.Mb,"utmfl="+h.d(a.Bb)].join("&")}};_gat.n=function(d,a,c,h,o){var k=this,l=_gat,s=l.q,q=l.b,f=l.P,n=l.C,w=l.T,x=l.z,g=l.c;k.a=a;k.f=d;k.Rb=c;k.ja=h;k.o=o;function z(p){return s(p)||"0"==p||!f(p,"://")}function B(p){var u="";p=w(x(p,"://")[1]);if(f(p,"/")){p=x(p,"/")[1];if(f(p,"?"))u=x(p,"?")[0]}return u}function A(p){var u="";u=w(x(p,"://")[1]);if(f(u,"/"))u=x(u,"/")[0];return u}k.Fc=function(p){var u=k.Fb(),m=k.o;return new l.n.s(n(p,m.fb+"=","&"),n(p,m.ib+"=","&"),n(p,m.kb+"=","&"),k.ba(p,m.db,"(not set)"),k.ba(p,m.gb,"(not set)"),
k.ba(p,m.jb,u&&!s(u.R)?l.J(u.R):q),k.ba(p,m.eb,q))};k.Ib=function(p){var u=A(p),m=B(p);if(f(u,k.o.ab)){p=x(p,"?").join("&");if(f(p,"&"+k.o.Gb+"="))if(m==k.o.Ic)return true}return false};k.Fb=function(){var p,u,m=k.Rb,r,i,b=k.o.fa;if(z(m)||k.Ib(m))return;p=A(m);for(r=0;r<b[g];r++){i=b[r];if(f(p,w(i.zb))){m=x(m,"?").join("&");if(f(m,"&"+i.Nb+"=")){u=x(m,"&"+i.Nb+"=")[1];if(f(u,"&"))u=x(u,"&")[0];return new l.n.s(q,i.zb,q,"(organic)","organic",u,q)}}}};k.ba=function(p,u,m){var r=n(p,u+"=","&"),i=!s(r)?
l.J(r):(!s(m)?m:"-");return i};k.Nc=function(p){var u=k.o.ea,m=false,r,i;if(p&&"organic"==p.da){r=w(l.J(p.R));for(i=0;i<u[g];i++)m=m||w(u[i])==r}return m};k.Ec=function(){var p="",u="",m=k.Rb;if(z(m)||k.Ib(m))return;p=w(x(m,"://")[1]);if(f(p,"/")){u=l.F(p,l.w(p,"/"));if(f(u,"?"))u=x(u,"?")[0];p=x(p,"/")[0]}if(0==l.w(p,"www."))p=l.F(p,4);return new l.n.s(q,p,q,"(referral)","referral",q,u)};k.sc=function(p){var u="";if(k.o.pa){u=l.Db(p);u=""!=u?u+"&":u}u+=p.search;return u};k.zc=function(){return new l.n.s(q,
"(direct)",q,"(direct)","(none)",q,q)};k.Oc=function(p){var u=false,m,r,i=k.o.ga;if(p&&"referral"==p.da){m=w(l.d(p.ia));for(r=0;r<i[g];r++)u=u||f(m,w(i[r]))}return u};k.U=function(p){return q!=p&&p.Fa()};k.yc=function(p,u){var m="",r="-",i,b,e=0,j,t,v=k.f;if(!p)return"";t=k.a[l.m]?k.a[l.m]:"";m=k.sc(k.a.location);if(k.o.I&&p.Jb()){r=p.Ca();if(!s(r)&&!f(r,";")){p.Ra();return""}}r=n(t,l.X+v+".",";");i=k.Fc(m);if(k.U(i)){b=n(m,k.o.hb+"=","&");if("1"==b&&!s(r))return""}if(!k.U(i)){i=k.Fb();if(!s(r)&&
k.Nc(i))return""}if(!k.U(i)&&u){i=k.Ec();if(!s(r)&&k.Oc(i))return""}if(!k.U(i))if(s(r)&&u)i=k.zc();if(!k.U(i))return"";if(!s(r)){var y=x(r,"."),E=new l.n.s;E.Cb(y.slice(4).join("."));j=w(E.ka())==w(i.ka());e=y[3]*1}if(!j||u){var F=n(t,l.r+v+".",";"),I=F.lastIndexOf("."),G=I>9?l.F(F,I+1)*1:0;e++;G=0==G?1:G;p.Xb([v,k.ja,G,e,i.ka()].join("."));p.Ra();return"&utmcn=1"}else return"&utmcr=1"}};_gat.n.s=function(d,a,c,h,o,k,l){var s=this;s.v=d;s.ia=a;s.ra=c;s.L=h;s.da=o;s.R=k;s.vb=l};_gat.n.s.prototype.ka=
function(){var d=this,a=_gat,c=[],h=[[a.Wa,d.v],[a.Ya,d.ia],[a.$a,d.ra],[a.Ua,d.L],[a.Xa,d.da],[a.Za,d.R],[a.Va,d.vb]],o,k;if(d.Fa())for(o=0;o<h[a.c];o++)if(!a.q(h[o][1])){k=h[o][1].split("+").join("%20");k=k.split(" ").join("%20");a.h(c,h[o][0]+k)}return c.join("|")};_gat.n.s.prototype.Fa=function(){var d=this,a=_gat.q;return!(a(d.v)&&a(d.ia)&&a(d.ra))};_gat.n.s.prototype.Cb=function(d){var a=this,c=_gat,h=function(o){return c.J(c.C(d,o,"|"))};a.v=h(c.Wa);a.ia=h(c.Ya);a.ra=h(c.$a);a.L=h(c.Ua);a.da=
h(c.Xa);a.R=h(c.Za);a.vb=h(c.Va)};_gat.Z=function(){var d=this,a=_gat,c={},h="k",o="v",k=[h,o],l="(",s=")",q="*",f="!",n="'",w={};w[n]="'0";w[s]="'1";w[q]="'2";w[f]="'3";var x=1;function g(m,r,i,b){if(a.b==c[m])c[m]={};if(a.b==c[m][r])c[m][r]=[];c[m][r][i]=b}function z(m,r,i){return a.b!=c[m]&&a.b!=c[m][r]?c[m][r][i]:a.b}function B(m,r){if(a.b!=c[m]&&a.b!=c[m][r]){c[m][r]=a.b;var i=true,b;for(b=0;b<k[a.c];b++)if(a.b!=c[m][k[b]]){i=false;break}if(i)c[m]=a.b}}function A(m){var r="",i=false,b,e;for(b=0;b<k[a.c];b++){e=m[k[b]];if(a.b!=
e){if(i)r+=k[b];r+=p(e);i=false}else i=true}return r}function p(m){var r=[],i,b;for(b=0;b<m[a.c];b++)if(a.b!=m[b]){i="";if(b!=x&&a.b==m[b-1]){i+=b.toString();i+=f}i+=u(m[b]);a.h(r,i)}return l+r.join(q)+s}function u(m){var r="",i,b,e;for(i=0;i<m[a.c];i++){b=m.charAt(i);e=w[b];r+=a.b!=e?e:b}return r}d.Kc=function(m){return a.b!=c[m]};d.N=function(){var m=[],r;for(r in c)if(a.b!=c[r])a.h(m,r.toString()+A(c[r]));return m.join("")};d.Sc=function(m){if(m==a.b)return d.N();var r=[m.N()],i;for(i in c)if(a.b!=
c[i]&&!m.Kc(i))a.h(r,i.toString()+A(c[i]));return r.join("")};d._setKey=function(m,r,i){if(typeof i!="string")return false;g(m,h,r,i);return true};d._setValue=function(m,r,i){if(typeof i!="number"&&(a.b==Number||!(i instanceof Number)))return false;if(Math.round(i)!=i||i==NaN||i==Infinity)return false;g(m,o,r,i.toString());return true};d._getKey=function(m,r){return z(m,h,r)};d._getValue=function(m,r){return z(m,o,r)};d._clearKey=function(m){B(m,h)};d._clearValue=function(m){B(m,o)}};_gat.ic=function(d,a){var c=this;c.jd=a;c.Pc=d;c._trackEvent=function(h,o,k){return a._trackEvent(c.Pc,h,o,k)}};_gat.kc=function(d){var a=this,c=_gat,h=c.b,o=c.q,k=c.w,l=c.F,s=c.C,q=c.P,f=c.z,n="location",w=c.c,x=h,g=new c.hc,z=false;a.a=document;a.e=window;a.ja=Math.round((new Date).getTime()/1000);a.H=d;a.yb=a.a.referrer;a.va=h;a.j=h;a.A=h;a.M=false;a.aa=h;a.rb="";a.l=h;a.Ab=h;a.f=h;a.u=h;function B(){if("auto"==g.g){var b=a.a.domain;if("www."==l(b,0,4))b=l(b,4);g.g=b}g.g=c.T(g.g)}function A(){var b=g.g,e=k(b,"www.google.")*k(b,".google.")*k(b,"google.");return e||"/"!=g.p||k(b,"google.org")>-1}function p(b,
e,j){if(o(b)||o(e)||o(j))return"-";var t=s(b,c.r+a.f+".",e),v;if(!o(t)){v=f(t,".");v[5]=v[5]?v[5]*1+1:1;v[3]=v[4];v[4]=j;t=v.join(".")}return t}function u(){return"file:"!=a.a[n].protocol&&A()}function m(b){if(!b||""==b)return"";while(c.Lb(b.charAt(0)))b=l(b,1);while(c.Lb(b.charAt(b[w]-1)))b=l(b,0,b[w]-1);return b}function r(b,e,j){if(!o(b())){e(c.J(b()));if(!q(b(),";"))j()}}function i(b){var e,j=""!=b&&a.a[n].host!=b;if(j)for(e=0;e<g.B[w];e++)j=j&&k(c.T(b),c.T(g.B[e]))==-1;return j}a.Bc=function(){if(!g.g||
""==g.g||"none"==g.g){g.g="";return 1}B();return g.pb?c.t(g.g):1};a.tc=function(b,e){if(o(b))b="-";else{e+=g.p&&"/"!=g.p?g.p:"";var j=k(b,e);b=j>=0&&j<=8?"0":("["==b.charAt(0)&&"]"==b.charAt(b[w]-1)?"-":b)}return b};a.Ia=function(b){var e="",j=a.a;e+=a.aa?a.aa.Xc():"";e+=g.qa?a.rb:"";e+=g.ta&&!o(j.title)?"&utmdt="+c.d(j.title):"";e+="&utmhid="+c.uc()+"&utmr="+a.va+"&utmp="+a.Tc(b);return e};a.Tc=function(b){var e=a.a[n];b=h!=b&&""!=b?c.d(b,true):c.d(e.pathname+unescape(e.search),true);return b};a.$c=
function(b){if(a.Q()){var e="";if(a.l!=h&&a.l.N().length>0)e+="&utme="+c.d(a.l.N());e+=a.Ia(b);x.O(e,a.H,a.a,a.f)}};a.qc=function(){var b=new c.Y(a.a,g);return b.Ha(a.f)?b.Wc():h};a._getLinkerUrl=function(b,e){var j=f(b,"#"),t=b,v=a.qc();if(v)if(e&&1>=j[w])t+="#"+v;else if(!e||1>=j[w])if(1>=j[w])t+=(q(b,"?")?"&":"?")+v;else t=j[0]+(q(b,"?")?"&":"?")+v+"#"+j[1];return t};a.Zb=function(){var b;if(a.A&&a.A[w]>=10&&!q(a.A,"=")){a.u.Uc(a.A);a.u.cd();c._gasoDomain=g.g;c._gasoCPath=g.p;b=a.a.createElement("script");
b.type="text/javascript";b.id="_gasojs";b.src="https://www.google.com/analytics/reporting/overlay_js?gaso="+a.A+"&"+c.wa();a.a.getElementsByTagName("head")[0].appendChild(b)}};a.Jc=function(){var b=a.a[c.m],e=a.ja,j=a.u,t=a.f+"",v=a.e,y=v?v.gaGlobal:h,E,F=q(b,c.r+t+"."),I=q(b,c.W+t),G=q(b,c.ma+t),C,D=[],H="",K=false,J;b=o(b)?"":b;if(g.I){E=c.Db(a.a[n]);if(g.pa&&!o(E))H=E+"&";H+=a.a[n].search;if(!o(H)&&q(H,c.r)){j.Rc(H);if(!j.Jb())j.pc();C=j.ya()}r(j.Ba,j.Wb,j.fc);r(j.Aa,j.Na,j.Qa)}if(!o(C))if(o(j.K())||
o(j.za())){C=p(H,"&",e);a.M=true}else{D=f(j.K(),".");t=D[0]}else if(F)if(!I||!G){C=p(b,";",e);a.M=true}else{C=s(b,c.r+t+".",";");D=f(s(b,c.W+t,";"),".")}else{C=[t,c.Gc(),e,e,e,1].join(".");a.M=true;K=true}C=f(C,".");if(v&&y&&y.dh==t){C[4]=y.sid?y.sid:C[4];if(K){C[3]=y.sid?y.sid:C[4];if(y.vid){J=f(y.vid,".");C[1]=J[0];C[2]=J[1]}}}j.Ub(C.join("."));D[0]=t;D[1]=D[1]?D[1]:0;D[2]=undefined!=D[2]?D[2]:g.Yc;D[3]=D[3]?D[3]:C[4];j.La(D.join("."));j.Vb(t);if(!o(j.Hc()))j.Ma(j.t());j.dc();j.Pa();j.ec()};a.Lc=
function(){x=new c.jc(g)};a._initData=function(){var b;if(!z){a.Lc();a.f=a.Bc();a.u=new c.Y(a.a,g)}if(u())a.Jc();if(!z){if(u()){a.va=a.tc(a.Ac(),a.a.domain);if(g.sa){a.aa=new c.gc(g.ua);a.aa.xc()}if(g.qa){b=new c.n(a.f,a.a,a.va,a.ja,g);a.rb=b.yc(a.u,a.M)}}a.l=new c.Z;a.Ab=new c.Z;z=true}if(!c.Hb)a.Mc()};a._visitCode=function(){a._initData();var b=s(a.a[c.m],c.r+a.f+".",";"),e=f(b,".");return e[w]<4?"":e[1]};a._cookiePathCopy=function(b){a._initData();if(a.u)a.u.bd(a.f,b)};a.Mc=function(){var b=a.a[n].hash,
e;e=b&&""!=b&&0==k(b,"#gaso=")?s(b,"gaso=","&"):s(a.a[c.m],c.Sa,";");if(e[w]>=10){a.A=e;if(a.e.addEventListener)a.e.addEventListener("load",a.Zb,false);else a.e.attachEvent("onload",a.Zb)}c.Hb=true};a.Q=function(){return a._visitCode()%10000<g.ha*100};a.Vc=function(){var b,e,j=a.a.links;if(!g.Kb){var t=a.a.domain;if("www."==l(t,0,4))t=l(t,4);g.B.push("."+t)}for(b=0;b<j[w]&&(g.Ga==-1||b<g.Ga);b++){e=j[b];if(i(e.host))if(!e.gatcOnclick){e.gatcOnclick=e.onclick?e.onclick:a.Qc;e.onclick=function(v){var y=
!this.target||this.target=="_self"||this.target=="_top"||this.target=="_parent";y=y&&!a.oc(v);a.ad(v,this,y);return y?false:(this.gatcOnclick?this.gatcOnclick(v):true)}}}};a.Qc=function(){};a._trackPageview=function(b){if(u()){a._initData();if(g.B)a.Vc();a.$c(b);a.M=false}};a._trackTrans=function(){var b=a.f,e=[],j,t,v,y;a._initData();if(a.j&&a.Q()){for(j=0;j<a.j.la[w];j++){t=a.j.la[j];c.h(e,t.S());for(v=0;v<t.ca[w];v++)c.h(e,t.ca[v].S())}for(y=0;y<e[w];y++)x.O(e[y],a.H,a.a,b,true)}};a._setTrans=
function(){var b=a.a,e,j,t,v,y=b.getElementById?b.getElementById("utmtrans"):(b.utmform&&b.utmform.utmtrans?b.utmform.utmtrans:h);a._initData();if(y&&y.value){a.j=new c.i;v=f(y.value,"UTM:");g.G=!g.G||""==g.G?"|":g.G;for(e=0;e<v[w];e++){v[e]=m(v[e]);j=f(v[e],g.G);for(t=0;t<j[w];t++)j[t]=m(j[t]);if("T"==j[0])a._addTrans(j[1],j[2],j[3],j[4],j[5],j[6],j[7],j[8]);else if("I"==j[0])a._addItem(j[1],j[2],j[3],j[4],j[5],j[6])}}};a._addTrans=function(b,e,j,t,v,y,E,F){a.j=a.j?a.j:new c.i;return a.j.nb(b,e,
j,t,v,y,E,F)};a._addItem=function(b,e,j,t,v,y){var E;a.j=a.j?a.j:new c.i;E=a.j.xa(b);if(!E)E=a._addTrans(b,"","","","","","","");E.mb(e,j,t,v,y)};a._setVar=function(b){if(b&&""!=b&&A()){a._initData();var e=new c.Y(a.a,g),j=a.f;e.Na(j+"."+c.d(b));e.Qa();if(a.Q())x.O("&utmt=var",a.H,a.a,a.f)}};a._link=function(b,e){if(g.I&&b){a._initData();a.a[n].href=a._getLinkerUrl(b,e)}};a._linkByPost=function(b,e){if(g.I&&b&&b.action){a._initData();b.action=a._getLinkerUrl(b.action,e)}};a._setXKey=function(b,e,
j){a.l._setKey(b,e,j)};a._setXValue=function(b,e,j){a.l._setValue(b,e,j)};a._getXKey=function(b,e){return a.l._getKey(b,e)};a._getXValue=function(b,e){return a.l.getValue(b,e)};a._clearXKey=function(b){a.l._clearKey(b)};a._clearXValue=function(b){a.l._clearValue(b)};a._createXObj=function(){a._initData();return new c.Z};a._sendXEvent=function(b){var e="";a._initData();if(a.Q()){e+="&utmt=event&utme="+c.d(a.l.Sc(b))+a.Ia();x.O(e,a.H,a.a,a.f,false,true)}};a._createEventTracker=function(b){a._initData();
return new c.ic(b,a)};a._trackEvent=function(b,e,j,t){var v=true,y=a.Ab;if(h!=b&&h!=e&&""!=b&&""!=e){y._clearKey(5);y._clearValue(5);v=y._setKey(5,1,b)?v:false;v=y._setKey(5,2,e)?v:false;v=h==j||y._setKey(5,3,j)?v:false;v=h==t||y._setValue(5,1,t)?v:false;if(v)a._sendXEvent(y)}else v=false;return v};a.ad=function(b,e,j){a._initData();if(a.Q()){var t=new c.Z;t._setKey(6,1,e.href);var v=j?function(){a.rc(b,e)}:undefined;x.O("&utmt=event&utme="+c.d(t.N())+a.Ia(),a.H,a.a,a.f,false,true,v)}};a.rc=function(b,
e){if(!b)b=a.e.event;var j=true;if(e.gatcOnclick)j=e.gatcOnclick(b);if(j||typeof j=="undefined")if(!e.target||e.target=="_self")a.e.location=e.href;else if(e.target=="_top")a.e.top.document.location=e.href;else if(e.target=="_parent")a.e.parent.document.location=e.href};a.oc=function(b){if(!b)b=a.e.event;var e=b.shiftKey||b.ctrlKey||b.altKey;if(!e)if(b.modifiers&&a.e.Event)e=b.modifiers&a.e.Event.CONTROL_MASK||b.modifiers&a.e.Event.SHIFT_MASK||b.modifiers&a.e.Event.ALT_MASK;return e};a._setDomainName=
function(b){g.g=b};a.dd=function(){return g.g};a._addOrganic=function(b,e){c.h(g.fa,new c.cb(b,e))};a._clearOrganic=function(){g.fa=[]};a.hd=function(){return g.fa};a._addIgnoredOrganic=function(b){c.h(g.ea,b)};a._clearIgnoredOrganic=function(){g.ea=[]};a.ed=function(){return g.ea};a._addIgnoredRef=function(b){c.h(g.ga,b)};a._clearIgnoredRef=function(){g.ga=[]};a.fd=function(){return g.ga};a._setAllowHash=function(b){g.pb=b?1:0};a._setCampaignTrack=function(b){g.qa=b?1:0};a._setClientInfo=function(b){g.sa=
b?1:0};a._getClientInfo=function(){return g.sa};a._setCookiePath=function(b){g.p=b};a._setTransactionDelim=function(b){g.G=b};a._setCookieTimeout=function(b){g.wb=b};a._setDetectFlash=function(b){g.ua=b?1:0};a._getDetectFlash=function(){return g.ua};a._setDetectTitle=function(b){g.ta=b?1:0};a._getDetectTitle=function(){return g.ta};a._setLocalGifPath=function(b){g.Da=b};a._getLocalGifPath=function(){return g.Da};a._setLocalServerMode=function(){g.D=0};a._setRemoteServerMode=function(){g.D=1};a._setLocalRemoteServerMode=
function(){g.D=2};a.gd=function(){return g.D};a._getServiceMode=function(){return g.D};a._setSampleRate=function(b){g.ha=b};a._setSessionTimeout=function(b){g.Tb=b};a._setAllowLinker=function(b){g.I=b?1:0};a._setAllowAnchor=function(b){g.pa=b?1:0};a._setCampNameKey=function(b){g.db=b};a._setCampContentKey=function(b){g.eb=b};a._setCampIdKey=function(b){g.fb=b};a._setCampMediumKey=function(b){g.gb=b};a._setCampNOKey=function(b){g.hb=b};a._setCampSourceKey=function(b){g.ib=b};a._setCampTermKey=function(b){g.jb=
b};a._setCampCIdKey=function(b){g.kb=b};a._getAccount=function(){return a.H};a._getVersion=function(){return _gat.lb};a.kd=function(b){g.B=[];if(b)g.B=b};a.md=function(b){g.Kb=b};a.ld=function(b){g.Ga=b};a._setReferrerOverride=function(b){a.yb=b};a.Ac=function(){return a.yb}};_gat._getTracker=function(d){var a=new _gat.kc(d);return a};


/** File: registration.js */
var selectedSection;

function openCloseClothing(linkDiv, imgRoot) {
    openCloseSection(linkDiv, selectedSection, imgRoot)
}

function setSelectedSection(newVal) {
    selectedSection = newVal;
}

function openCloseSection(linkDiv, contentDiv, imgRoot) {
    if($("#" + contentDiv).css("display") == "none") {
        $("#" + linkDiv + "> a > .arrow").attr("src",imgRoot + "images2_5/registration/oarrow_down.png");
        $("#"+contentDiv).slideDown();
        $("#" + linkDiv + "> .clickInfo").hide();
        $("#" + linkDiv + "> a > span.catName").css('color', '#6A9F16');
        }
    else {
       $("#" + linkDiv + "> a > .arrow").attr("src",imgRoot + "images2_5/registration/oarrow_side.png");
        $("#"+contentDiv).slideUp();
        $("#" + linkDiv + "> a > span.catName").css('color', '#0072AD');
        $("#" + linkDiv + "> .clickInfo").show();
    }
}

function switchContent(currentContent, newContent) {
    $("#" + currentContent).fadeOut(function()
            {
        $("#" + newContent).fadeIn();
            });
}

function toggleLike(referenceDiv) {
    if( $("#"+referenceDiv).attr('disabled')){
        document.getElementById(referenceDiv).disabled = false;
        $($('#'+referenceDiv).siblings('.likebtn')).children('a').attr('class','ulikeit');
    }
    else {
        document.getElementById(referenceDiv).disabled = true;
        $($('#'+referenceDiv).siblings('.likebtn')).children('a').attr('class','ilikeit');
    }
}

var selectedEmailHost;
function setSelectedEmailHost(host) {
    selectedEmailHost = host;
}

function toggleEmailHost(newHost){
    $("#btn_" + selectedEmailHost).fadeOut(function(){
        $("#btn_" + newHost).fadeIn();
    });
    $("#link_" + newHost).fadeOut(function(){
        $("#link_" + selectedEmailHost).fadeIn();
        document.getElementById("selected_"+selectedEmailHost).disabled = true;
        document.getElementById("selected_" + newHost).disabled = false;
        setSelectedEmailHost(newHost);
    });
     $("#emailLogin").val("");
    $("#emailPassword").val("");

}


//custom checkbox functions

function toggleCheckBox(referenceDiv){
    if( $("#"+referenceDiv).attr('disabled')){
        document.getElementById(referenceDiv).disabled = false;
        $('#'+referenceDiv).siblings('a.unselected').attr('class','selected');
    }
    else {
        document.getElementById(referenceDiv).disabled = true;
        $('#'+referenceDiv).siblings('a.selected').attr('class','unselected');
    }
}



function toggleEachFeaturedAllCheckBox(featuredBrandId) {
    allBrandsId = featuredBrandId + "_all";
    hiddenVarId = featuredBrandId + "_all_hiddenVar";
    if($("#" + hiddenVarId).attr("disabled")){
        document.getElementById(hiddenVarId).disabled = false;
        $("#" + featuredBrandId).addClass('selected');
        $("#" + featuredBrandId).removeClass('unselected');
        $("#" + allBrandsId).addClass('selected');
        $("#" + allBrandsId).removeClass('unselected');
    }
    else {
        document.getElementById(hiddenVarId).disabled = true;
        $("#" + featuredBrandId).addClass('unselected');
        $("#" + featuredBrandId).removeClass('selected');
        $("#" + allBrandsId).addClass('unselected');
        $("#" + allBrandsId).removeClass('selected');    
    }
}

keyArrAll = {};
function toggleAllFeaturedCheckBoxes(featuredDivRef, allDivRef, selectAll) {
    $(allDivRef.find('a.checkBoxLink')).each(function(){
       keyArrAll[$(this).attr('id')] = $(this);
    });
    $(featuredDivRef.find('a.checkBoxLink')).each(function(){
        if(selectAll) {
            try{
            featuredRefid = $(this).attr('id');
            $(this).addClass('selected');
            $(this).removeClass('unselected');
            allRef = keyArrAll[featuredRefid + "_all"];
            allRef.addClass('selected');
            allRef.removeClass('unselected');
            document.getElementById(featuredRefid + "_all_hiddenVar").disabled = false;
            }
            catch(e) {
//                alert($(this).attr('id'));
            }
        }
        else {
            try{
            featuredRefid = $(this).attr('id');
            $(this).addClass('unselected');
            $(this).removeClass('selected');
            allRef = keyArrAll[featuredRefid + "_all"];
            allRef.addClass('unselected');
            allRef.removeClass('selected');
            document.getElementById(featuredRefid + "_all_hiddenVar").disabled = true;
            }
            catch(e) {
//                alert($(this).attr('id'));
            }
        }
    });
}

function toggleAllFeaturedAllCheckBoxes(featuredDivRef, allDivRef, selectAll) {
    $(featuredDivRef.find('a.checkBoxLink')).each(function(){
        if(selectAll) {
            try{
            $(this).addClass('selected');
            $(this).removeClass('unselected');
            }
            catch(e) {
//                alert($(this).attr('id'));
            }
        }
        else {
            try{
            $(this).addClass('unselected');
            $(this).removeClass('selected');
            }
            catch(e) {
//                alert($(this).attr('id'));
            }
        }
    });

    $(allDivRef.find('a.checkBoxLink')).each(function(){
        if(selectAll) {
            try{
            $(this).addClass('selected');
            $(this).removeClass('unselected');
            document.getElementById($(this).attr('id') + "_hiddenVar").disabled = false;
            }
            catch(e) {
//                alert(e + " " + $(this).attr('id'));
            }
        }
        else {
            try{
            $(this).addClass('unselected');
            $(this).removeClass('selected');
            document.getElementById($(this).attr('id') + "_hiddenVar").disabled = true;
            }
            catch(e) {
//                alert($(this).attr('id'));
            }
        }
    });

}

function minBrandSelected(linkContainerClass, errorDivId) {
    if ($('.' + linkContainerClass).children('a.selected').size() > 0) {
        return true;
    }
    $("#" +errorDivId).css('display','block')
    return false;
}

function selectDeselectAllCheckBox(referenceLink, prefix, startCount, endCount,switchText){
    if($(referenceLink).attr('class') == 'unselected'){
        $(referenceLink).attr('class','selected');
            selectDeselectAll(true, prefix, startCount, endCount);
         if(switchText){
             $("#clearText1").show();
             $("#clearText2").show();
            $("#checkText1").hide();
             $("#checkText2").hide();
        }
        }
    else {
        $(referenceLink).attr('class','unselected');
        selectDeselectAll(false, prefix, startCount, endCount);
         if(switchText){
              $("#checkText1").show();
             $("#checkText2").show();
            $("#clearText1").hide();
             $("#clearText2").hide();

        }
    }
}

function selectDeselectAllLinkCheckbox(referenceLink, prefix, startCount, endCount, show, hide){
    $("." + show).show();
    $("." + hide).hide();
    if($('#' + referenceLink).attr('class') == 'unselected'){
        $('#' + referenceLink).attr('class','selected');
            selectDeselectAll(true, prefix, startCount, endCount);
        }
    else {
        $('#' + referenceLink).attr('class','unselected');
        selectDeselectAll(false, prefix, startCount, endCount);
    }
}

function selectDeselectAll(selected, prefix, startCount, endCount){
    //follows format prefix1, prefix2 etc
    if(selected){
        for (i = startCount;i<=endCount;i++) {
            referenceDiv = prefix + i;
            document.getElementById(referenceDiv).disabled = false;
            $('#'+referenceDiv).siblings('a.unselected').attr('class','selected');
        }
    }
    else {
        for (i = startCount;i<=endCount;i++) {
            referenceDiv = prefix + i;
            document.getElementById(referenceDiv).disabled = true;
            $('#'+referenceDiv).siblings('a.selected').attr('class','unselected');
        }
    }
}

function selectWomensClothing(refLink) {
    refLink.parents('.genderSelectorContainer').css('display','none');
    refLink.parents('.genderSelectorContainer').siblings('.regFlowBrandsContainer').css('display','block');
	selectRegFlowTab('womens_apparel');

}

function selectMensClothing(refLink) {
    refLink.parents('.genderSelectorContainer').css('display','none');
    refLink.parents('.genderSelectorContainer').siblings('.regFlowBrandsContainer').css('display','block');
       selectRegFlowTab('mens_apparel');

}

function selectRegFlowTab(catType) {
    if(catType == 'womens_apparel') {
        refLink = $("#womens_apparel_tabLink");
        refLink.children('img').addClass('womens_apparel_tabSelected');
        refLink.children('img').removeClass('womens_apparel_tabUnSelected');
        refLink.siblings('a').children('img').addClass('mens_apparel_tabUnSelected');
        refLink.siblings('a').children('img').removeClass('mens_apparel_tabSelected')
        $('.womens_apparel_category').css('display','block');
        $('.mens_apparel_category').css('display','none');
    }
    else if(catType == 'mens_apparel') {
        refLink = $("#mens_apparel_tabLink");
        refLink.children('img').addClass('mens_apparel_tabSelected');
        refLink.children('img').removeClass('mens_apparel_tabUnSelected');
        refLink.siblings('a').children('img').addClass('womens_apparel_tabUnSelected');
        refLink.siblings('a').children('img').removeClass('womens_apparel_tabSelected');
        $('.mens_apparel_category').css('display','block');
        $('.womens_apparel_category').css('display','none');
    }
}

function viewAllBrands(refLink) {
    refLink.parents('.featured').css('display','none');
    refLink.parents('.featured').siblings('.allListings').css('display','block');
}

function viewFeaturedBrands(refLink) {
    refLink.parents('.allListings').css('display','none');
    refLink.parents('.allListings').siblings('.featured').css('display','block');
}

function selectSubCategory(refParentDiv, refCheckBox) {
    subCatImg = refParentDiv.find('.subCategoryImage');
    if( $("#"+refCheckBox).attr('disabled')){
        imgPosition = ' 0 -10px'
    }
    else {
        imgPosition = ' 0 -112px'
    }
    subCatImg.css({"background-position":imgPosition});
    toggleCheckBox(refCheckBox);
}


function selectDeselectAllSubCategories(parentRef,selected, prefix, startCount, endCount) {
    selectDeselectAll(selected, prefix, startCount, endCount);

//    if(selected) {
//        imgPosition = ' 0 -10px'
//    }
//    else {
//        imgPosition = ' 0 -112px'
//    }
//    parentRef.find('.subCategoryImage').css({"background-position":imgPosition});
}

function showMoreSelectedBrands(linkRef) {
    linkRef.css('display','none');
    linkRef.parent().siblings('.moreBrands').slideDown();
}

function showLessSelectedBrands(linkRef) {
    linkRef.parents('.moreBrands').siblings('.seeMoreLess').children().css('display','block');
    linkRef.parents('.moreBrands').slideUp();
}

function makeMoreBrandsYouLikeFormAsync( form, callback )
{
    form.submit( function() {

        var url = form.attr("action");
    	if (url.charAt(url.length-1) == '?') url = url.substr(0, url.length-1);
    	var formElements=form[0].elements;
	    var params = new Object();
        var numParams = 0;
        var numSelected = 0;
        var queryString = "";
        for(var i=0;i<formElements.length; i++){
             if ( (formElements[i].type != 'radio' && formElements[i].type != 'checkbox') || formElements[i].checked) {
              if(numParams == 0) {
                  queryString = "?" + formElements[i].name + "="+ formElements[i].value;
              }
              else {
                  queryString += "&" + formElements[i].name + "="+ formElements[i].value;
              }
             if(formElements[i].checked)
                numSelected++;

            numParams++;
            params[formElements[i].name] = formElements[i].value;
          }
        }
        if(numSelected > 0) {
            url = url + queryString;
            $.get(url, {}, callback);
            return false;
        }
        else {
            return false;
        }
    });
}


function prepareMoreBrandsYouLikeForm (formid, moreBrandsContainer, moreBrandsSuccess, moreBrandsError) {

    formRef = $("#" + formid);
    makeMoreBrandsYouLikeFormAsync($("#" + formid), function(data) {
        if(data =="success") {
            $("#" + moreBrandsContainer).slideUp(function(){
                $("#" + moreBrandsSuccess).slideDown();
            })
        }
        else {
            $("#" + moreBrandsError).css('display','block');
        }
    })
}

/** File: gridView.js */
/*
* JsPopUpBox v.0.3
* http://maurizio.mavida.com/
* based on great jQuery  - http://jquery.com/

Use:
*** jquery  mode ***
*/

var varGridPopup = ""
var width = 325;
var height = 275;
var orientation = "";
var searchPopupTimeout;
var popupDisplayTimeout;
var referenceDivId;
                                    
function fixIE(n,w,h){
	//alert("start IE fix");
    if(!$(n).is("div")){ //only do this for divs
        return;
    }
    var bg = $(n).css("background-image");
    var bgImg;
    var repeat;
    if(bg.match(/^url[("']+(.*\.png)[)"']+$/i)){
        bgImg = RegExp.$1;
        $(n).css("background-image","none");
        repeat = $(n).css("background-repeat");

    }else{
        return;
    }
    var method = (repeat.indexOf("y") > -1 || repeat.indexOf("x") > -1)? "scale" : "crop";
    //alert(w+" " + h);
    $(n).css("filter", "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+bgImg+"',sizingMethod='"+method+"')");
    if(method == "scale"){
        var divH = $(n).height();
        var divW = $(n).width();
        if (repeat.indexOf("x") > -1)
            $(n).css("width",divW+"px");
        if(w != null)
            $(n).css("width",w+"px");
        if (repeat.indexOf("y") > -1)
            $(n).css("height",divH+"px");
        if(h != null)
            $(n).css("height",h+"px");
    }
}

function iePositionFix(n){
    if($(n).is("input") || $(n).is("a")){
        $(n).css({position:"relative"});
    }
}

function iePNGFix(pDiv){
    $.each($(pDiv).children(), function(i,n){
        iePNGFix(n);
    });
    fixIE(pDiv);
    iePositionFix(pDiv);
}

function gridPopup(dataDivId,event,clickObj,imgSize, productId, isSponsored){
if(typeof document.body.style.maxHeight == "undefined") // IE6 or other older browser, hide select boxes
          hideSelectBoxes(); //defined in lightbox js

  if (referenceDivId != undefined && referenceDivId != 'searchGridPopup_'+ productId && referenceDivId != 'searchGridPopup_sp_'+ productId) {
     $("#" + referenceDivId).css("display", "none");
  }
  if(isSponsored){
    referenceDivId =  "searchGridPopup_sp_" + productId;
  }
    else {
    referenceDivId =  "searchGridPopup_" + productId;
  }
    clearTimeout(searchPopupTimeout);
    if(orientation.length < 1)
        orientation = "Left";
    var dataDiv = $("#" + dataDivId).html();
    if($("#" + referenceDivId).size() == 0) {
        varGridPopup = "<div id='" + referenceDivId + "' class='searchGridPopup'></div>"
        $(document.body).append(varGridPopup);
        varGridContent = "<div class='topLeft'><!-- --></div><div class='topCenter'><!-- --></div><div class='topRight'><!-- --></div>"
        varGridContent = varGridContent + "<div class='clearer'><!-- --></div><div class='bodyContainer'><div class='bodyLeft'><div class='arrowPointerLeft'><!-- --></div></div><div class='bodyCenter'><div><a href='#' onClick='closePopup();return false;' class='close_x' id='PTMx'><img src='" + imgRoot + "images2_5/ptm/close_x.gif'></a></div></div><div class='bodyRight'><div class='arrowPointerRight'><!-- --></div><!-- --></div><div class='clearer'><!-- --></div></div>"
        varGridContent = varGridContent + "<div class='clearer'><!-- --></div><div class='bottomLeft'><!-- --></div><div class='bottomCenter'><!-- --></div><div class='bottomRight'><!-- --></div>"
        $("#"+ referenceDivId).html(varGridContent);
        //            $("#"+ referenceDivId).children(".bodyContainer").children(".bodyCenter").append( $("#" + dataDivId).children(".product_image_gridview").html());
        $("#" + dataDivId).children(".product_image_gridview").clone().appendTo($("#"+ referenceDivId).children(".bodyContainer").children(".bodyCenter"));
        $("#" + dataDivId).children(".product_info_gridview").clone().appendTo($("#"+ referenceDivId).children(".bodyContainer").children(".bodyCenter"));
        $("#"+ referenceDivId).children(".bodyContainer").children(".bodyCenter").children(".product_info_gridview").children(".ratingInfo").remove();
        $("#"+ referenceDivId).children(".bodyContainer").children(".bodyCenter").children(".product_image_gridview").children(".gridDetails").remove();
        arrangeData(imgSize, productId);
        initializeStyles(width, height);
        $("#" + referenceDivId).css("display", "block");
        $(window).resize(function(){ positionPopup(clickObj); } );
    }
    else {
         $("#" + referenceDivId).toggle();
         positionPopup(clickObj);
         return;
     }

    $("#" + referenceDivId).css("display", "block");
        $("#" + referenceDivId).css("visibility", "hidden");
    positionPopup(clickObj);
    clearTimeout(popupDisplayTimeout);
    popupDisplayTimeout = setTimeout(function() {
        $("#" + referenceDivId).css("visibility", "visible");
    },750);
}

function flipArrow(direction){
    var hide = (direction == "Right")? "Left" : "Right";
    var show = (direction == "Right")? "Right" : "Left";

    $("div#" + referenceDivId + " > div.bodyContainer > div.body" +hide+ " > div.arrowPointer" + hide).css({
        "display"          :   "none"
    });
    $("div#" + referenceDivId + " > div.bodyContainer > div.body" +show+ " > div.arrowPointer" + show).css({
        "display"          :   "block"
    });
    orientation = direction;
    //fixIE($("div#" + referenceDivId + " > div.bodyContainer > div.body" +show+ " > div.arrowPointer" + show));
}

var modifiedDetails = "";
function positionPopup(clickObj) {

    /***
     New Positioning code, it will ensure that if the window height
     is great enough to fit the pop-up in i.e. about 270px then the
     pop-up will always appear on-screen (i.e. no parts off screen).
     Otherwise it will simply position the pop-up to the top of the
     screen.
    ***/

    //POSITION LEFT OR RIGHT
    clickObjPos = $(clickObj).position();
    if( width < clickObjPos.left ){
       nLeft = clickObjPos.left - width;
       flipArrow("Right");

    }else{
        nLeft = clickObjPos.left + clickObj.offsetWidth;
        flipArrow("Left");
    }

    //POSITION TOP: NEW TOP POSITIONING CODE
    //var windowH = $(window).height();
    var visibleScreenTop = $(document).scrollTop();
    //var visibleScreenBottom = visibleScreenTop+windowH;

    //position pop-up at the top of the visible screen.
    nTop = visibleScreenTop;

    //if the caller link's lowest part is lower on the screen than
    //the lowest part of the pop-up, move the pop-up lower.
    while((clickObjPos.top + 20) > (nTop + height) ){
        nTop += 25;
    }
    //calculate the top-margin for the arrow
    var arrowTop = (clickObjPos.top - nTop) - 20;
    if(arrowTop > 240)
        arrowTop = 240;
    else if (arrowTop < 0)
        arrowTop = 0;
    $("div#" + referenceDivId + " > div.bodyContainer > div.body" + orientation + " > div.arrowPointer" + orientation).css({
        "margin-top"          :   arrowTop + "px"
      });
    /*** END NEW TOP POSITIONING CODE ***/

    //alert('n-top is ' + nTop + ' nleft is ' + nLeft);
    $("#" + referenceDivId).css("top",nTop+"px");
    $("#" + referenceDivId).css("left",nLeft+"px");

    if($.browser.msie){
        var ver = $.browser.version;
        if(ver.indexOf("5") > -1 || ver.indexOf("6") > -1){
            if(modifiedDetails.indexOf(referenceDivId) == -1){
                var theObj = $("div#" + referenceDivId);
                var theObjPos = theObj.position();
                fixIE($("div#" + referenceDivId + "  > div.bodyContainer > div.bodyRight > div.arrowPointerRight"));
                fixIE($("div#" + referenceDivId + "  > div.bodyContainer > div.bodyLeft > div.arrowPointerLeft"));
                fixIE($("div#" + referenceDivId + "  > div.topCenter"));
                fixIE($("div#" + referenceDivId + "  > div.bottomCenter"));
                fixIE($("div#" + referenceDivId + "  > div.topRight"));
                fixIE($("div#" + referenceDivId + "  > div.bottomRight"));
                fixIE($("div#" + referenceDivId + "  > div.bodyContainer > div.bodyRight"),10,null);
                fixIE($("div#" + referenceDivId + "  > div.bodyContainer > div.bodyLeft"),11, null);
                var center = $("div#" + referenceDivId + "  > div.bodyContainer > div.bodyCenter");
                center.width(center.width()-3+"px");
                fixIE($("div#" + referenceDivId + "  > div.topLeft"),11,null);
                $("div#" + referenceDivId + "  > div.topLeft").width("11px");
                fixIE($("div#" + referenceDivId + "  > div.bottomLeft"),11,null);
                $("div#" + referenceDivId + "  > div.bottomLeft").width("11px");
                //$("div#" + referenceDivId + "  > div.bodyContainer > div.bodyLeft").css("margin-left","20px");
                modifiedDetails += referenceDivId + ",";
            }
        }
    }

    return true;
}


function arrangePopupLikeInfo() {
    $("div#" + referenceDivId + "  > div.bodyContainer> div.bodyCenter > div > div.ilike_info > div.discoveredby_photo_gridview").css("display", "none");
    $("div#" + referenceDivId + " > div.bodyContainer > div.bodyCenter > div > div.ilike_info > div.discoveredby_photo_gridview").css("width", "25px");
    $("div#" + referenceDivId + " > div.bodyContainer > div.bodyCenter > div > div.ilike_info > div.search_ilike_btn_gridview").css("display", "none");
}

function arrangeData(imgSize, productId) {
    $("div#" + referenceDivId + "  > div.bodyContainer > div.bodyCenter > div > p.product_description").show();
    $("div#" + referenceDivId + "  > div.bodyContainer > div.bodyCenter > div.product_info_gridview > div.product_title_gridview > a.title > span.titleShort").css("display", "none");
    $("div#" + referenceDivId + "  > div.bodyContainer > div.bodyCenter > div.product_info_gridview > div.product_title_gridview > a.title > span.titleLong").css("display", "block");
    $("div#" + referenceDivId + " > div.bodyContainer > div.bodyCenter > div.product_buyinfo_gridview > p.pricegridview > a.productpricegridview").css("font-size", "16px")
    $("div#" + referenceDivId + " > div.bodyContainer > div.bodyCenter > div.product_image_gridview").css("height","150px");
    $("div#" + referenceDivId + " > div.bodyContainer > div.bodyCenter").css("height",height);
    arrangePopupLikeInfo();
    if(imgSize == 'large') {
        $("div#" + referenceDivId + " > div.bodyContainer > div.bodyCenter > div.product_image_gridview > a > img").css("display", "none");
        $("div#" + referenceDivId + " > div.bodyContainer > div.bodyCenter > div.product_image_gridview > a").load("/community/productAsynchDataRetrieval.do?prontoProductId=" +productId + "&view=productForImagePopup&imageSize=large");
        $("div#" + referenceDivId + " > div.bodyContainer > div.bodyCenter  > div.product_image_gridview").css("padding-bottom","5px");
        $("div#" + referenceDivId + " > div.bodyContainer > div.bodyCenter > div.product_image_gridview").css("height","155px");
    }
    else {
        $("div#" + referenceDivId + " > div.bodyContainer > div.bodyCenter > div.product_image_gridview").css("height","120px");
        $("div#" + referenceDivId + " > div.bodyContainer > div.bodyCenter > div.product_image_gridview").css("padding-top","30px");
    }

 }

function closePopup() {
         $("#" + referenceDivId).css("display", "none");
}


function initializeStyles(width, height) {
     $("div#" + referenceDivId).css({
            "width"          :   width + "px"
          });

    $("div#" + referenceDivId + " > div.bodyContainer").css({
            "width"          :   width + "px"
          });

       $("div#" + referenceDivId + " > div.bodyContainer > div.bodyRight").css({
            "height"          :   height + "px"
            });
        $("div#" + referenceDivId + " > div.bodyContainer > .bodyLeft").css({
            "height"          :   height + "px"
            });
        $("div#" +referenceDivId + " > div.bodyContainer > .bodyCenter").css({
            "width"          :   width - 82 + "px"
          });

        $("div#" + referenceDivId + " > div.topCenter").css({
            "width"          :   (width - 56) + "px"
          });
        $("div#" + referenceDivId + " > div.bottomCenter").css({
            "width"          :   (width - 56) + "px"
          });

}

//  LIST JS

 var tempKey;
function showA2L(caller, popupName, itemKey, itemType, parentUrl){
    divObjId = popupName;
	divObjClass = "listPopup";
	popupBtnsRef = $(caller).parents('.popupBtns');
    divObj = popupBtnsRef.parent().find('.popupListContent');    
//    divObj = $(caller).parents('.popupContent').find('.popupListContent');
    update = true;
    $(caller).children('img').addClass('addToListSelected');
    $(caller).children('img').removeClass('addToList');

    if(divObj.length > 0){
        divObj.html('');
    }
    $(caller).parents('.popupMiddle').siblings('.popupBottom').addClass('bottomBlue');
    $(caller).parents('.popupMiddle').siblings('.popupBottom').removeClass('    bottomWhite');
    var url = "/community/addToListShowDialogLightBox.do?itemKey=" + itemKey + "&itemType="+itemType + "&parentUrl="+parentUrl;
    divObj.css('display','block');


    /*if(divObj.length > 0){ //if obj exists
        if (itemKey == tempKey){ //if same link
            //do nothing, already hidden
            if(divObj.css("display") != "none"){
                tempKey="";
                divObj.remove(); //hide whatever is being displayed
                return;
            }
        }
    }
        divObj.remove();
        divObj = $("<div id='"+divObjId+"' class='"+divObjClass+"'></div>");
        divObj.appendTo("body");
     */
        divObj.load(url, function(){


//         positionA2L(caller,  divObj );
    });

    tempKey = itemKey;
	return false;
}


function hideA2L(divObj){
//    divObj = $(caller).parents('.popupListContent');
    divObj.css('display','none');
    addToListLink = divObj.siblings('.popupBtns').children('.showAddToList');
    addToListLink.children('img').addClass('addToList');
    addToListLink.children('img').removeClass('addToListSelected');
    divObj.parents('.popupMiddle').siblings('.popupBottom').addClass('bottomWhite');
    divObj.parents('.popupMiddle').siblings('.popupBottom').removeClass('bottomBlue');


}
var openPopup = undefined;

function openProductPopup(caller, refDiv) {
    if(openPopup != undefined && openPopup != null) {
        if(openPopup.parents('.eachGridProduct').attr('id') != refDiv.parents('.eachGridProduct').attr('id')) {
            openPopup.css("display",'none');
            hideDetailsBtn(openPopup.parents('.eachGridProduct'));
            refDiv.css('display','block');
            openPopup = refDiv;
        }
        else {
            if(openPopup.css('display') == 'block') {
                openPopup.css("display",'none');
                hideDetailsBtn(openPopup.parents('.eachGridProduct'));
            }
            else {
            refDiv.css('display','block');
            }
        }
    }
    else {
        refDiv.css('display','block');
        openPopup = refDiv;
    }

    var productGridRef = caller.parents('.eachGridProduct');
    var positionGridProduct = productGridRef.position();
    var positionGridWidth = productGridRef.width();
    var popupWidth = 365;

    var winWidth = $(window).width();

    if(positionGridProduct.left + positionGridWidth + popupWidth < winWidth) {
        refDiv.css("left",(positionGridProduct.left + positionGridWidth +"px" ));
        refDiv.find('.leftArrow').css('display','block');
    }
    else {
        refDiv.css("left",(positionGridProduct.left-popupWidth  )+"px");
        refDiv.find('.rightArrow').css('display','block');
    }


	refDiv.css("top",(positionGridProduct.top-12)+"px");
}




function showDetailsBtn(divRef) {
    /*if ((detailsBtnRef).parents('.eachGridProduct').children('productPopup').css('display') == 'none')
           detailsBtnRef = divRef.children('.seeDetails');    */
    detailsBtnRef = divRef.children('.seeDetails');
    if(detailsBtnRef.css('display' != 'none'))
        detailsBtnRef.fadeIn(100);

//    divRef.children('.seeDetails').fadeIn();
}

function hideDetailsBtn(containerRef) {
    detailsBtnRef = containerRef.find('.seeDetails');
    if ((detailsBtnRef).parents('.eachGridProduct').children('.productPopup').css('display') == 'none')
        detailsBtnRef.fadeOut(100);
}

function closeProductPopup(popupRef) {
    eachProductRef = popupRef.parents('.eachGridProduct');
    eachProductRef.find('.seeDetails').fadeOut(100);
    eachProductRef.find('.productPopup').css('display','none');
    openPopup = undefined;
}

function selectEnlargeImageTab(productId, linkRef) {
    var popupContent = linkRef.parents('.popupContent');
    var imgDiv = popupContent.find(".popupEnlargeImage");
    if(imgDiv.size() == 0) {
        popupContent.append("<div class='popupEnlargeImage'></div>");
        imgDiv = popupContent.find(".popupEnlargeImage");
        imgDiv.load("/community/productAsynchDataRetrieval.do?prontoProductId=" + productId + "&view=productForImagePopup", function(detailsDiv, imgDiv) {});
    }
    var detailsDiv = popupContent.find(".popupProductDetails");
    detailsDiv.css('display','none');
    switchTabs(linkRef);
    imgDiv.css('display','block');
}

function selectDetailsTab(linkRef) {
    var popupContent = linkRef.parents('.popupContent');
    var imgDiv = popupContent.find(".popupEnlargeImage");
    var detailsDiv = popupContent.find(".popupProductDetails");
    imgDiv.css('display','none');
    switchTabs(linkRef);
    detailsDiv.css('display','block');

}

function switchTabs(linkRef) {
    linkRef.addClass('selectedTab');
    linkRef.siblings('a').removeClass('selectedTab');
}