//start /sites/scripts/common.js
var panelToChange;
var panelWidth;

function setSelectedValue(s, v) {
    for ( var i = 0; i < s.options.length; i++ ) {
        if ( s.options[i].value == v ) {
            s.options[i].selected = true;
            return;
        }
    }
}

function replaceTargetImage(target, image)
{
  if(image != ''){
    $(target).src = image;
  }
}

//trim string... good for imposing maxlengths in textareass
function Trim(s, maxlength) {
    if (s.value.length > maxlength) 
    s.value = s.value.substring(0,maxlength);
}

function setCookie(name,value,expiredays)
{
    var exdate=new Date();
    exdate.setDate(exdate.getDate()+expiredays);
    document.cookie=name+ "=" +escape(value)+
    ((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
}
	
function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
	    var c = ca[i];
	    while (c.charAt(0)==' ') c = c.substring(1,c.length);
	    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;	
}

//grays out anything on the screen with z-index less than 1500
//vis = true to start the gray-out, false to remove the gray out.
function grayOut(vis, options) {
      // Pass true to gray out screen, false to ungray
      // options are optional.  This is a JSON object with the following (optional) properties
      // opacity:0-100         // Lower number = less grayout higher = more of a blackout 
      // zindex: #             // HTML elements with a higher zindex appear on top of the gray out
      // bgcolor: (#xxxxxx)    // Standard RGB Hex color code
      // grayOut(true, {'zindex':'50', 'bgcolor':'#0000FF', 'opacity':'70'});
      // Because options is JSON opacity/zindex/bgcolor are all optional and can appear
      // in any order.  Pass only the properties you need to set.
      var options = options || {}; 
      var zindex = options.zindex || 1500;
      var opacity = options.opacity || 50;
      var opaque = (opacity / 100);
      var bgcolor = options.bgcolor || '#000000';
      var dark=document.getElementById('darkenScreenObject');
      if (!dark) {
        // The dark layer doesn't exist, it's never been created.  So we'll
        // create it here and apply some basic styles.
        // If you are getting errors in IE see: http://support.microsoft.com/default.aspx/kb/927917
        var tbody = document.getElementsByTagName("body")[0];
        var tnode = document.createElement('div');           // Create the layer.
            tnode.style.position='absolute';                 // Position absolutely
            tnode.style.top='0px';                           // In the top
            tnode.style.left='0px';                          // Left corner of the page
            tnode.style.overflow='hidden';                   // Try to avoid making scroll bars            
            tnode.style.display='none';                      // Start out Hidden
            tnode.id='darkenScreenObject';                   // Name it so we can find it later
        tbody.appendChild(tnode);                            // Add it to the web page
        dark=document.getElementById('darkenScreenObject');  // Get the object.
      }
      if (vis) { 
        
    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 if (document.documentElement && document.documentElement.scrollHeight > document.documentElement.offsetHeight){ // Explorer 6 strict mode
		xScroll = document.documentElement.scrollWidth;
		yScroll = document.documentElement.scrollHeight;
	} else { // Explorer Mac...would also work in Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	pageWidth = xScroll;
	pageHeight = yScroll;
	
	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;
	}	
        
        
        
        //set the shader to cover the entire page and make it visible.
        dark.style.opacity=opaque;                      
        dark.style.MozOpacity=opaque;                   
        dark.style.filter='alpha(opacity='+opacity+')'; 
        dark.style.zIndex=zindex;        
        dark.style.backgroundColor=bgcolor;  
        dark.style.width= pageWidth + 'px';
        dark.style.height= pageHeight + 'px';
        dark.style.display='block';                          
      } else {
         dark.style.display='none';
      }
}

function openDHTMLDivWindow(id, title, div_name, width, height, left, top, gray_out)
{
    grayOut(true);
    ajaxwin=dhtmlwindow.open(id, "div", div_name, title, "width="+width+"px,height="+height+"px,left="+left+"px,top="+top+"px,resize=0,scrolling=0");
}

function IsANumber(x)
{
    var anum=/(^\d+$)|(^\d+\.\d+$)/
    if (anum.test(x))
        return true;
    else{
        return false;
    }
}

function GetAspFieldValue(id)
{
    var element_array = Form.getElements('form1');
    var len = element_array.length;
    var namestring = " ";
           
    for(var i=0; i < len; i++)
    {
        var element = Form.getElements('form1')[i];
        var var_len = element.length;
        
        namestring = namestring + " " + element.name;
    
        if(element.name.search(id) != -1)
        {
            return element.value;
        }
    }
    
    return "";
}
function GetAspField(id)
{
    var element_array = Form.getElements('form1');
    var len = element_array.length;
           
    for(var i=0; i < len; i++)
    {
        var element = Form.getElements('form1')[i];
        var var_len = element.length;
    
        if(element.id.search(id) != -1)
        {
            return element;
        }
    }
    
    return "";
}
//get the asp field by id and class
function GetAspFieldByClass(id,className)
{  
    var field = null;
    $$(className).each(
            function(element)
            {
                if(element.id.search(id) != -1)
                {
                    field = element;
                    $break;
                }
           }
         )        
    return field;
} 
function GetAspFieldId(id)
{
    var element_array = Form.getElements('form1');
    var len = element_array.length;
    var namestring = " ";
           
    for(var i=0; i < len; i++)
    {
        var element = Form.getElements('form1')[i];
        var var_len = element.length;
        
        namestring = namestring + " " + element.name;
    
        if(element.name.search(id) != -1)
        {
            return element.id;
        }
    }
    
    return "";
} 
function isIE6() {
	var appVer = navigator.appVersion;
	appVer = appVer.split(';');
	if(appVer[1] == ' MSIE 6.0') {
		return true;
	}				
}

function updateOptions(option_title,chosen_option,initial_load)
{
	$(option_title + '_loading').toggle()
	var options_string = GetAspFieldByClass(option_title.toLowerCase() + "_" + chosen_option.replace(' ','_').toLowerCase(),"input").value;

	var options = options_string.split("|");

	for(var j=0; j<options.length; j++)
	{
		var opt_str = options[j];
	    var option_values = opt_str.split(":");

	    var option = option_values[0];
	    var values = option_values[1].split(",");

	    var select = GetAspFieldByClass(option,"select.option_Dropdown");
	    var selectedIndex = select.selectedIndex;
	    //we don't want to preseve the selection if this is a change in color, only if it's a postback
	    var preserveSelection = false;
        //if select.innerHTML.indexOf('selected') > -1 then something other than Select... was chosen
    	if(initial_load && select.innerHTML.indexOf('selected') > -1)
        {
            preserveSelection = true;
        }
	    select.descendants().each(Element.remove); 
        
        var newOption = document.createElement('option');
	    newOption.text = "Select...";
	    newOption.value = "Select";

		try
		{
		  select.add(newOption, select.options[select.length]); // standards compliant; doesnt work in IE
		}
		catch(ex) {
		  select.add(newOption, select.length); // IE only
		}	    

	    for(var i=0; i< values.length; i++)
	    {
	    	var value = values[i];

	    	var newOption = document.createElement('option');
	    	newOption.text = value;
	    	newOption.value = value;


			try
			{
			  select.add(newOption, select.options[select.length]); // standards compliant; doesnt work in IE
			}
			catch(ex) {
			  select.add(newOption, select.length); // IE only
			}

	    	/*
			var newOption = new Option(value, value);
	    	$(option).options[$(option)length];*/
	    }
	    
	    if(preserveSelection)
        {
           select.selectedIndex = selectedIndex + 1;
	    }

	}
    setTimeout("$('" + option_title + "_loading').toggle()",500);
}
function getComputedHeight(theElt){
        var browserName=navigator.appName;
         if (browserName=="Microsoft Internet Explorer"){
                var is_ie=true;
         } else {
                var is_ie=false;
         }
        if(is_ie){
                tmphght = $(theElt).offsetHeight;
        }
        else{
                docObj = $(theElt);
                var tmphght1 = document.defaultView.getComputedStyle(docObj, "").getPropertyValue("height");
                tmphght = tmphght1.split('px');
                tmphght = tmphght[0];
        }
        return tmphght;
}

function isDefined(varname)
{
    if ( typeof( window[ varname ] ) != "undefined" ) {
       return true;
    } 
    else {
       return false;
    }
}

function isFunction(name)
{
    if(typeof name == 'function') { 
        return true;
    }
    return false;
}

function addMailingList(email,panel,image) {
    if($F(email) != ''){
        panelToChange = panel;
        
        Element.hide(image);
        //new Insertion.Top(panel, '<div id="adding" style="width:100%;text-decoration: blink;text-align:right;">Adding...</div>');
        new Insertion.Top(panel, '<span id="adding" style="width:100%;text-decoration: blink;text-align:right;">Adding...</span>');
        var url = 'process.aspx';
        var params = 'type=mailinglist&email=' + $F(email);
        try
        {
            var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: addMailingListResult });
        }
        catch(exc)
        {
            Element.show($('emailError'));
        }
    }
    else
    {
        Element.show($('emailError'));
    }
}

function addMailingListResult(result){
    Element.hide('adding');
    if(result.responseText == "True")
    {
        new Insertion.Top(panelToChange, '<span id="result" style="width:100%;text-align:right;">Email Successfully Added</span>');        
    }
    else{
        new Insertion.Top(panelToChange, '<span id="result" style="width:100%;text-align:right;">You are already on our mailing list.</span>');        
    }    
}


function addDiscountMailingList(email,panel,image,errorpanel) {
    if($F(email) != ''){
        panelToChange = panel;
        
        Element.hide(image);
        //new Insertion.Top(panel, '<div id="adding" style="width:100%;text-decoration: blink;text-align:right;">Adding...</div>');
        new Insertion.Top(panel, '<span id="adding" style="width:100%;text-decoration: blink;text-align:right;">Adding...</span>');
        var url = 'process.aspx';
        var params = 'type=discountmailinglist&email=' + $F(email);
        try
        {
            var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: addDiscountMailingListResult });
        }
        catch(exc)
        {
            Element.show(errorpanel);
        }
    }
    else
    {
        Element.show(errorpanel);
    }
}

function addDiscountMailingListResult(result){
    Element.hide('adding');
    if(result.responseText.indexOf("True") > -1)
    {
        new Insertion.Top(panelToChange, '<span id="result" style="width:100%;text-align:right;"> Thanks. Your coupon will be sent by email.</span>');        
    }
    else{
        new Insertion.Top(panelToChange, '<span id="result" style="width:100%;text-align:right;"> You are already on our mailing list.</span>');        
    }    
}


function sendLostPasswdByNameEmail(username,email,panel,image) {
    if($F(username) != '' || $F(email) != ''){
        panelToChange = panel;
        
        //new Insertion.Top(panel, '<div id="adding" style="width:100%;text-decoration: blink;text-align:right;">Adding...</div>');
        $(panelToChange).innerHTML = '';
        new Insertion.Top(panel, '<span id="adding" style="width:100%;text-decoration: blink;text-align:right;">Sending...</span>');
        var url = 'process.aspx';
        var params = 'type=lostpassword&email='+$F(email)+'&username=' + $F(username);

        var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: lostPasswdResult });
    }
    else{
        Element.show($('passwdSentFailure'));
    }
}

function sendLostPasswd(username,panel,image) {
    if($F(username) != ''){
        panelToChange = panel;
        
        //new Insertion.Top(panel, '<div id="adding" style="width:100%;text-decoration: blink;text-align:right;">Adding...</div>');
        $(panelToChange).innerHTML = '';
        new Insertion.Top(panel, '<span id="adding" style="width:100%;text-decoration: blink;text-align:right;">Sending...</span>');
        var url = 'process.aspx';
        var params = 'type=lostpassword&username=' + $F(username);

        var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: lostPasswdResult });
    }
    else{
        Element.show($('passwdSentFailure'));
    }
}

function lostPasswdResult(result){
    if(result.responseText == "True")
    {
        $(panelToChange).innerHTML = '';
        new Insertion.Top(panelToChange, '<span id="result" style="width:100%;text-align:right;">Your password has been sent to your email account.</span>');        
    }
    else{
        $(panelToChange).innerHTML = '';
        new Insertion.Top(panelToChange, '<span id="result" style="width:100%;text-align:right;">Your email address cannot be retrieved. For more help, please contact Customer Support.</span>');        
    }    
}

function removeMailingList(panel,image,email) {
    if($F(email) != ''){
        $('unsubscribeMessage').style.textDecoration = "blink";
        Element.update( $('unsubscribeMessage'), "Unsubscribing...")

        var url = 'process.aspx';
        var params = 'type=removemailinglist&email=' + $F(email);

        var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: removeMailingListResult });
        Element.hide('unsubscribe_email_error');
    }
    else{
        Element.show($('unsubscribe_email_error'));
    }
}

function removeMailingListResult(result){
    $('unsubscribeMessage').style.textDecoration = "none";
    if(result.responseText == "True")
    {
        Element.update( $('unsubscribeMessage'), "Email Unsubscribe Successful")
    }
    else{
        Element.update( $('unsubscribeMessage'), "Email address not found")
    }    
}

function askAQuestion(panel,button,question,email,name,subject,skuLink) {
    if($F(question) != '' && $F(email) != ''){
        panelToChange = panel;
        Element.hide(button);
        
        new Insertion.Top(panel, '<div id="sendingQuestion" style="width:100%;text-decoration: blink;text-align:right;">Sending...</div>');
        var url = 'process.aspx';
        var params = 'type=question&email=' + $F(email) + '&question=' + $F(question) + '<br>' + skuLink + '&name=' + $F(name) + '&subject=' + subject;

        var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: askAQuestionResult });
        $(question).value = '';
        $(email).value = '';
        $(name).value = '';
    }
    else{
        if($F(question) == ''){
            $(question + '_error').style.display = 'inline';
        }
        else{
            $(question + '_error').style.display = 'none';
        }
        if($F(email) == ''){
            $(email + '_error').style.display = 'inline';
        }        
        else{
            $(email + '_error').style.display = 'none';
        }        
    }
}

function requestPasswordEmail(panel,button,email,first_name,last_name,company,zip,other) {
    if($F(email) != ''){
        panelToChange = panel;
        Element.hide(button);
        
        new Insertion.Top(panel, '<div id="sendingQuestion" style="width:100%;text-decoration: blink;text-align:right;">Sending...</div>');
        var url = 'process.aspx';
        var params = 'type=passwordEmail&email=' + $F(email) + '&first_name=' + $F(first_name) + '&last_name=' + $F(last_name) + '&company=' + $F(company) + '&zip=' + $F(zip) + '&other=' + $F(other);

        var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: passwordEmailResult });
        $(email).value = '';
        $(first_name).value = '';
        $(last_name).value = '';
        $(company).value = '';
        $(zip).value = '';
        $(other).value = '';
    }
    else{
        if($F(email) == ''){
            $(email + '_error').style.display = 'inline';
        }        
        else{
            $(email + '_error').style.display = 'none';
        }        
    }
}

function askAQuestionResult(result){
    Element.hide('sendingQuestion');
    if(result.responseText == "True")
    {
        new Insertion.Top(panelToChange, '<div id="result" style="width:100%;text-align:right;">Thank you. Your question has been sent.</div>');        
    }
    else{
        new Insertion.Top(panelToChange, '<div id="result" style="width:100%;text-align:right;">There was an error sending your question.</div>');        
    }        
}

function passwordEmailResult(result){
    Element.hide('sendingQuestion');
    if(result.responseText == "True")
    {
        new Insertion.Top(panelToChange, '<div id="result" style="width:100%;text-align:right;color:red;">Thank you. Your request has been sent.</div>');        
    }
    else{
        new Insertion.Top(panelToChange, '<div id="result" style="width:100%;text-align:right;color:red;">There was an error sending your request.</div>');        
    }        
}

function tellAFriend(panel,button,message,your_email,your_name,their_email,title,sku) {
    if($F(message) != '' && $F(your_email) != '' && $F(their_email) != ''){
        var emailSubject;
        emailSubject = $F(your_name) + ' wants you to know about the ' + title;
        panelToChange = panel;
        Element.hide(button);
        new Insertion.Top(panel, '<div id="sendingQuestion" style="width:100%;text-decoration: blink;text-align:right;">Sending...</div>');
        var url = 'process.aspx';
        var params = 'type=tell&your_email=' + $F(your_email) + '&message=' + $F(message) + '&your_name=' + $F(your_name) + '&their_email=' + $F(their_email)  + '&subject=' + emailSubject + '&sku=' + sku + '&title=' + title;

        var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: tellAFriendResult });
        $(message).value = '';
        $(your_email).value = '';
        $(your_name).value = '';
        $(their_email).value = '';        
    }
    else{
        if($F(message) == ''){
            $(message + '_error').style.display = 'inline';
        }
        else{
            $(message + '_error').style.display = 'none';
        }
        
        if($F(your_email) == ''){
            $(your_email + '_error').style.display = 'inline';
        }        
        else{
            $(your_email + '_error').style.display = 'none';
        } 
        
        if($F(their_email) == ''){
            $(their_email + '_error').style.display = 'inline';
        }        
        else{
            $(their_email + '_error').style.display = 'none';
        }                
    }
}

function getFraudScore(order_number, min_score) //min_score will come from web config
{
    var url = 'process.aspx';
    var params = 'type=getFraudScore';
    //riskSocre is now returned from process - YH 4/15/10
    var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: fraudScoreResult });
}

function fraudScoreResult(result)
{
    RunVerification(result.responseText);
}

function expandVerificationAddress(section_name)
{
    if($(section_name).style.display == 'none')
    {
        $(section_name).style.display = 'block';
        $('addressTable').style.display = 'block';
    }
    else
    {
        $(section_name).style.display = 'none';
    }
    
    if($('shippingAddress').style.display=='none' && $('billingAddress').style.display=='none')
    {
        $('addressTable').style.display = 'none';
    }
    return false;
}

function SubmitVerification(site_id, user_id, order_number)
{
    if( ValidateVerificationFields() )
    {
        var url = 'process.aspx';
        var params = 'type=verification'+($('sFirstName') != null ? "&sFname="+$F('sFirstName')+"&sLname="+$F('sLastName')+"&sAddress1="+ encodeURIComponent($F('sAddress1'))+
                       "&sAddress2="+ encodeURIComponent($F('sAddress2'))+"&sCompany="+$F("sCompany")+"&sZip="+$F("sZip")+"&sCity="+$F("sCity")+
                       "&sState="+(GetAspFieldValue("ShippingCountry")=='US' ? GetAspFieldValue("ShippingState") : $F("sState"))+"&sCountry="+GetAspFieldValue("ShippingCountry")+'&bFname='+$F('bFirstName')+"&bLname="+$F('bLastName')+
                       "&bAddress1="+encodeURIComponent($F('bAddress1'))+"&bAddress2="+encodeURIComponent($F('bAddress2'))+"&bCompany="+$F("bCompany")+"&bZip="+$F("bZip")+"&bCity="+$F("bCity")+
                       "&bState="+(GetAspFieldValue("BillingCountry")=='US' ? GetAspFieldValue("BillingState") : $F("bState"))+"&bCountry="+GetAspFieldValue("BillingCountry") : "")+
                       ($("bankName")!=null? "&bankName="+$F("bankName") : "" )+($('bankPhone')!=null ? "&bankPhone="+$F("bankPhone") : "")+
                       ($("b1FirstName")==null ? "" : "&b1Fname="+$F("b1FirstName")+"&b1Lname="+$F("b1LastName")+"&b1Address1="+encodeURIComponent($F("b1Address1"))+"&b1Address2="+ encodeURIComponent($F("b1Address2")) +
                       "&b1Company="+$F("b1Company")+"&b1City="+$F("b1City")+"&b1State="+(GetAspFieldValue("Billing1Country")=='US' ? GetAspFieldValue("Billing1State") : $F("b1State"))+"&b1Zip="+$F("b1Zip")+"&b1Country="+GetAspFieldValue("Billing1Country"));

        var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: verificationResult });
    }
}

function ValidateVerificationFields()
{
    passes_validation = true;
    filled_in = false;

    try{
        if($('sAddress1')!=null)
        {
            if($F('sAddress1')!="" || $F('sZip')!="" || $F('sCity')!="")
            {
                if($F('sFirstName')=="") { $('sFirstNameLabel').style.color="red"; passes_validation = false; } else { $('sFirstNameLabel').style.color="black"; } 
                if($F('sLastName')=="") { $('sLastNameLabel').style.color="red"; passes_validation = false; } else { $('sLastNameLabel').style.color="black";} 
                if($F('sAddress1')=="") { $('sAddress1Label').style.color="red"; passes_validation = false; } else { $('sAddress1Label').style.color="black";} 
                if($F('sCity')=="") { $('sCityLabel').style.color="red"; passes_validation = false; } else { $('sCityLabel').style.color="black";} 
                if($F('sZip')=="") { $('sZipLabel').style.color="red"; passes_validation = false; } else { $('sZipLabel').style.color="black";} 
                if($F('sState')=="" && GetAspFieldValue("ShippingCountry")!='US') { $('sStateLabel').style.color="red"; passes_validation = false; } else { $('sStateLabel').style.color="black";} 
                filled_in = true;
            }
        }
        
        if($('bAddress1')!=null)
        {
            if($F('bAddress1')!="" || $F('bZip')!="" || $F('bCity')!="")
            {
                if($F('bFirstName')=="") { $('bFirstNameLabel').style.color="red"; passes_validation = false; } else { $('bFirstNameLabel').style.color="black"; } 
                if($F('bLastName')=="") { $('bLastNameLabel').style.color="red"; passes_validation = false; } else { $('bLastNameLabel').style.color="black";} 
                if($F('bAddress1')=="") { $('bAddress1Label').style.color="red"; passes_validation = false; } else { $('bAddress1Label').style.color="black";} 
                if($F('bCity')=="") { $('bCityLabel').style.color="red"; passes_validation = false; } else { $('bCityLabel').style.color="black";} 
                if($F('bZip')=="") { $('bZipLabel').style.color="red"; passes_validation = false; } else { $('bZipLabel').style.color="black";} 
                if($F('bState')=="" && GetAspFieldValue("BillingCountry")!='US') { $('bStateLabel').style.color="red"; passes_validation = false; } else { $('bStateLabel').style.color="black";} 
                filled_in = true;
            }
        }
        
        if($('b1Address1')!=null)
        {
            if($F('b1Address1')!="" || $F('b1Zip')!="" || $F('b1City')!="")
            {
                if($F('b1FirstName')=="") { $('b1FirstNameLabel').style.color="red"; passes_validation = false; } else { $('b1FirstNameLabel').style.color="black"; } 
                if($F('b1LastName')=="") { $('b1LastNameLabel').style.color="red"; passes_validation = false; } else { $('b1LastNameLabel').style.color="black";} 
                if($F('b1Address1')=="") { $('b1Address1Label').style.color="red"; passes_validation = false; } else { $('b1Address1Label').style.color="black";} 
                if($F('b1City')=="") { $('b1CityLabel').style.color="red"; passes_validation = false; } else { $('b1CityLabel').style.color="black";} 
                if($F('b1Zip')=="") { $('b1ZipLabel').style.color="red"; passes_validation = false; } else { $('b1ZipLabel').style.color="black";} 
                if($F('b1State')=="" && GetAspFieldValue("Billing1Country")!='US') { $('b1StateLabel').style.color="red"; passes_validation = false; } else { $('b1StateLabel').style.color="black";} 
                filled_in = true;
            }
        }
        
        if($('bankName')!=null)
        {
            if($F("bankName")!="" || $F("bankPhone")!="")
            {
                $("bankNameLabel").style.color="black";
                $("bankPhoneLabel").style.color=="black";
                filled_in = true;
            }
        }
    }catch(exc) 
    {
    }
    
    if(filled_in && !passes_validation)
    {
        $('v_nothing_entered').style.display = 'none'; 
        $("v_err_msg").style.display = "inline"; 
    }
    else if(!filled_in)
    {
        $('v_nothing_entered').style.display = 'inline'; 
        $("v_err_msg").style.display = "none"; 
        passes_validation = false;
    }
    else
    {
        $('v_nothing_entered').style.display = 'none'; 
        $("v_err_msg").style.display = "none"; 
    }
    
    /*
    if(passes_validation)
    { 
        $("v_err_msg").style.display = "none"; 
    } 
    else 
    { 
        $("v_err_msg").style.display = "inline"; 
    } 
    
    if(!filled_in)
    {
        $('v_nothing_entered').style.display = 'inline'; 
        passes_validation = false;
    }
    else if(filled_in && passes_validation)
    {
        $('v_nothing_entered').style.display = 'none'; 
    }
    
    
  /*  if($('bAddress1')!=null)
    {
        if($F('bAddress1')=="" && $F('bZip')=="" && $F('sAddress1')=="" && $F('sZip')=="") 
        { 
            if($("bankPhone") !=null)
            {
                if($F("bankName")=="" && $F("bankPhone")=="")
                {
                    if($("b1Address1")==null)
                    {
                        $('v_nothing_entered').style.display = 'inline'; 
                        passes_validation = false;
                    }
                    else
                    {
                        if($F("b1Address1")=="" && $F("b1City")=="" && $F("b1Zip")=="")
                        {
                            $('v_nothing_entered').style.display = 'inline'; 
                            passes_validation = false;
                        }
                    }
                }
            }
            else if($("b1Address1")!=null)
            {
                if($F("b1Address1")=="" && $F("b1City")=="" && $F("b1Zip")=="")
                {
                    $('v_nothing_entered').style.display = 'inline'; 
                    passes_validation = false;
                }
            }
            else
            {
                $('v_nothing_entered').style.display = 'inline'; 
                passes_validation = false;
            }
        }
    }
    else if($("bankPhone") !=null)
    {        
        if($("b1Address1")==null)
        {
            if($F("b1Address1")=="" && $F("b1City")=="" && $F("b1Zip")=="")
            {
                $('v_nothing_entered').style.display = 'inline'; 
                passes_validation = false;
            }
        }
        else if($F("bankName")=="" && $F("bankPhone")=="")
        {
            $('v_nothing_entered').style.display = 'inline'; 
            passes_validation = false;
        }
    }
    else
    {
        $('v_nothing_entered').style.display = 'none';  
    }*/
    
    return passes_validation;
}

function verificationResult()
{
    $("verificationContent").innerHTML = "<table width='660' height='420'><tr><td align='center' valign='middle'><font color='red' size='+1'>Thank you. Your updates have been processed.</font><br><br><br><font size='+1'> We will contact you if any further information is needed.</font><br><br><br><a href='javascript:void(0);' onclick='window.parent.ajaxwin.close();'><u>Close Window</u></a></td></tr></table>";
}

function tellAFriendResult(result){
    Element.hide('sendingQuestion');
    if(result.responseText == "True")
    {
        new Insertion.Top(panelToChange, '<div id="result" style="width:100%;text-align:right;">Thank you. Your email has been sent.</div>');        
    }
    else{
        new Insertion.Top(panelToChange, '<div id="result" style="width:100%;text-align:right;">There was an error sending your email.</div>');        
    }        
}

function suggestProduct(panel,button,comment,email,name,subject,page,site_id) {
    if($F(comment) != '' && $F(email) != '' && $F(name) != ''){
        panelToChange = panel;
        Element.hide(button);
        
        new Insertion.Top(panel, '<div id="sendingComments" style="width:100%;text-align:right;text-decoration: blink;">Sending...</div>');
        var url = 'process.aspx';
        var params = 'type=suggestProduct&email=' + $F(email) + '&comment=' + $F(comment) + '&name=' + $F(name) + '&subject=' + subject+'&page='+page+'&site_id='+site_id;

        var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: suggestProductResult });
        $(comment).value = '';
        $(email).value = '';
        $(name).value = '';
    }
    else{
        if($F(comment) == ''){
            $(comment + '_error').style.display = 'inline';
        }
        else{
            $(comment + '_error').style.display = 'none';
        }
        if($F(email) == ''){
            $(email + '_error').style.display = 'inline';
        }        
        else{
            $(email + '_error').style.display = 'none';
        } 
        if($F(name) == ''){
            $(name + '_error').style.display = 'inline';
        }        
        else{
            $(name + '_error').style.display = 'none';
        }         
    }
}

function suggestProductResult(result){
    Element.hide('sendingComments');
    if(result.responseText == "True")
    {
        new Insertion.Top(panelToChange, '<div id="result" style="width:100%;text-align:right;">Thank you. Your comments have been sent.</div>');        
    }
    else{
        new Insertion.Top(panelToChange, '<div id="result" style="width:100%;text-align:right;">There was an error sending your comments.</div>');        
    }        
}

function tellUs(panel,button,comment,email,name,subject,page,site_id) {
    if($F(comment) != '' && $F(email) != '' && $F(name) != ''){
        panelToChange = panel;
        Element.hide(button);
        
        new Insertion.Top(panel, '<div id="sendingComments" style="width:100%;text-decoration: blink;text-align:right;">Sending...</div>');
        var url = 'process.aspx';
        var params = 'type=tellus&email=' + $F(email) + '&comment=' + $F(comment) + '&name=' + $F(name) + '&subject=' + subject+'&page='+page+'&site_id='+site_id;

        var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: tellUsResult });
        $(comment).value = '';
        $(email).value = '';
        $(name).value = '';
    }
    else{
        if($F(comment) == ''){
            $(comment + '_error').style.display = 'inline';
        }
        else{
            $(comment + '_error').style.display = 'none';
        }
        if($F(email) == ''){
            $(email + '_error').style.display = 'inline';
        }        
        else{
            $(email + '_error').style.display = 'none';
        } 
        if($F(name) == ''){
            $(name + '_error').style.display = 'inline';
        }        
        else{
            $(name + '_error').style.display = 'none';
        }         
    }
}

function tellUsResult(result){
    Element.hide('sendingComments');
    if(result.responseText == "True")
    {
        new Insertion.Top(panelToChange, '<div id="result" style="width:100%;text-align:right;">Thank you. Your comments have been sent.</div>');        
    }
    else{
        new Insertion.Top(panelToChange, '<div id="result" style="width:100%;text-align:right;">There was an error sending your comments.</div>');        
    }        
}



    function fill_form(id, firstname, lastname, address1, address2, company, city, state, country, zip, dayphone, nightphone, fax,use_this)
    {
        var element_array = Form.getElements('form1');
        var len = element_array.length;
        var namestring = " ";
        var stateTextBoxId = "";
        //if use_this is 1, then the customer choose an address, else they didn't
        
        //$("address_id").value = id;        
        for(var i=0; i < len; i++)
        {
            var element = Form.getElements('form1')[i];
            var var_len = element.length;
            
            namestring = namestring + " " + element.name;
        
            if(element.name.search("FirstNameTextbox") != -1)
            {
                element.value=firstname;
                if(use_this == 1){
                    element.readOnly="readOnly";
                }
                continue;
            }
            
            if(element.name.search("LastNameTextbox") != -1)
            {
                element.value=lastname;
                if(use_this == 1){
                    element.readOnly="readOnly";
                }
                continue;
            }
            
            if(element.name.search("Address1Textbox") != -1)
            {
                element.value=address1;
                if(use_this == 1){
                    element.readOnly="readOnly";

                }
                continue;
            }
            
            if(element.name.search("CompanyTextbox") != -1)
            {
                element.value=company;
                if(use_this == 1){
                    element.readOnly="readOnly";

                }
                continue;
            }
            
            if(element.name.search("Address2Textbox") != -1)
            {
                element.value=address2;
                if(use_this == 1){
                    element.readOnly="readOnly";

                }
                continue;
            }
            
            if(element.name.search("CityTextbox") != -1)
            {
                element.value=city;
                if(use_this == 1){
                    element.readOnly="readOnly";

                }
                continue;
            }
            
            if(element.name.search("StateDropDown") != -1)
            {
                element.value = state;
                if(use_this == 1){
                    element.readOnly="readOnly";
                    Element.hide("StateDropdownDiv");                
                    Element.show("StateTextboxDiv");                   

                }
                continue;
            }
            
            if(element.name.search("StateTextbox") != -1)
            {
                stateTextBoxId = element.id;
                element.value=state;
                if(use_this == 1){
                    element.readOnly="readOnly";

                }
                continue;
            }
            
            if(element.name.search("CountryCodeDropDownList") != -1)
            {
                element.value = country;
                if(use_this == 1){
                    Element.hide("CountryDropdownDiv");                
                    Element.show("CountryTextboxDiv");                
                    element.readOnly="readOnly";

                }
                continue;
            }
            
            if(element.name.search("ZipTextbox") != -1)
            {
                element.value=zip;
                if(use_this == 1){
                    element.readOnly="readOnly";

                }
                continue;
            }
            
            if(element.name.search("DayPhoneTextbox") != -1)
            {
                element.value=dayphone;
                if(use_this == 1){
                    element.readOnly="readOnly";

                }
                continue;
            }
            
            if(element.name.search("NightPhoneTextbox") != -1)
            {
                element.value=nightphone;
                if(use_this == 1){
                    element.readOnly="readOnly";

                }
                continue;
            }
            
            if(element.name.search("FaxTextbox") != -1)
            {
                element.value=fax;
                if(use_this == 1){
                    element.readOnly="readOnly";

                }
                continue;
            }                   
        }     
        
        
        if(use_this == 1){                 
            $('StateTextboxDiv').innerHTML = "<input type=text name='StateTextbox' id='" + stateTextBoxId + "' maxlength='128' value=" + state + "></input>";
            $(stateTextBoxId).readOnly="readOnly";
        }
        
        
        if(use_this == 1){  
            $('CountryTextboxDiv').innerHTML = "<input type=text name='CountryTextbox' id='CountryTextbox' value=" + country + "></input>";
            $("CountryTextbox").readOnly="readOnly";
            Element.show("CreateNewAddressDiv"); 
            if($('SaveToMyAddressBook') != null)
            {
                Element.hide("SaveToMyAddressBook"); 
            }
        }        
    }     
    
    function allow_new_form()
    {
        var element_array = Form.getElements('form1');
        var len = element_array.length;
        var namestring = " ";
        
        $("address_id").value = -1;
        $("use_this").value = 0;
         
        for(var i=0; i < len; i++)
        {
            var element = Form.getElements('form1')[i];
            var var_len = element.length;
            
            namestring = namestring + " " + element.name;
        
            if(element.name.search("FirstNameTextbox") != -1)
            {
                element.readOnly="";

                element.value = '';
                continue;
            }
            
            if(element.name.search("LastNameTextbox") != -1)
            {
                element.readOnly="";

                element.value = '';
                continue;
            }
            
            if(element.name.search("Address1Textbox") != -1)
            {
                element.readOnly="";

                element.value = '';
                continue;
            }
            
            if(element.name.search("CompanyTextbox") != -1)
            {
                element.readOnly="";

                element.value = '';
                continue;
            }
            
            if(element.name.search("Address2Textbox") != -1)
            {
                element.readOnly="";

                element.value = '';
                continue;
            }
            
            if(element.name.search("CityTextbox") != -1)
            {
                element.readOnly="";

                element.value = '';
                continue;
            }
            
            if(element.name.search("StateDropDown") != -1)
            {                
                Element.show("StateDropdownDiv");
                Element.show(element);
                element.readOnly="";

                continue;
            }
            
            if(element.name.search("StateTextbox") != -1)
            {
                element.readOnly="";
                element.value = '';
                continue;
            }
            
            if(element.name.search("CountryCodeDropDownList") != -1)
            {                
                element.value = "US";
                Element.show("CountryDropdownDiv");
                element.readOnly="";

                continue;
            }
            
            if(element.name.search("ZipTextbox") != -1)
            {
                element.readOnly="";

                element.value = '';
                continue;
            }
            
            if(element.name.search("DayPhoneTextbox") != -1)
            {
                element.readOnly="";

                element.value = '';
                continue;
            }
            
            if(element.name.search("NightPhoneTextbox") != -1)
            {
                element.readOnly="";

                element.value = '';
                continue;
            }
            
            if(element.name.search("FaxTextbox") != -1)
            {
                element.readOnly="";

                element.value = '';
                continue;
            }
         
        }   
        $('CountryTextboxDiv').innerHTML = "";
        $('StateTextboxDiv').innerHTML = "";
        Element.hide("CreateNewAddressDiv");         
        if($('SaveToMyAddressBook') != null)
        {
            Element.show("SaveToMyAddressBook"); 
        }
        if($('same_address_checkbox') != null)
        {
            $('same_address_checkbox').checked = false;
        }        
    }


    
function loadAjaxText()
{
	var dest = "www13.karatedepot.com/catalog/ajax_test.txt";

	try
	{
	
		if (window.XMLHttpRequest)     // Object of the current windows
		{
			xmlhttp = new XMLHttpRequest();     // Firefox, Safari, ...
		}
		else if (window.ActiveXObject)   // ActiveX version
		{
		       xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");    // Internet Explorer
		}
	
	}catch(e)
	{
		//no javascript
	}
	
	xmlhttp.onreadystatechange = triggered();
	xmlhttp.open("GET", dest, true);
	xmlhttp.send(null);
	
}

function triggered() {
	if (xmlhttp.readyState == 4) {
		document.getElementById("ajax_form").innerHTML = xmlhttp.responseText;
	}
}    
function updateAjaxDisplay()
{
	var pars = '';
	var url = "/sites/scripts/ajax_test.txt";

	var myAjax = new Ajax.Request(
			url,
			{
				method: 'get',
				parameters: pars,       
				onComplete: showResponse
			});
}

function showPopup(panel){
    Effect.Appear(panel,{ duration: .25});
} 

function hidePopup(panel){
    Effect.Fade(panel,{ duration: .25});
} 

function showResponse(originalRequest)
{
	//put returned XML in the textarea
	$('ajax_div').innerHTML = originalRequest.responseText;
}

String.prototype.toTitleCase = function() {
    //lowercase the whole string
    var ls = this.toLowerCase();
    //turn it into an array by splitting at spaces
    var la = ls.split(' ');
    //loop through word array
    for (var i = 0; i < la.length; i++ ) {
    //replace first letter with uppercase version
    la[i] = la[i].charAt(0).toUpperCase() + la[i].slice(1);
    }
    //rejoin words and return the new string
    return la.join(' ');
}

//check if function is an array
function isArray(obj) {
return (obj.constructor.toString().indexOf("Array") != -1);
}

function formatCurrency(num) {
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num))
    num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
    cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
    num = num.substring(0,num.length-(4*i+3))+','+
    num.substring(num.length-(4*i+3));
    return (((sign)?'':'-') + '$' + num + '.' + cents);
}

String.prototype.trim = function() 
{
	var l=0; 
	var r=this.length - 1;
	
	while(l < this.length && this[l] == ' ')
	{	l++; }
	
	while(r > l && this[r] == ' ')
	{	r-=1;	}
	
	return this.substring(l, r+1);
}

String.prototype.ltrim = function() 
{
	var l=0;
	while(l < s.length && this[l] == ' ')
	{	l++; }
	return this.substring(l, this.length);
}

String.prototype.rtrim = function() 
{
	var r=this.length -1;
	while(r > 0 && this[r] == ' ')
	{	r-=1;	}
	return s.substring(0, r+1);
}

function correctPNG() // correctly handle PNG transparency in Win IE 5.5 & 6.
{
   var arVersion = navigator.appVersion.split("MSIE")
   var version = parseFloat(arVersion[1])
   if ((version >= 5.5 && version < 7) && (document.body.filters)) 
   {
      for(var i=0; i<document.images.length; i++)
      {
         var img = document.images[i]
         var imgName = img.src.toUpperCase()
         if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
         {
            var imgID = (img.id) ? "id='" + img.id + "' " : ""
            var imgClass = (img.className) ? "class='" + img.className + "' " : ""
            var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
            var imgStyle = "display:inline-block;" + img.style.cssText 
            if (img.align == "left") imgStyle = "float:left;" + imgStyle
            if (img.align == "right") imgStyle = "float:right;" + imgStyle
            if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
            var strNewHTML = "<span " + imgID + imgClass + imgTitle
            + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";border:none;"
            + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
            + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
            img.outerHTML = strNewHTML
            i = i-1
         }
      }
   }    
}
if(navigator.appName == "Microsoft Internet Explorer"){
    window.attachEvent("onload", correctPNG);
}

function detectArrayItem(originalArray, itemToDetect) {
    for (var j=0; j < originalArray.length; j++) {
        if (originalArray[j] == itemToDetect) {
            return true;
        }
    }
    return false;
}

function removeArrayItem(originalArray, itemToRemove) {
    for (var j=0; j < originalArray.length; j++) {
        if (originalArray[j] == itemToRemove) {
            originalArray.splice(j,1);
        }
    }
    return originalArray;
}

function display_submenu(elmnt){
       
    if (ClickTaleIsIn("recording") && typeof ClickTaleExec == "function") {
		var elmntId = elmnt.id;
		if(elmntId) {
			ClickTaleExec("display_submenu(document.getElementById('" + elmntId + "'))");
		}
	}
         
	elmnt.childNodes[2].style.visibility='visible';
	elmnt.childNodes[2].style.left='auto';
	elmnt.className = 'w_d_down_hover';
	//alert(elmnt.childNodes[2].type)
}

function bhhag(elmnt){   
    if (ClickTaleIsIn("recording") && typeof ClickTaleExec == "function") {
		var elmntId = elmnt.id;
		if(elmntId) {
			ClickTaleExec("bhhag(document.getElementById('" + elmntId + "'))");
		}
	}
         
	elmnt.childNodes[2].style.left='-3000px';
	elmnt.childNodes[2].style.visibility='hidden';
	elmnt.className = 'w_d_down';
	//elmnt.className = elmnt.className.replace(' t_menu_selected', '');
}

//clears a field if there is a title and the current value does not equal the title
function ClearField(field)
{   
    if(field != null)
    {
        if(field.title != '' && field.value == field.title)
        {
            field.value = '';
        }
    }
}

//returns the default valueto a field (the title) if the field is empty and there is a title
function DefaultValue(field)
{
    if(field != null){
        if(field.title != '' && field.value == '')
        {
            field.value = field.title;
        }
    }
}

function luhn_check(s) {

  var i, n, c, r, t;

  // First, reverse the string and remove any non-numeric characters.

  r = "";
  for (i = 0; i < s.length; i++) {
    c = parseInt(s.charAt(i), 10);
    if (c >= 0 && c <= 9)
      r = c + r;
  }

  // Check for a bad string.

  if (r.length <= 1)
    return false;

  // Now run through each single digit to create a new string. Even digits
  // are multiplied by two, odd digits are left alone.

  t = "";
  for (i = 0; i < r.length; i++) {
    c = parseInt(r.charAt(i), 10);
    if (i % 2 != 0)
      c *= 2;
    t = t + c;
  }

  // Finally, add up all the single digits in this string.

  n = 0;
  for (i = 0; i < t.length; i++) {
    c = parseInt(t.charAt(i), 10);
    n = n + c;
  }

  // If the resulting sum is an even multiple of ten (but not zero), the
  // card number is good.

  if (n != 0 && n % 10 == 0)
    return true;
  else
    return false;
}

function isValidEmail(email) {

    var filter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
    if (!filter.test(email.value)) 
    {
        return false;
    }
    return true;    
}

// Changes the cursor to an hourglass
function waitcursor() {
document.body.style.cursor = 'wait';
}

// Returns the cursor to the default pointer
function clearcursor() {
document.body.style.cursor = 'default';
}
/*
function showInfoTip(title, innerHTML)
{
Tip(innerHTML, WIDTH, 300, TITLE, title, SHADOW, true, FADEIN, 300, FADEOUT, 300, STICKY, 1, CLOSEBTN, true, CLICKCLOSE, true)
}*/
function showInfoTip(title, innerHTML)
{    
    if(ClickTaleIsIn("recording") && (typeof ClickTaleExec == "function"))
         ClickTaleExec("showInfoTip('"+title+"', '"+innerHTML+"')");
         
    ajaxwin=dhtmlwindow.open("infoWin", "inline", innerHTML, title, "left=270px,top=220px,resize=1,scrolling=0");
    pageTracker._trackEvent('Info Tip', title);
}

function ShowLiveChat(id,pageTitle)
{
	window.open('http://www.fightsupport.net/livezilla/livezilla.php?intgroup=' + id + '=&hg=Pw__&reset=true','','width=590,height=550,left=0,top=0,resizable=yes,menubar=no,location=yes,status=yes,scrollbars=yes');
	pageTracker._trackEvent('Live Chat', pageTitle);
}

function showDiggThis(){
    var newWindow = window.open('http://digg.com/submit/?phase=2&url='+ encodeURIComponent(location.href) +'&title='+encodeURIComponent(document.title),'diggThis','location=no,menubar=no,toolbar=no,scrollbars=yes');
    newWindow.focus();
    return false;
} 

//gets selected radio from a list
//RT 5/26/2010
function GetSelectedRadio(name)
{
    var radioButtons = document.getElementsByName(name);
      for (var x = 0; x < radioButtons.length; x++) {
        if (radioButtons[x].checked) {
          return radioButtons[x];
        }
      }
      return "";
} 

// Clears the field is the value is equal to the defaulText (if specified)
//YH 5/26/10
function ClearIfDefault(element)
{
    if(element.attributes["defaultText"] != null)
    {
        var defaultText = element.attributes["defaultText"].value;
        if(element.value == defaultText)
        {
            element.value = '';
        }
    }
}

//cross-browser method for getting element that triggered the event. x is the event object
// RT 5/21/10
function getTarget(x){
    x = x || window.event;
    return x.target || x.srcElement;
} 

//gets URL parameter from a URL
function getUrlParam(url, name)
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( url );
  if( results == null )
    return "";
  else
    return results[1];
}

// function for preloading images... takes parameters of image paths
// RT 7/6/2010
function preloadImages() {
    for(var i=0; i<arguments.length; i++){
        var img = new Image();        // error image for validation
        img.src = arguments[i];
    }
}
// returns whether should perform clicktale action. should be used with clicktale functions to avoid error
// true if clicktale is loaded and in recording session, otherwise false
// RT 7/15/2010
function doClickTale() {
    if (typeof ClickTaleExec == "function") {
        if(ClickTaleIsIn("recording")) {
            return true;
        }
    } else {
        return false;
    }
}
//end /sites/scripts/common.js
//start /sites/scripts/clicktale.js
function ClickTaleIsIn (testFor) {
	var topLocation = top.location;
 
	if(testFor == "recording" && window.location == topLocation) {
		return true;
	} else if(testFor == "recording" || window.location == topLocation) {
		return false;
	}
 
	switch(testFor.toLowerCase()) {
	case "report":
		var fn = arguments.callee;
		return fn("scroll-heatmap") || fn("click-heatmap") || fn("form-analytics");
	case "scroll-heatmap":
		var regex = new RegExp("Heatmap.aspx\?", "i");
		return regex.test(topLocation);
	case "click-heatmap":
		var regex = new RegExp("ClickHeatMap.aspx\?", "i");
		return regex.test(topLocation);
	case "form-analytics":
		var regex = new RegExp("FormAnalytics.aspx\?", "i");
		return regex.test(topLocation);
	case "playback":
		var regex = new RegExp("Player.aspx\?", "i");
		return regex.test(topLocation);
	}
}

//end /sites/scripts/clicktale.js
//start /sites/scripts/json.js
/*
    json.js
    2007-04-30

    Public Domain

    This file adds these methods to JavaScript:

        array.toJSONString()
        boolean.toJSONString()
        date.toJSONString()
        number.toJSONString()
        object.toJSONString()
        string.toJSONString()
            These methods produce a JSON text from a JavaScript value.
            It must not contain any cyclical references. Illegal values
            will be excluded.

            The default conversion for dates is to an ISO string. You can
            add a toJSONString method to any date object to get a different
            representation.

        string.parseJSON(filter)
            This method parses a JSON text to produce an object or
            array. It can throw a SyntaxError exception.

            The optional filter parameter is a function which can filter and
            transform the results. It receives each of the keys and values, and
            its return value is used instead of the original value. If it
            returns what it received, then structure is not modified. If it
            returns undefined then the member is deleted.

            Example:

            // Parse the text. If a key contains the string 'date' then
            // convert the value to a date.

            myData = text.parseJSON(function (key, value) {
                return key.indexOf('date') >= 0 ? new Date(value) : value;
            });

    It is expected that these methods will formally become part of the
    JavaScript Programming Language in the Fourth Edition of the
    ECMAScript standard in 2008.

    This file will break programs with improper for..in loops. See
    http://yuiblog.com/blog/2006/09/26/for-in-intrigue/

    This is a reference implementation. You are free to copy, modify, or
    redistribute.

    Use your own copy. It is extremely unwise to load untrusted third party
    code into your pages.
*/

/*jslint evil: true */

// Augment the basic prototypes if they have not already been augmented.

if (!Object.prototype.toJSONString) {

    Array.prototype.toJSONString = function () {
        var a = ['['],  // The array holding the text fragments.
            b,          // A boolean indicating that a comma is required.
            i,          // Loop counter.
            l = this.length,
            v;          // The value to be stringified.

        function p(s) {

// p accumulates text fragments in an array. It inserts a comma before all
// except the first fragment.

            if (b) {
                a.push(',');
            }
            a.push(s);
            b = true;
        }

// For each value in this array...

        for (i = 0; i < l; i += 1) {
            v = this[i];
            switch (typeof v) {

// Serialize a JavaScript object value. Ignore objects thats lack the
// toJSONString method. Due to a specification error in ECMAScript,
// typeof null is 'object', so watch out for that case.

            case 'object':
                if (v) {
                    if (typeof v.toJSONString === 'function') {
                        p(v.toJSONString());
                    }
                } else {
                    p("null");
                }
                break;

// Otherwise, serialize the value.

            case 'string':
            case 'number':
            case 'boolean':
                p(v.toJSONString());

// Values without a JSON representation are ignored.

            }
        }

// Join all of the fragments together and return.

        a.push(']');
        return a.join('');
    };


    Boolean.prototype.toJSONString = function () {
        return String(this);
    };


    Date.prototype.toJSONString = function () {

// Ultimately, this method will be equivalent to the date.toISOString method.

        function f(n) {

// Format integers to have at least two digits.

            return n < 10 ? '0' + n : n;
        }

        return '"' + this.getFullYear() + '-' +
                f(this.getMonth() + 1) + '-' +
                f(this.getDate()) + 'T' +
                f(this.getHours()) + ':' +
                f(this.getMinutes()) + ':' +
                f(this.getSeconds()) + '"';
    };


    Number.prototype.toJSONString = function () {

// JSON numbers must be finite. Encode non-finite numbers as null.

        return isFinite(this) ? String(this) : "null";
    };


    Object.prototype.toJSONString = function () {
        var a = ['{'],  // The array holding the text fragments.
            b,          // A boolean indicating that a comma is required.
            k,          // The current key.
            v;          // The current value.

        function p(s) {

// p accumulates text fragment pairs in an array. It inserts a comma before all
// except the first fragment pair.

            if (b) {
                a.push(',');
            }
            a.push(k.toJSONString(), ':', s);
            b = true;
        }

// Iterate through all of the keys in the object, ignoring the proto chain.

        for (k in this) {
            if (this.hasOwnProperty(k)) {
                v = this[k];
                switch (typeof v) {

// Serialize a JavaScript object value. Ignore objects that lack the
// toJSONString method. Due to a specification error in ECMAScript,
// typeof null is 'object', so watch out for that case.

                case 'object':
                    if (v) {
                        if (typeof v.toJSONString === 'function') {
                            p(v.toJSONString());
                        }
                    } else {
                        p("null");
                    }
                    break;

                case 'string':
                case 'number':
                case 'boolean':
                    p(v.toJSONString());

// Values without a JSON representation are ignored.

                }
            }
        }

// Join all of the fragments together and return.

        a.push('}');
        return a.join('');
    };


    (function (s) {

// Augment String.prototype. We do this in an immediate anonymous function to
// avoid defining global variables.

// m is a table of character substitutions.

        var m = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        };


        s.parseJSON = function (filter) {
            var j;

            function walk(k, v) {
                var i;
                if (v && typeof v === 'object') {
                    for (i in v) {
                        if (v.hasOwnProperty(i)) {
                            v[i] = walk(i, v[i]);
                        }
                    }
                }
                return filter(k, v);
            }


// Parsing happens in three stages. In the first stage, we run the text against
// a regular expression which looks for non-JSON characters. We are especially
// concerned with '()' and 'new' because they can cause invocation, and '='
// because it can cause mutation. But just to be safe, we will reject all
// unexpected characters.

            if (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.
                    test(this)) {

// In the second stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

                try {
                    j = eval('(' + this + ')');
                } catch (e) {
                    throw new SyntaxError("parseJSON");
                }
            } else {
                throw new SyntaxError("parseJSON");
            }

// In the optional third stage, we recursively walk the new structure, passing
// each name/value pair to a filter function for possible transformation.

            if (typeof filter === 'function') {
                j = walk('', j);
            }
            return j;
        };


        s.toJSONString = function () {

// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can simply slap some quotes around it.
// Otherwise we must also replace the offending characters with safe
// sequences.

            if (/["\\\x00-\x1f]/.test(this)) {
                return '"' + this.replace(/([\x00-\x1f\\"])/g, function (a, b) {
                    var c = m[b];
                    if (c) {
                        return c;
                    }
                    c = b.charCodeAt();
                    return '\\u00' +
                        Math.floor(c / 16).toString(16) +
                        (c % 16).toString(16);
                }) + '"';
            }
            return '"' + this + '"';
        };
    })(String.prototype);
}
//end /sites/scripts/json.js
//start /sites/scripts/ibox.js
/**
 * iBox 2.2 (Build 1612)
 * For more info & download: http://www.ibegin.com/labs/ibox/
 * Created as a part of the iBegin Labs Project - http://www.ibegin.com/labs/
 * For licensing please see readme.html (MIT Open Source License)
*/
var iBox = function() {
	var _pub = {
		// label for the close link
		close_label: 'close',

		// show iframed content in the parent window
		// this *does not* work with #containers
		inherit_frames: false,

		// how fast to fade in the overlay/ibox (this is each step in ms)
		fade_in_speed: 300,
		fade_out_speed: 300,

		// our attribute identifier for our iBox elements
		attribute_name: 'rel',
		
		// tags to hide when we show our box
		tags_to_hide: ['select', 'embed', 'object'],

		// default width of the box (when displaying html only)
		// height is calculated automatically
		default_width: 450,

		// public version number
		version_number: '2.2',
		// internal build number
		build_number: '1612',

		// browser checks		
		is_opera: navigator.userAgent.indexOf('Opera/9') != -1,
		is_ie: navigator.userAgent.indexOf("MSIE ") != -1,
		is_ie6: false /*@cc_on || @_jscript_version < 5.7 @*/,
		is_firefox: navigator.appName == "Netscape" && navigator.userAgent.indexOf("Gecko") != -1 && navigator.userAgent.indexOf("Netscape") == -1,
		is_mac: navigator.userAgent.indexOf('Macintosh') != -1,

		// url for including images/external files
		base_url: '',
		
		/**
		 * Updates the base_url variable.
		 * @param {String} path Relative or absolute path to this file.
		 */
		setPath: function(path) {
			_pub.base_url = path;
		},
		
		/**
		 * Checks a container for specified tags containing rel="ibox"
		 * @param {Object} container
		 * @param {String} tag_name
		 */
		checkTags: function(container, tag_name) {
			if (!container) var container = document.body;
			if (!tag_name) var tag_name = 'a';
			var els = container.getElementsByTagName(tag_name);
			for (var i=0; i<els.length; i++) {
				if (els[i].getAttribute(_pub.attribute_name)) {
					var t = els[i].getAttribute(_pub.attribute_name);
					if ((t.indexOf("ibox") != -1) || t.toLowerCase() == "ibox") { // check if this element is an iBox element
						els[i].onclick = _pub.handleTag;
					}
				}
			}
		},
		
		/**
		 * Binds arguments to a callback function
		 */
		bind: function(fn) {
				var args = [];
				for (var n=1; n<arguments.length; n++) args.push(arguments[n]);
				return function(e) { return fn.apply(this, [e].concat(args)); };
		},

		/**
		 * Sets the content of the ibox
		 * @param {String} content HTML content
		 * @param {Object} params
		 */
		html: function(content, params) {
			if (content === undefined) return els.content;
			if (params === undefined) var params = {};
			if (!active.is_loaded) return;
			_pub.clear();

			_pub.updateObject(els.wrapper.style, {display: 'block', visibility: 'hidden', left: 0, top: 0, height: '', width: ''});
			
			if (typeof(content) == 'string') els.content.innerHTML = content;
			else els.content.appendChild(content);

			var pagesize = _pub.getPageSize();

			if (params.can_resize === undefined) params.can_resize = true;
			if (params.fade_in === undefined) params.use_fade = true;

			if (params.fullscreen) {
				params.width = '100%';
				params.height = '100%';
			}
			
			// reset offsets
			offset.container = [els.wrapper.offsetLeft*2, els.wrapper.offsetTop*2];
			offset.wrapper = [els.wrapper.offsetWidth-els.content.offsetWidth, els.wrapper.offsetHeight-els.content.offsetHeight];

			// TODO: remove the +4 when issue is solved with calculations
			offset.wrapper[1] += 4;

			if (params.width) var width = params.width;
			else var width = _pub.default_width;

			if (params.height) var height = params.height;
			else {
				els.content.style.height = '100%';
				var height = els.content.offsetHeight + 12;
				els.content.style.height = '';
			}
			active.dimensions = [width, height];
			active.params = params;
			_pub.reposition();

			// XXX: Fix for inline containers which had elements that were hidden
			for (var i=0; i<_pub.tags_to_hide.length; i++) {
				showTags(_pub.tags_to_hide[i], els.content);
			}

			els.wrapper.style.visibility = 'visible';
		},
		
		/**
		 * Empties the content of the iBox (also hides the loading indicator)
		 */
		clear: function() {
			els.loading.style.display = "none";
			while (els.content.firstChild) els.content.removeChild(els.content.firstChild);
		},
		
		/**
		 * Loads text into the ibox
		 * @param {String} text
		 * @param {String} title
		 * @param {Object} params
		 */
		show: function(text, title, params) {
			showInit(title, params, function() {
				_pub.html(text, active.params);
			});
		},
		/**
		 * Loads a url into the ibox
		 * @param {String} url
		 * @param {String} title
		 * @param {Object} params
		 */
		showURL: function(url, title, params) {
			showInit(title, params, function() {
				for (var i=0; i<_pub.plugins.list.length; i++) {
					var plugin = _pub.plugins.list[i];
					if (plugin.match(url)) {
						active.plugin = plugin;
						plugin.render(url, active.params);
						break;
					}
				}
			});
		},

		/**
		 * Hides the iBox
		 */
		hide: function() {
			if (active.plugin) {
				// call the plugins unload method
				if (active.plugin.unload) active.plugin.unload();
			}
			active = {}
			_pub.clear();
			// restore elements that were hidden
			for (var i=0; i<_pub.tags_to_hide.length; i++) showTags(_pub.tags_to_hide[i]);

			els.loading.style.display = 'none';
			els.wrapper.style.display = 'none';
			_pub.fade(els.overlay, _pub.getOpacity(null, els.overlay), 0, _pub.fade_out_speed, function() { els.overlay.style.display = 'none';});
			_pub.fireEvent('hide');
		},

		/**
		 * Repositions the iBox wrapper based on the params set originally.
		 */
		reposition: function() {
			if (!active.is_loaded) return;

			// center loading box
			if (els.loading.style.display != 'none') _pub.center(els.loading);
			
			// update ibox width/height/position
			if (active.dimensions) {
				var pagesize = _pub.getPageSize();

				var width = active.dimensions[0];
				var height = active.dimensions[1];
				
				if (height.toString().indexOf('%') != -1) {
					els.wrapper.style.height = (Math.max(document.documentElement.clientHeight, document.body.clientHeight, pagesize.height) - offset.container[0])*(parseInt(height)/100) + 'px';
				}
				else if (height) {
					els.content.style.height = height + 'px';
					// TODO: if we dont set wrapper height, it doesnt restrict the height and the box is fine
					// so offset.wrapper[1] must not be correct
					els.wrapper.style.height = els.content.offsetHeight + offset.wrapper[1] + 'px';
				}
				else {
					els.wrapper.style.height = els.content.offsetHeight + offset.wrapper[1] + 'px';
				}
				var container_offset = (els.content.offsetHeight - els.content.firstChild.offsetHeight);
				if (width.toString().indexOf('%') != -1) {
					els.wrapper.style.width = (Math.max(document.documentElement.clientWidth, document.body.clientWidth, pagesize.width) - offset.container[1])*(parseInt(width)/100) + 'px';
					var container_offset = 0;
				}
				else {
					els.content.style.width = width + 'px';
					els.wrapper.style.width = els.content.offsetWidth + offset.wrapper[0] + 'px';
				}

				_pub.updateObject(els.content.style, {width: '', height: ''});

				var width = parseInt(els.wrapper.style.width);
				var height = parseInt(els.wrapper.style.height);

				// if we can resize this, make sure it fits in our page bounds
				if (active.params.can_resize) {
					var x = pagesize.width;
					var y = pagesize.height;
					
					x -= offset.container[0];
					y -= offset.container[1];
					if (width > x) {
						if (active.params.constrain) height = height * (x/width);
						width = x;
					}
					if (height > y) {
						if (active.params.constrain) width = width * (y/height);
						height = y;
					}
					_pub.updateObject(els.wrapper.style, {width: width + 'px', height: height + 'px'});
				}

				//els.content.style.width = width - offset.wrapper[0] + 'px';
				// TODO: this isn't adjusting to the right height for containers that are smaller than the page height
				// resize the wrappers height based on the content boxes height
				// this needs to be height - ibox_content[margin+padding+border]
				els.content.style.height = height - offset.wrapper[1] + 'px';
				if (active.dimensions != ['100%', '100%']) _pub.center(els.wrapper);
			}
			
			// fix overlay width/height (cant use css fixed on ie6 or fx or any
			// browser really due to issues)
			els.overlay.style.height = Math.max(document.body.clientHeight, document.documentElement.clientHeight) + 'px';
		},

		updateObject: function(obj, params) {
			for (var i in params) obj[i] = params[i];
		},

		/**
		 * Centers an object
		 * @param {Object} obj
		 */
		center: function(obj) {
			var pageSize = _pub.getPageSize();
			var scrollPos = _pub.getScrollPos();
			var emSize = _pub.getElementSize(obj);
			var x = Math.round((pageSize.width - emSize.width) / 2 + scrollPos.scrollX);
			var y = Math.round((pageSize.height - emSize.height) / 2 + scrollPos.scrollY);
			if (obj.offsetLeft) x -= obj.offsetLeft;
			if (obj.offsetTop) y -= obj.offsetTop;
			if (obj.style.left) x += parseInt(obj.style.left);
			if (obj.style.top) y += parseInt(obj.style.top);
			// this nearly centers it due to scrollbars
			x -= 10;
			_pub.updateObject(obj.style, {top: y + 'px', left: x + 'px'});
		},
		
		getStyle: function(obj, styleProp) {
			if (obj.currentStyle)
				return obj.currentStyle[styleProp];
			else if (window.getComputedStyle)
				return document.defaultView.getComputedStyle(obj,null).getPropertyValue(styleProp);
		},

		/**
		 * Gets the scroll positions
		 */
		getScrollPos: function() {
			var docElem = document.documentElement;
			return {
				scrollX: document.body.scrollLeft || window.pageXOffset || (docElem && docElem.scrollLeft),
				scrollY: document.body.scrollTop || window.pageYOffset || (docElem && docElem.scrollTop)
			};
		},

		/**
		 * Gets the page constraints
		 */
		getPageSize: function() {
			return {
				width: window.innerWidth || (document.documentElement && document.documentElement.clientWidth) || document.body.clientWidth,
				height: window.innerHeight || (document.documentElement && document.documentElement.clientHeight) || document.body.clientHeight
			};
		},

		/**
		 * Gets an objects offsets
		 * @param {Object} obj
		 */
		getElementSize: function(obj) {
			return {
				width: obj.offsetWidth || obj.style.pixelWidth,
				height: obj.offsetHeight || obj.style.pixelHeight
			};
		},
		
		fade: function(obj, start, end, speed, callback) {
			if (start === undefined || !(start >= 0) || !(start <= 100)) var start = 0;
			if (end === undefined || !(end >= 0) || !(end <= 100)) var end = 100;
			if (speed === undefined) var speed = 0;

			if (obj.fader) clearInterval(obj.fader);

			if (!speed) {
				_pub.setOpacity(null, obj, end);
				if (callback) callback();
			}
			
			var opacity_difference = end - start; 
			var time_total = speed; // time is speed (jQuery compat)
			var step_size = 25; // step size in ms
			var steps = time_total / step_size; // total number of steps
			var increment = Math.ceil(opacity_difference / steps); // how much to incr per step
			
			obj.fader = setInterval(_pub.bind(function(e, obj, increment, end, callback) {
				var opacity = _pub.getOpacity(e, obj) + increment;
				_pub.setOpacity(e, obj, opacity);
				if ((increment < 0 && opacity <= end) || (increment > 0 && opacity >= end)) {
					_pub.setOpacity(e, obj, end);
					clearInterval(obj.fader);
					if (callback) callback();
				}
			}, obj, increment, end, callback), step_size);
		},

		/**
		 * Sets the opacity of an element
		 * @param {Object} obj
		 * @param {Integer} value
		 */
		setOpacity: function(e, obj, value) {
			value = Math.round(value);
			obj.style.opacity = value/100;
			obj.style.filter = 'alpha(opacity=' + value + ')';
		},
		
		/**
		 * Gets the opacity of an element
		 * @param {Object} obj
		 * @return {Integer} value
		 */
		getOpacity: function(e, obj) {
			return _pub.getStyle(obj, 'opacity')*100;
		},
		
		/**
		 * Creates a new XMLHttpRequest object based on browser
		 */
		createXMLHttpRequest: function() {
			var http;
			if (window.XMLHttpRequest) { // Mozilla, Safari,...
				http = new XMLHttpRequest();
				if (http.overrideMimeType) {
					// set type accordingly to anticipated content type
					http.overrideMimeType('text/html');
				}
			}
			else if (window.ActiveXObject) { // IE
				try {
					http = new ActiveXObject("Msxml2.XMLHTTP");
				} catch (e) {
					try {
						http = new ActiveXObject("Microsoft.XMLHTTP");
					} catch (e) {}
				}
			}
			if (!http) {
				alert('Cannot create XMLHTTP instance');
				return false;
			}
			return http;
		},
		
		addEvent: function(obj, evType, fn) {
			if (obj.addEventListener) {
				obj.addEventListener(evType, fn, false);
				return true;
			}
			else if (obj.attachEvent) {
				var r = obj.attachEvent("on"+evType, fn);
				return r;
			}
			else {
				return false;
			}
		},
		
		addEventListener: function(name, callback) {
			if (!events[name]) events[name] = new Array();
			events[name].push(callback);
		},
		
		/**
		 * Causes all event listeners attached to `name` event to
		 * execute.
		 * @param {String} name Event name
		 */
		fireEvent: function(name) {
				if (events[name] && events[name].length) {
					for (var i=0; i<events[name].length; i++) {
						var args = [];
						for (var n=1; n<arguments.length; n++) args.push(arguments[n]);
						// Events returning false stop propagation
						if (events[name][i](args) === false) break;
					}
				}
		},
		
		/**
		 * Parses the arguments in the rel attribute
		 * @param {String} query
		 */
		parseQuery: function(query) {
			 var params = new Object();
			 if (!query) return params; 
			 var pairs = query.split(/[;&]/);
			 var end_token;
			 for (var i=0; i<pairs.length; i++) {
					var keyval = pairs[i].split('=');
					if (!keyval || keyval.length != 2) continue;
					var key = unescape(keyval[0]);
					var val = unescape(keyval[1]);
					val = val.replace(/\+/g, ' ');
					if (val[0] == '"') var token = '"';
					else if (val[0] == "'") var token = "'";
					else var token = null;
					if (token) {
						if (val[val.length-1] != token) {
							do {
								i += 1;
								val += '&'+pairs[i];
							}
							while ((end_token = pairs[i][pairs[i].length-1]) != token)
						}
						val = val.substr(1, val.length-2);
					}
					if (val == 'true') val = true;
					else if (val == 'false') val = false;
					else if (val == 'null') val = null;
					params[key] = val;
			 }
			 return params;
		},
		/**
		 * Handles the onclick event for iBox anchors.
		 * @param {Event} e
		 */
		handleTag: function(e) {
			var t = this.getAttribute('rel');
			var params = _pub.parseQuery(t.substr(5,999));
			if (params.target) var url = params.target;
			else if (this.target && !params.ignore_target) var url = this.target;
			else var url = this.href;
			var title = this.title;
			if (_pub.inherit_frames && window.parent) window.parent.iBox.showURL(url, title, params);
			else _pub.showURL(url, title, params);
			return false;
		},
		
		plugins: {
			list: new Array(),
			register: function(func, last) {
				if (last === undefined) var last = false;
				if (!last) {
					_pub.plugins.list = [func].concat(_pub.plugins.list);
				}
				else {
					_pub.plugins.list.push(func);
				}
			}
		}
	};
	
	// private methods and variables
	var active = {};
	
	// events
	var events = {};

	// some containers
	// we store these in memory instead of finding them each time
	var els = {};
	
	var offset = {};
	
	/**
	 * Creates the iBox container and appends it to an element
	 * @param {HTMLObject} elem Container to attach to
	 * @return {HTMLObject} iBox element
	 */
	var create = function(elem) {
		pagesize = _pub.getPageSize();
		
		// TODO: why isnt this using DOM tools
		// a trick on just creating an ibox wrapper then doing an innerHTML on our root ibox element
		els.container = document.createElement('div');
		els.container.id = 'ibox';

		els.overlay = document.createElement('div');
		els.overlay.style.display = 'none';
		_pub.setOpacity(null, els.overlay, 0);
		// firefox mac has issues with opacity and flash
		if (!_pub.is_firefox) els.overlay.style.background = '#000000';
		else els.overlay.style.backgroundImage = "url('/sites/images/overlay.png')";
		els.overlay.id = 'ibox_overlay';
		params = {position: 'absolute', top: 0, left: 0, width: '100%'};
		_pub.updateObject(els.overlay.style, params);
		els.overlay.onclick = _pub.hide;
		els.container.appendChild(els.overlay);

		els.loading = document.createElement('div');
		els.loading.id = 'ibox_loading';
		els.loading.innerHTML = 'Loading...';
		els.loading.style.display = 'none';
		els.loading.onclick = _pub.hide
		els.container.appendChild(els.loading);

		els.wrapper = document.createElement('div')
		els.wrapper.id = 'ibox_wrapper';
		_pub.updateObject(els.wrapper.style, {position: 'absolute', top: 0, left: 0, display: 'none'});

		els.content = document.createElement('div');
		els.content.id = 'ibox_content';
		_pub.updateObject(els.content.style, {overflow: 'auto'})
		els.wrapper.appendChild(els.content);
	
		var child = document.createElement('div');
		child.id = 'ibox_footer_wrapper';
	
		var child2 = document.createElement('a');
		child2.innerHTML = _pub.close_label;
		child2.href = 'javascript:void(0)';
		child2.onclick = _pub.hide;
		child.appendChild(child2);
	
		els.footer = document.createElement('div');
		els.footer.id = 'ibox_footer';
		els.footer.innerHTML = '&nbsp;';
		child.appendChild(els.footer);
		els.wrapper.appendChild(child);

		els.container.appendChild(els.wrapper);

		elem.appendChild(els.container);
				
		_pub.updateObject(els.wrapper.style, {right: '', bottom: ''});
		
		return els.container;
	};
	
	/**
	 * Hides tags within the container
	 * @param {String} tag The name of the tag (e.g. 'a')
	 * @param {HTMLObject} container The container to restore tags within (defaults to document)
	 */
	var hideTags = function(tag, container) {
		if (container === undefined) var container = document.body;
		var list = container.getElementsByTagName(tag);
		for (var i=0; i<list.length; i++) {
			if (_pub.getStyle(list[i], 'visibility') != 'hidden' && list[i].style.display != 'none') {
				list[i].style.visibility = 'hidden';
				list[i].wasHidden = true;
			}
		}
	};
	
	/**
	 * Shows all previously hidden tags in a container.
	 * @param {String} tag The name of the tag (e.g. 'a')
	 * @param {HTMLObject} container The container to restore tags within (defaults to document)
	 */
	var showTags = function(tag, container) {
		if (container === undefined) var container = document.body;
		var list = container.getElementsByTagName(tag);
		for (var i=0; i<list.length; i++) {
			if (list[i].wasHidden) {
				list[i].style.visibility = 'visible';
				list[i].wasHidden = null;
			}
		}
	};
	
	var showInit = function(title, params, callback) {
		if (!_initialized) initialize();
		if (params === undefined) var params = {};
		if (active.plugin) _pub.hide();

		active.is_loaded = true;
		active.params = params;
		
		els.loading.style.display = "block";
		
		_pub.center(els.loading);
		_pub.reposition();

		// hide tags
		for (var i=0; i<_pub.tags_to_hide.length; i++) {
			hideTags(_pub.tags_to_hide[i]);
		}

		// set title here
		els.footer.innerHTML = title || "&nbsp;";

		// setup background
		els.overlay.style.display = "block";
		
		if (!_pub.is_firefox) var amount = 70;
		else var amount = 100;
		_pub.fade(els.overlay, _pub.getOpacity(null, els.overlay), amount, _pub.fade_in_speed, callback);
		
		_pub.fireEvent('show');
	};
	
	var drawCSS = function() {
		// Core CSS (positioning/etc)
		var core_styles = "#ibox {z-index:1000000;text-align:left;} #ibox_overlay {z-index:1000000;} #ibox_loading {position:absolute;z-index:1000001;} #ibox_wrapper {margin:30px;position:absolute;top:0;left:0;z-index:1000001;} #ibox_content {z-index:1000002;margin:27px 5px 5px 5px;padding:2px;} #ibox_content object {display:block;} #ibox_content .ibox_image {width:100%;height:100%;margin:0;padding:0;border:0;display:block;} #ibox_footer_wrapper a {float:right;display:block;outline:0;margin:0;padding:0;} #ibox_footer_wrapper {text-align:left;position:absolute;top:5px;right:5px;left:5px;white-space:nowrap;overflow:hidden;}";
		
		// Default style/theme/skin/whatever
		var default_skin = "#ibox_footer_wrapper {font-weight:bold;height:20px;line-height:20px;} #ibox_footer_wrapper a {text-decoration:none;background:#888;border:1px solid #666;line-height:16px;padding:0 5px;color:#333;font-weight:bold;font-family:Verdana, Arial, Helvetica, sans-serif;font-size:10px;} #ibox_footer_wrapper a:hover {background-color:#bbb;color:#111;} #ibox_footer_wrapper {font-size:12px;font-family:Verdana, Arial, Helvetica, sans-serif;color:#111;} #ibox_wrapper {border:1px solid #ccc;} #ibox_wrapper {background-color:#999;}#ibox_content {background-color:#eee;border:1px solid #666;} #ibox_loading {padding:50px; background:#000;color:#fff;font-size:16px;font-weight:bold;}";

		var head = document.getElementsByTagName("head")[0];

		// tricky hack for IE
		// because IE doesn't like when you insert stuff the proper way
		// and we cant use relative paths to include this as an external
		// stylesheet
		var htmDiv = document.createElement('div');

		htmDiv.innerHTML = '<p>x</p><style type="text/css">'+default_skin+'</style>';
		head.insertBefore(htmDiv.childNodes[1], head.firstChild);

		htmDiv.innerHTML = '<p>x</p><style type="text/css">'+core_styles+'</style>';
		head.insertBefore(htmDiv.childNodes[1], head.firstChild);
	};

	var _initialized = false;
	var initialize = function() {
		// make sure we haven't already done this
		if (_initialized) return;
		_initialized = true;
		// elements here start the look up from the start non <a> tags
		drawCSS();
		var els = document.getElementsByTagName('script');
		var src;
		for (var i=0, el=null; (el = els[i]); i++) {
			if (!(src = el.getAttribute('src'))) continue;
			src = src.split('?')[0];
			if (src.substr(src.length-8) == '/ibox.js') {
				_pub.setPath(src.substr(0, src.length-7));
				break;
			}
		}
		create(document.body);
		_pub.checkTags(document.body, 'a');
		_pub.http = _pub.createXMLHttpRequest();
		_pub.fireEvent('load');
	};
	
	_pub.addEvent(window, 'keypress', function(e){ if (e.keyCode == (window.event ? 27 : e.DOM_VK_ESCAPE)) { iBox.hide(); }});
	_pub.addEvent(window, 'resize', _pub.reposition);
	_pub.addEvent(window, 'load', initialize);
	_pub.addEvent(window, 'scroll', _pub.reposition);

	// DEFAULT PLUGINS

	/**
	 * Handles embedded containers in the page based on url of #container.
	 * This _ONLY_ works with hidden containers.
	 */
	var iBoxPlugin_Container = function() {
		var was_error = false;
		var original_wrapper = null;
		return {
			/**
			 * Matches the url and returns true if it fits this plugin.
			 */
			match: function(url) {
				return url.indexOf('#') != -1;
			},
			/**
			 * Called when this plugin is unloaded.
			 */
			unload: function() {
				if (was_error) return;
				var elemSrc = _pub.html().firstChild;
				if (elemSrc) {
					elemSrc.style.display = 'none';
					original_wrapper.appendChild(elemSrc);
				}
			},
			/**
			 * Handles the output
			 * @param {iBox} ibox
			 * @param {String} url
			 * @return {iBoxContent} an instance or subclass of iBoxContent
			 */
			render: function(url, params) {
				was_error = false;
				var elemSrcId = url.substr(url.indexOf("#") + 1);
				var elemSrc = document.getElementById(elemSrcId);
				// If the element doesnt exist, break the switch
				if (!elemSrc) {
					was_error = true;
					_pub.html(document.createTextNode('Oops! There seems to be a problem with this photograph'), params);
				}
				else {
					original_wrapper = elemSrc.parentNode;
					elemSrc.style.display = 'block';
					_pub.html(elemSrc, params);
				}
			}
		}
	}();
	_pub.plugins.register(iBoxPlugin_Container, true);

	/**
	 * Handles images
	 */
	var iBoxPlugin_Image = function() {
		// Image types (for auto detection of image display)
		var image_types = /\.jpg|\.jpeg|\.png|\.gif/gi;

		return {
			match: function(url) {
				return url.match(image_types);
			},

			render: function(url, params) {	
				var img = document.createElement('img');
				img.onclick = _pub.hide;
				img.className = 'ibox_image'
				img.style.cursor = 'pointer';
				img.onload = function() {
					_pub.html(img, {width: this.width, height: this.height, constrain: true})
				}
				img.onerror = function() {
					_pub.html(document.createTextNode('There was an error loading the document.'), params);
				}
				img.src = url;
			}
		}
	}();
	_pub.plugins.register(iBoxPlugin_Image);

	var iBoxPlugin_YouTube = function() {
		var youtube_url = /(?:http:\/\/)?(?:www\d*\.)?(youtube\.(?:[a-z]+))\/(?:v\/|(?:watch(?:\.php)?)?\?(?:.+&)?v=)([^&]+).*/;
		return {
			match: function(url) {
				return url.match(youtube_url);
			},

			render: function(url, params) {
				var _match = url.match(youtube_url);
				var domain = _match[1];
				var id = _match[2];
				params.width = 425;
				params.height = 355;
				params.constrain = true;
				var html = '<span><object width="100%" height="100%" style="overflow: hidden; display: block;"><param name="movie" value="http://www.' + domain + '/v/' + id + '"/><param name="wmode" value="transparent"/><embed src="http://www.' + domain + '/v/' + id + '" type="application/x-shockwave-flash" wmode="transparent" width="100%" height="100%"></embed></object></span>';
				_pub.html(html, params);
			}
		}
	}();
	_pub.plugins.register(iBoxPlugin_YouTube);

	var iBoxPlugin_Document = function() {
		return {
			match: function(url) {
				return true;
			},

			render: function(url, params) {
				_pub.http.open('get', url, true);

				_pub.http.onreadystatechange = function() {
					if (_pub.http.readyState == 4) {
						// XXX: why does status return 0?
						if (_pub.http.status == 200 || _pub.http.status == 0) {
							_pub.html(_pub.http.responseText, params);
						}
						else {
							_pub.html(document.createTextNode('There was an error loading the document.'), params);
						}
					}
				}
				_pub.http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
				try {
					_pub.http.send(null);
				}
				catch (ex) {
					_pub.html(document.createTextNode('There was an error loading the document.'), params);
				}
			}
		};
	}();
	_pub.plugins.register(iBoxPlugin_Document, true);

	return _pub;
}();
//end /sites/scripts/ibox.js
//start /sites/scripts/wall.js
/* document must also have the wz_tooltip and json javascript script in it */

function WallVote(logged_in, sku, pid, pos, type, wurl)
{
    if(!logged_in)
    {
        Tip('Hey, <u><a href="/controller.aspx?type=view&info=WallLogin&wtype=product&url='+wurl+'&sku='+sku+'&pid='+pid+'&a=vote&pos='+pos+'&ptype='+type+'">login</a></u> to vote!', CLICKCLOSE, true, STICKY, true, FADEOUT, 200);
        pageTracker._trackEvent('Wall', 'attemptedVoteOn'+type, sku);
    }
    else
    {
        var url = 'process.aspx';
        var params = 'type=wallRating&url='+wurl+'&sku='+sku+'&pid='+pid+'&pos='+pos+'&post_type='+type;
        
        waitcursor();
        var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: wallVoteResult });
    }
}

function wallVoteResult(result){
    clearcursor();
    var response = result.responseText.parseJSON();
    if(response.success == "true")
    {
        window.location = "/" + response.url + "?success=true&pid="+response.pid+"&ptype="+response.type+"&a=vote#"+response.type+"_"+response.pid; 
    }
    else
    {
        $(response.type+"VoteResponse_"+response.pid).style.display = "inline";
        $(response.type+"VoteResponse_"+response.pid).innerHTML = response.error;   
    }        
}
function DeleteWallPost(pid)
{
    var url = 'process.aspx';
    var params = 'type=deleteWallPost&pid='+pid;

    waitcursor();
    var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: deletePostResult });
}

function deletePostResult(result){
    clearcursor();
    var response = result.responseText.parseJSON();
    if(response.success == "true")
    {
        $$("#postDiv_"+response.pid).each(function(s) { s.className = "deletedPost"; });
        $$("#postDiv_"+response.pid).each(function(s) { s.innerHTML = "Your post has been deleted."; });
    }
    else
    {
         $("postDiv_"+response.pid).innerHTML = "<span class='error'>You do not have permission to delete this post.</span>" + $("postDiv_"+response.pid).innerHTML;
    }        
}
function FollowWallPost(pid)
{
    var url = 'process.aspx';
    var params = 'type=followpost&pid='+pid;

    waitcursor();
    var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: followWallPostResult });
}

function followWallPostResult(result){
    clearcursor();
    var response = result.responseText.parseJSON();
    if(response.success == "true")
    {
        $("postNotification_"+response.pid).innerHTML="You got it!  You are now subscribed to this post.";
    }
    else
    {
         $("postNotification_"+response.pid).innerHTML = "<span class='error'>Unable to set up email notification at this time.</span>";
    }        
}
function DeleteWallComment(pid)
{
    var url = 'process.aspx';
    var params = 'type=deleteWallComment&pid='+pid;

    waitcursor();
    var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: deleteCommentResult });
}

function deleteCommentResult(result){
    clearcursor();
    var response = result.responseText.parseJSON();
    if(response.success == "true")
    {
        $("commentDiv_"+response.pid).className = "deletedComment";
        $("commentDiv_"+response.pid).innerHTML="Your post has been deleted.";
    }
    else
    {
         $("commentDiv_"+response.pid).innerHTML = "<span class='error'>You do not have permission to delete this post.</span>" + $("postDiv_"+response.pid).innerHTML;
    }         
}
function updateWallProfile(bio, location)
{
    var url = 'process.aspx';
    var params = 'type=updatewallprofile&bio='+bio+'&location='+location;

    waitcursor();
    var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: updateWallProfileResult });
}

function updateWallProfileResult(result){
    clearcursor();
    var response = result.responseText.parseJSON();
    if(response.success == "true")
    {
        tt_HideInit();
        $("bio").innerHTML = bio_text;
        $("location").innerHTML = location_text;
    }
    else
    {
        $("profileError").innerHTML = "There has been an error with your submission. Please make sure you are still logged in and try again.";
         //$("postDiv_"+response.pid).innerHTML = "<span class='error'>You do not have permission to delete this post.</span>" + $("postDiv_"+response.pid).innerHTML;
    }        
}
//used for submitting wall reviews that do not have pros, cons or recommended... calls the updated wallreview with "" for pros, cons, recommended
function WallReview(logged_in, sku, title, text, stars, wtype, wurl)
{
    WallReviewFull(logged_in, sku, title, "", "", text, "", stars, wtype, wurl);
}
function WallReviewFull(logged_in, sku, title, pros, cons, text, recommended, stars, wtype, wurl)
{
    if(!logged_in)
    {
        Tip('Hey, <u><a href="/controller.aspx?type=view&info=WallLogin&sku='+sku+'&a=review&wtype='+wtype+'&url='+escape(wurl)+'">login</a></u> to review', CLICKCLOSE, true, STICKY, true, FADEOUT, 200);
    }
    else
    {
        if(stars==0) {$('reviewMsg').innerHTML = "Please choose a star rating."; return; }
        if(text=="") {$('reviewMsg').innerHTML = "Please enter your review."; return; }
        
        var url = 'process.aspx';
        var params = 'type=wallreview&title='+escape(title)+'&text='+escape(text)+'&stars='+stars+'&sku='+sku+'&wtype='+wtype+'&url='+escape(wurl)+'&pros='+pros+'&cons='+cons+'&recommended='+recommended;

        waitcursor();
        var myAjax = new Ajax.Request( url, { method: 'post', parameters: params, onComplete: wallReviewResult });
    }
}

function wallReviewResult(result){
    clearcursor();
    var response = result.responseText.parseJSON();
    if(response.success == "true")
    {
        var url = window.location.href;
        window.location = "/" + response.url + "?success=true&pid="+response.pid+"&ptype=post&a=submit#post_"+response.pid;
        //if(url.indexOf("type=view") == -1){ window.location = url.substring(0, url.indexOf("?")) + "?success=true&pid="+response.pid+"&a=submit#post_"+response.pid; }
        //else{ window.location = url + "&success=true&pid="+response.pid+"&a=submit&#post_"+response.pid; }
    }
    else
    { 
        $('reviewMsg').innerHTML = response.error;   
    }        
}
function WallVideo(logged_in, sku, title, text, video_url, wtype, wurl)
{
    if(!logged_in)
    {
        Tip('Hey, <u><a href="/controller.aspx?type=view&info=WallLogin&sku='+sku+'&a=video&wtype='+wtype+'&url='+escape(wurl)+'">login</a></u> to upload', CLICKCLOSE, true, STICKY, true, FADEOUT, 200);
    }
    else
    {
        if(video_url=="") {$('videoMsg').innerHTML = "Please enter a video URL."; return; }
        if(title=="") {$('videoMsg').innerHTML = "Please enter a title for your video."; return; }
        
        var url = 'process.aspx';
        var params = 'type=wallvideo&title='+escape(title)+'&text='+escape(text)+'&video_url='+escape(video_url)+'&sku='+sku+'&wtype='+wtype+'&url='+escape(wurl);

        waitcursor();
        var myAjax = new Ajax.Request( url, { method: 'post', parameters: params, onComplete: wallVideoResult });
    }
}

function wallVideoResult(result){
    clearcursor();
    var response = result.responseText.parseJSON();
    if(response.success == "true")
    {
        var url = window.location.href;
        window.location = "/" + response.url + "?success=true&pid="+response.pid+"&ptype=post&a=submit#post_"+response.pid;
        //if(url.indexOf("type=view") == -1){ window.location = url.substring(0, url.indexOf("?")) + "?success=true&pid="+response.pid+"&a=submit#post_"+response.pid; }
        //else{ window.location = url + "&success=true&pid="+response.pid+"&a=submit&#post_"+response.pid; }
    }
    else
    { 
        $('videoMsg').innerHTML = response.error;   
    }        
}
function WallQuestion(logged_in, sku, title, text, wtype, wurl)
{
    if(!logged_in)
    {
        Tip('Hey, <u><a href="/controller.aspx?type=view&info=WallLogin&sku='+sku+'&a=question&wtype='+wtype+'&url='+escape(wurl)+'">login</a></u> to ask your question', CLICKCLOSE, true, STICKY, true, FADEOUT, 200);
    }
    else
    {
        if(text=="") {$('reviewMsg').innerHTML = "Please enter your question."; return; }
        
        var url = 'process.aspx';
        var params = 'type=wallquestion&title='+escape(title)+'&text='+escape(text)+'&sku='+sku+'&wtype='+wtype+'&url='+escape(wurl);

        waitcursor();
        var myAjax = new Ajax.Request( url, { method: 'post', parameters: params, onComplete: wallQuestionResult });
    }
}

function wallQuestionResult(result){
    clearcursor();
    var response = result.responseText.parseJSON();
    if(response.success == "true")
    {
        var url = window.location.href;
        window.location = "/" + response.url + "?success=true&pid="+response.pid+"&ptype=post&a=submit#post_"+response.pid;
    }
    else
    {
        $('questionMsg').innerHTML = response.error; 
    }        
}
//DEPRECATED - calls the appropriate function with "product" wall_type selected as default
function WallComment(logged_in, sku, pid, text, wurl) 
{
    WallCommentFull(logged_in, sku, pid, text, 'product', wurl);
}
function WallCommentFull(logged_in, sku, pid, text, wtype, wurl)
{
    if(!logged_in)
    {
        Tip('Hey, <u><a href="/controller.aspx?type=view&info=WallLogin&wtype='+wtype+'&url='+wurl+'&sku='+sku+'&a=review">login</a></u> to respond', CLICKCLOSE, true, STICKY, true,  FADEOUT, 200);
    }
    else
    {
        if(text=="") {$('commentMsg').innerHTML = "Please enter your text here."; return; }
        
        var url = 'process.aspx';
        var params = 'type=wallcomment&pid='+pid+'&text='+escape(text)+'&sku='+sku+'&url='+wurl;

        waitcursor();
        var myAjax = new Ajax.Request( url, { method: 'post', parameters: params, onComplete: wallCommentResult });
    }
}

function wallCommentResult(result){
    clearcursor();
    var response = result.responseText.parseJSON();
    if(response.success == "true")
    {
        var url = window.location.href;
        window.location = "/" + response.url + "?success=true&pid="+response.cid+"&a=submit&ptype=comment#comment_"+response.cid;
        //if(url.indexOf("type=view") == -1){ window.location = url.substring(0, url.indexOf("?")) + "?success=true&pid="+response.pid+"&a=submit#post_"+response.pid; }
        //else{ window.location = url + "&success=true&pid="+response.pid+"&a=submit&#post_"+response.pid; }
    }
    else
    {
        $("commentMsg_"+response.pid).innerHTML = response.error;
    }        
}

function WallFlag(logged_in, sku, pid, text, type)
{
    if(!logged_in)
    {
        Tip('Hey, <u><a href="/controller.aspx?type=view&info=WallLogin&ptype='+type+'&sku='+sku+'&a=flag&pid='+pid+'">login</a></u> to flag', CLICKCLOSE, true, STICKY, true,  FADEOUT, 200);
    }
    else
    {        
        var url = 'process.aspx';
        var params = 'type=wallflag&sku='+sku+'&pid='+pid+'&text='+escape(text)+"&ptype="+type;

        waitcursor();
        var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: wallFlagResult });
    }
}

function wallFlagResult(result){
    clearcursor();
    var response = result.responseText.parseJSON();
    if(response.success == "true")
    {
        var url = window.location.href;
        window.location = "/" + response.sku + ".html?success=true&pid="+response.pid+"&a=flag&ptype=" + response.type + "#" + response.type + "_"+response.pid;
    }
    else
    {
        //what to do on error
    }        
}

function RemoveWallFlag(logged_in, sku, pid, type)
{
    if(!logged_in)
    {
        Tip('Hey, <u><a href="/controller.aspx?type=view&info=WallLogin&ptype='+type+'&sku='+sku+'&a=flag&pid='+pid+'">login</a></u> to remove this flag', CLICKCLOSE, true, STICKY, true,  FADEOUT, 200);
    }
    else
    {        
        var url = 'process.aspx';
        var params = 'type=wallremoveflag&pid='+pid+"&ptype="+type+"&sku="+sku;

        waitcursor();
        var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: wallRemoveFlagResult });
    }
}

function wallRemoveFlagResult(result){
    clearcursor();
    var response = result.responseText.parseJSON();
    if(response.success == "true")
    {
        var url = window.location.href;
        window.location = "/" + response.sku + ".html?success=true&pid="+response.pid+"&a=unflag&ptype="+response.type+"#"+response.type+"_"+response.pid;
    }
    else
    {
        //what to do on error
    }        
}

function ViewFlagged(type, id)
{
    $$("#"+type+"_"+id).each(function(s) { s.style.display='block'; });
    $$("#"+type+'_flag_'+id).each(function(s) { s.style.display='none'; });
}

function OpenFlagForm(logged_in, sku, id, type)
{
    if(!logged_in)
    {
        Tip('Hey, <u><a href="/controller.aspx?type=view&info=WallLogin&ptype='+type+'&sku='+sku+'&a=flag&pid='+id+'">login</a></u> to flag', CLICKCLOSE, true, STICKY, true,  FADEOUT, 200);
    }
    else
    {   
        if($(type+"flagopen_"+id).style.display == 'none') { $(type+"flagopen_"+id).style.display = "block"; }
        else { $(type+"flagopen_"+id).style.display = "none"; }
    }
}

function ShowTooltip(id,text)
{
    Tip(text);
}

function openWallForm(obj, type)
{
    $(type+'InitialInput').style.display="none";
    $(type+'Form').style.display='block';
    if($(type+'FormTitle') != null) { $(type+'FormTitle').focus(); }
    if(isDefined("uploadType")) { uploadType = type; }
}

function closeWallForm(type)
{
    $(type+'Form').style.display='none';
    $(type+'InitialInput').style.display="block";
}
function CloseFlagForm(type, id)
{
    $(type+'flagopen_'+id).style.display='none';
}

function openCommentForm(id)
{
    $('commentInitial_'+id).style.display="none";
    $('commentForm_'+id).style.display='block';
    $('commentText_'+id).focus();
}

function closeCommentForm(id)
{
    $('commentInitial_'+id).style.display="block";
    $('commentForm_'+id).style.display='none';
}

function OpenEditForm(id, type)
{
    $('edit'+type.toTitleCase()+'_'+id).style.display = "block";
}

function CloseEditForm(id, type)
{
    $('edit'+type.toTitleCase()+'_'+id).style.display = "none";
}

function SubmitReviewEdit(sku, id, stars, title, text, wurl)
{
    if(stars==0) {$('reviewEditMsg').innerHTML = "Please choose a star rating."; return; }
    if(text=="") {$('reviewEditMsg').innerHTML = "Please enter your review."; return; }
    
    var url = 'process.aspx';
    var params = 'type=editwallreview&url='+wurl+'&title='+escape(title)+'&text='+escape(text)+'&stars='+stars+'&sku='+sku+'&id='+id;

    waitcursor();
    var myAjax = new Ajax.Request( url, { method: 'post', parameters: params, onComplete: wallReviewEditResult });
}

function wallReviewEditResult(result){
    clearcursor();
    var response = result.responseText.parseJSON();
    if(response.success == "true")
    {
        var url = window.location.href;
        window.location = "/" + response.url + "?success=true&pid="+response.pid+"&ptype=post&a=edit#post_"+response.pid;
        //if(url.indexOf("type=view") == -1){ window.location = url.substring(0, url.indexOf("?")) + "?success=true&pid="+response.pid+"&a=submit#post_"+response.pid; }
        //else{ window.location = url + "&success=true&pid="+response.pid+"&a=submit&#post_"+response.pid; }
    }
    else
    { 
        $('reviewMsg').innerHTML = response.error;   
    }        
}
function SubmitQuestionEdit(sku, id, title, text, wurl)
{
    if(text=="") {$('questionEditMsg_'+id).innerHTML = "Please enter your text."; return; }
    
    var url = 'process.aspx';
    var params = 'type=editwallquestion&title='+escape(title)+'&text='+escape(text)+'&sku='+sku+'&id='+id+"&url="+wurl;

    waitcursor();
    var myAjax = new Ajax.Request( url, { method: 'post', parameters: params, onComplete: wallQuestionEditResult });
}

function wallQuestionEditResult(result){
    clearcursor();
    var response = result.responseText.parseJSON();
    if(response.success == "true")
    {
        var url = window.location.href;
        window.location = "/" + response.url + "?success=true&pid="+response.pid+"&ptype=post&a=edit#post_"+response.pid;
        //if(url.indexOf("type=view") == -1){ window.location = url.substring(0, url.indexOf("?")) + "?success=true&pid="+response.pid+"&a=submit#post_"+response.pid; }
        //else{ window.location = url + "&success=true&pid="+response.pid+"&a=submit&#post_"+response.pid; }
    }
    else
    { 
        $('questionMsg').innerHTML = response.error;   
    }        
}
function SubmitCommentEdit(sku, id, text, wurl)
{
    if(text=="") {$('editcommentMsg').innerHTML = "Please enter your comment."; return; }
    
    var url = 'process.aspx';
    var params = 'type=editwallcomment&text='+escape(text)+'&sku='+sku+'&id='+id+'&url='+wurl;

    waitcursor();
    var myAjax = new Ajax.Request( url, { method: 'post', parameters: params, onComplete: wallCommentEditResult });
}

function wallCommentEditResult(result){
    clearcursor();
    var response = result.responseText.parseJSON();
    if(response.success == "true")
    {
        var url = window.location.href;
        window.location = "/" + response.url + "?success=true&pid="+response.cid+"&ptype=comment&a=edit#comment_"+response.cid;
        //if(url.indexOf("type=view") == -1){ window.location = url.substring(0, url.indexOf("?")) + "?success=true&pid="+response.pid+"&a=submit#post_"+response.pid; }
        //else{ window.location = url + "&success=true&pid="+response.pid+"&a=submit&#post_"+response.pid; }
    }
    else
    { 
        $('editcommentMsg+'+response.pid).innerHTML = response.error;   
    }        
}
function toggleComments(id)
{
    if($("comments_"+id).style.display == "none")
    {
        $("comments_"+id).style.display = "block";
        $("hideCommentsIcon_"+id).src = $("hideCommentsIcon_"+id).src.replace("view", "hide");
    }
    else
    {
        $("comments_"+id).style.display = "none";
        $("hideCommentsIcon_"+id).src = $("hideCommentsIcon_"+id).src.replace("hide", "view");
    }
}

function SetRating(rating)
{
    stars = rating;
    rating_width = rating * 25;
	$('current-rating').style.width = rating_width+'px';
	SetRatingText(rating);
	return stars;
} 

function SetRatingText(n)
{
    switch(n)
    {
        case 0:
            $('ratingText').innerHTML=''; 
        break;
        case 1:
            $('ratingText').innerHTML='Just awful.';
        break;
        case 2:
            $('ratingText').innerHTML='Can\'t Recommend';
        break;
        case 3:
            $('ratingText').innerHTML='It\'s ok.';
        break;
        case 4:
            $('ratingText').innerHTML='Pretty good.';
        break;
        case 5:
            $('ratingText').innerHTML='Awesome!';
        break;
    }
}

function SetEditRating(type, id, rating)
{
    eval("stars"+id+" = rating;");
    rating_width = rating * 25;
	$('current-rating-'+id).style.width = rating_width+'px';
	SetEditRatingText(id, rating);
	return rating;
} 

function SetEditRatingText(type, id, n)
{
    switch(n)
    {
        case 0:
            $(type+'starstext_'+id).innerHTML=''; 
        break;
        case 1:
            $(type+'starstext_'+id).innerHTML='Just awful.';
        break;
        case 2:
            $(type+'starstext_'+id).innerHTML='Can\'t Recommend';
        break;
        case 3:
            $(type+'starstext_'+id).innerHTML='It\'s ok.';
        break;
        case 4:
            $(type+'starstext_'+id).innerHTML='Pretty good.';
        break;
        case 5:
            $(type+'starstext_'+id).innerHTML='Awesome!';
        break;
    }
}

function RemoveRatingText()
{
    SetRatingText(stars);
}

function RemoveEditRatingText(type, id)
{
    SetEditRatingText(type, id, eval('stars' + id));
}

function OpenBioEdit()
{
    TagToTip('bioEdit', CLOSEBTN, true, STICKY, true, WIDTH, 400, DELAY, 0);
    $('WzBoDy').getElementsBySelector('[id="bioTxt"]').each(function(s){s.value=bio_text;});
    $('WzBoDy').getElementsBySelector('[id="locationTxt"]').each(function(s){s.value=location_text;});
}
function OpenInitialBioEdit()
{
    TagToTip('bioEdit', CLOSEBTN, true, STICKY, true, WIDTH, 400, DELAY, 0, FIX, ['location', -8, -160]);
    //$('WzBoDy').getElementsBySelector('[id="bioTxt"]').each(function(s){s.value="What drives you? What's your level of training? How did you get started? Let everyone know a little about yourself.";s.onFocus="this.value='';";});
    //$('WzBoDy').getElementsBySelector('[id="locationTxt"]').each(function(s){s.value="Tell the other community members where you practice.";s.onFocus="this.value='';";});
}

function OpenTagEdit()
{
    TagToTip('tagEdit', CLOSEBTN, true, STICKY, true, WIDTH, 400, DELAY, 0);
    
    $A($('WzBoDy').getElementsByClassName("selectedWallTag")).each(function(s){s.className="";});
    var tags_array = tags_text.split(" // ");
    for(t=0; t<tags_array.length; t++)
    {
        $('WzBoDy').getElementsBySelector('[id="tags'+tags_array[t].split(' ').join('')+'"]').each(function(s){s.className="selectedWallTag";});
    }
}

function addTags(tag, link)
{
    if(tags_text.indexOf(tag) > -1)
    {
        tags_text = tags_text.replace("// " + tag, "");
        tags_text = tags_text.replace(tag, "");
        link.className = "";
    }
    else
    {
        if(tags_text!="") { tags_text = tags_text + " // "; }
        tags_text = tags_text + tag;
        link.className = "selectedWallTag";
    }
    
    var url = 'process.aspx';
    var params = 'type=updatewalltags&tags='+tags_text;

    waitcursor();
    var myAjax = new Ajax.Request( url, { method: 'post', parameters: params, onComplete: addTagsResult });  
}

function addTagsResult(result){
    clearcursor();
    var response = result.responseText.parseJSON();
    if(response.success == "true")
    {
        $("wallTags").innerHTML = tags_text; 
//        tt_HideInit();        
    }
    else
    {
        //what to do on error
    }        

}

function ShowPostType(imagePath,type)
{
    $("all_tab").className= "dark";
    if($("review_tab") != null) { $("review_tab").className= "dark"; }
    $("question_tab").className= "dark";
    $("image_tab").className= "dark";
    
    $(type+"_tab").className= "light";
    

    document.getElementsByClassName("userRemark").each(function(s) { s.style.display="table"; });
    document.getElementsByClassName("userActions").each(function(s) { s.style.display="table"; });

    if(type != "review" && type != "all")
    {
         document.getElementsByClassName("reviewDiv").each(function(s) { s.style.display="none"; }); 
         if($("writeReview") != null)
         {
            $("writeReview").style.display = "none";
         }
    }
    if(type != "question" && type != "all")
    { 
        document.getElementsByClassName("questionDiv").each(function(s) { s.style.display="none"; }); 
         if($("writeQuestion") != null)
         {
            $("writeQuestion").style.display = "none";
         }         
    }
    if(type!= "image" && type!= "all")
    {
        document.getElementsByClassName("imageDiv").each(function(s) { s.style.display="none"; }); 
        document.getElementsByClassName("videoDiv").each(function(s) { s.style.display="none"; }); 
         if($("uploadImageVideo") != null)
         {
            $("uploadImageVideo").style.display = "none";
         }           
    }
    
    pageTracker._trackEvent('Wall', 'changedTab', type);
 }

//calls process.aspx to login the facebook user 
// returns "error" or the user object
//YH 5/10
function LoginFacebookUser(accessToken,userId,returnFunction)
{
        var url = 'process.aspx';
        var params = 'type=fblogin&token=' + accessToken + '&uid=' + userId;       ;
        var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: 
            function(result)
            {
                returnFunction(result.responseText);
            }
        
        });

}

//calls process.aspx to login the site user
// returns "error" or the user object
//YH 5/25/10
function LoginSiteUser(email,password,rememberMe,returnFunction)
{
        var url = 'process.aspx';
        var params = 'type=login_siteuser&email=' + email + '&password=' + password + '&remember_me=' + rememberMe;       
        waitcursor();
        var myAjax = new Ajax.Request( url, { method: 'post', parameters: params, onComplete: 
            function(result)
            {               
                returnFunction(result.responseText);
            }        
        });
}

//calls process.aspx to login the wall user 
// returns "error" or the display name of the user
//YH 5/25/10
function CreateWallUser(displayName,email,password,rememberMe,returnFunction)
{
        var url = 'process.aspx';
        var params = 'type=create_walluser&display_name=' + displayName + '&email=' + email + '&password=' + password + '&remember_me=' + rememberMe;       
        waitcursor();
        var myAjax = new Ajax.Request( url, { method: 'post', parameters: params, onComplete: 
            function(result)
            {               
                returnFunction(result.responseText);
            }        
        });
}


//YH 5/10
function CreateWallReview(text,pros,cons,stars,recommended,owns,sku,wtype,wurl,returnFunction)
{
    var url = 'process.aspx';
    var params = 'type=wallreview&title=&text='+escape(text)+'&stars='+stars+'&sku='+sku+'&wtype='+wtype+'&url='+wurl+'&pros='+escape(pros)+'&cons='+escape(cons)+'&recommended='+recommended+'&owns='+owns+'&allow_anon=true';
    clearcursor();
    var myAjax = new Ajax.Request( url, { method: 'post', parameters: params, onComplete: 
            function(result)
            {
                returnFunction(result.responseText);
            }
        
        });
}

//YH 5/25/10
function CreateWallQuestion(title,text,owns,sku,wtype,wurl,returnFunction)
{
    var url = 'process.aspx';
    var params = 'type=wallquestion&title='+escape(title)+'&text='+escape(text)+'&sku='+sku+'&wtype='+wtype+'&url='+wurl+'&owns='+owns+'&allow_anon=true';
    clearcursor();
    var myAjax = new Ajax.Request( url, { method: 'post', parameters: params, onComplete: 
            function(result)
            {
                returnFunction(result.responseText);
            }
        
        });
}

//this function creates a post of type comment, not to be confused with a wall_comment
//YH 5/25/10
function CreateWallCommentPost(text,owns,sku,wtype,wurl,returnFunction)
{
    var url = 'process.aspx';
    var params = 'type=wallcommentpost&text='+escape(text)+'&sku='+sku+'&wtype='+wtype+'&url='+wurl+'&owns='+owns+'&allow_anon=true';
    clearcursor();
    var myAjax = new Ajax.Request( url, { method: 'post', parameters: params, onComplete: 
            function(result)
            {
                returnFunction(result.responseText);
            }
        
        });
}

//this function creates a post of type video
//RT 7/1/2010
function CreateWallVideo(title,text,video_url,owns,sku,wtype,wurl,returnFunction)
{
    var url = 'process.aspx';
        var params = 'type=wallvideo&title='+escape(title)+'&text='+escape(text)+'&video_url='+escape(video_url)+'&sku='+sku+'&wtype='+wtype+'&url='+escape(wurl);
        clearcursor();
        var myAjax = new Ajax.Request( url, { method: 'post', parameters: params, onComplete: 
            function(result)
            {
                returnFunction(result.responseText);
            }
        
        });
}

//this function creates a post of type video
//RT 7/1/2010
function CreateWallImage(title,text,img_path,owns,sku,wtype,wurl,returnFunction)
{
    var url = 'process.aspx';
        var params = 'type=wallimage&title='+escape(title)+'&text='+escape(text)+'&img_path='+escape(img_path)+'&sku='+sku+'&wtype='+wtype+'&url='+escape(wurl);
        clearcursor();
        var myAjax = new Ajax.Request( url, { method: 'post', parameters: params, onComplete: 
            function(result)
            {
                returnFunction(result.responseText);
            }
        
        });
}

//this function creates a wall_comment
//YH 5/26/10
function CreateWallComment(text,pid,owns,sku,wtype,wurl,returnFunction)
{
    var url = 'process.aspx';
    var params = 'type=wallcomment&pid=' + pid + '&text='+escape(text)+'&sku='+sku+'&wtype='+wtype+'&url='+wurl+'&owns='+owns+'&allow_anon=true';
    clearcursor();
    var myAjax = new Ajax.Request( url, { method: 'post', parameters: params, onComplete: 
            function(result)
            {
                returnFunction(result.responseText);
            }
        
        });
}


function openWallLogin(id,div,title)
{
    loginCallerId = id;
    ajaxwin=dhtmlwindow.open("ajaxbox", "div", div, title, "width=415px,height=250px,left=350px,top=100px,resize=1,scrolling=0")
    ajaxwin.isResize(false);
}

function SetEditRecommended(id,yesorno)
{
    //this function does not use the "checkthis" because checkthis does not take a parameter for the type
    if(yesorno == 'yes'){
        document.getElementById(id + 'No').className = 'no';
        $(id + 'Yes').className = 'yes active'
    }
    else{
        document.getElementById(id + 'Yes').className = 'yes';
        $(id + 'No').className = 'no active'
    }
    eval(id + 'Recommended' + '="' + yesorno + '"');
}

//switches the panel (comment, review or question) shown in the stand alone post section
// YH 5/12/10   
function ShowStandAlonePostPanel(panel)
{
    if(panel == "standAloneCommentPanel")
    {
        $("standAloneCommentPanel").show();
        $("standAloneQuestionPanel").hide();
        $("standAloneReviewPanel").hide();
        if($("standAloneUploadPanel") != null) {$("standAloneUploadPanel").hide(); };
        postType = "commentPost";
    }
    else if(panel == "standAloneReviewPanel")
    {
        //if showing the question panel, put any non default text entered in the comment panel in the bottom line text panel YH 6/4/10
        var commentTextInput = $("standAloneComment");        
        if(commentTextInput.value != commentTextInput.attributes["defaultText"].value && commentTextInput.value != "")
        {
            $("standAloneBottomLine").value = commentTextInput.value;
        }        
    
        $("standAloneCommentPanel").hide();
        $("standAloneQuestionPanel").hide();
        $("standAloneReviewPanel").show();
        if($("standAloneUploadPanel") != null) {$("standAloneUploadPanel").hide(); };
        postType = "review";
    }
    else if(panel == "standAloneQuestionPanel")
    {
        //if showing the question panel, put any non default text entered in the comment panel in the question text panel YH 6/4/10
        var commentTextInput = $("standAloneComment");        
        if(commentTextInput.value != commentTextInput.attributes["defaultText"].value && commentTextInput.value != "")
        {
            $("standAloneQuestionText").value = commentTextInput.value;
        }
        $("standAloneCommentPanel").hide();
        $("standAloneQuestionPanel").show();
        $("standAloneReviewPanel").hide();
        if($("standAloneUploadPanel") != null) {$("standAloneUploadPanel").hide(); };
        postType = "question";
    }  
    else if(panel == "standAloneQuestionPanel")
    {
        //if showing the question panel, put any non default text entered in the comment panel in the question text panel YH 6/4/10
        var commentTextInput = $("standAloneComment");        
        if(commentTextInput.value != commentTextInput.attributes["defaultText"].value && commentTextInput.value != "")
        {
            $("standAloneQuestionText").value = commentTextInput.value;
        }
        $("standAloneCommentPanel").hide();
        $("standAloneQuestionPanel").show();
        $("standAloneReviewPanel").hide();
        if($("standAloneUploadPanel") != null) {$("standAloneUploadPanel").hide(); };
        postType = "question";
    }  
    else if(panel == "standAloneUploadPanel")
    {
        var commentTextInput = $("standAloneComment");        

        $("standAloneCommentPanel").hide();
        $("standAloneQuestionPanel").hide();
        $("standAloneReviewPanel").hide();
        if($("standAloneUploadPanel") != null) {$("standAloneUploadPanel").show(); };
        postType = "upload";
    }  
    SetPostButtons('standAlone',postType,loggedIn);
    $("typeIcon").src = ImagePath + "/wall/" + postType + ".gif";
}     

//displays the login box for facebook
//id is the id of the panel that called the function
// YH 5/12/10       
function FacebookLogin(id,permissions)
{               
    var result;
    FB.login(function(response) {
      if (response.session) {
        if (response.perms) 
        {                                           
            LoginFacebookUser(response.session.access_token,response.session.uid,
                function(response)
                {
                    if(response != "error")
                    {
                        var result = response.parseJSON();                                 
                        $$('div[id $= WallLoginPanel]').each(function(element) {element.hide();});
                        $$('div[id $= PostToFacebookPanel]').each(function(element) {element.show();});
                        displayName = result.DisplayName;
                        loggedIn = true;
                        //if the preview is showing, update the names shows
                        if($(id + "PreviewPanel").visible())
                        {
                            //ShowPreview(id);
                            //now we actually do the post YH 6/7/10
                            $(id + "PreviewPostButton").onclick();
                        }
                        else
                        {
                            //show the welcome box
                            $(id + "LoggedInDisplayName").update(displayName);
                            $(id + "LoggedIn").show();                        
                            SetPostButtons(id,postType,true);
                        }
                    }
                }                        
            );                        
        } 
      } 
      else 
      {
      }
    }, {perms:permissions});                
}  

//shows the preview panel
//id is the id of the panel used
// YH 5/17/10
function ShowPreview(id)
{
    //if the type is comment and the id is standAlone then we need to get the actual type from the radio button
    if(postType == 'comment' && id == 'standAlone')
    {
        postType = $('form1').getInputs('radio', 'standAlonePostType').find(function(radio) { return radio.checked; }).value;
    }
    if(ValidatePost(id,postType))
    {
        //hide the content panel
        $(id + "Post").getElementsBySelector("[id=" + id + "ContentPanel]").invoke("hide");
        $(id + "Post").getElementsBySelector("[id=" + id + "PreviewDate]")[0].update(new Date().format("shortDateTime"));
        if(postType == "review")
        {
            $("reviewPreview").getElementsBySelector("[id=stars]")[0].src = ImagePath + "/stars/red_" + starsstandAlone + ".png";
            if($(id + "Pros") != null) 
            {
                if($(id + "Pros").value == "")
                {
                    $("reviewProsPreview").hide();
                }
                else
                {
                    $("reviewProsPreview").show();
                }
                $("reviewPreview").getElementsBySelector("[id=pros]")[0].update($(id + "Pros").value);
            }
            if($(id + "Cons") != null)
            {
                if($(id + "Cons").value == "")
                {
                    $("reviewConsPreview").hide();
                }
                else
                {
                    $("reviewConsPreview").show();
                }  
                $("reviewPreview").getElementsBySelector("[id=cons]")[0].update($(id + "Cons").value);
            }   
            if($("reviewPreview").getElementsBySelector("[id=recommended]").length > 0) 
            {
                $("reviewPreview").getElementsBySelector("[id=recommended]")[0].update(standAloneRecommended);
            }
            $("reviewPreview").getElementsBySelector("[id=bottomLine]")[0].update($(id + "BottomLine").value);
            $("commentPreview").hide();
            $("reviewPreview").show();
            $("questionPreview").hide();
        }
        else if(postType == "question")
        {
            //if the question title has not been changed from the default text, then we just show nothing for the title
            var questionTitleInput = $(id + "QuestionTitle");
            var questionTitleText = "";
            if(questionTitleInput.value != questionTitleInput.attributes["defaultText"].value)
            {
                questionTitleText = questionTitleInput.value;
            }
            $("questionPreview").getElementsBySelector("[id=questionTitle]")[0].update(questionTitleText);
            $("questionPreview").getElementsBySelector("[id=questionText]")[0].update($(id + "QuestionText").value);
            $("commentPreview").hide();
            $("reviewPreview").hide();
            $("questionPreview").show();

        }
        else if(postType == "commentPost")
        {
            $("commentPreview").getElementsBySelector("[id=commentText]")[0].update($(id + "Comment").value);
            $("commentPreview").show();
            $("reviewPreview").hide();
            $("questionPreview").hide();
        }  
        else if(postType == "comment")
        {
            $(id + "CommentPreview").getElementsBySelector("[id=" + id + "CommentText]")[0].update($("commentText_" + id).value);
            $(id + "CommentPreview").show();
        }  
        else if(postType == "upload")
        {            
            if (uploadType=="photo")
            {
                // upload the photo from the iframe
                window.iUploadImage.__doPostBack("ctl03_File1", "");                
                // when iframe reloads, it will call the function to show the preview or the error
            
            }
            else if (uploadType=="video")
            {
                var video_id = getUrlParam($(id + "VideoPath").value, "v");
                var video_embed = '<object width="320" height="265"><param name="wmode" value="transparent" /><param name="movie" value="http://www.youtube-nocookie.com/v/'+video_id+'&hl=en_US&fs=1&rel=0"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube-nocookie.com/v/'+video_id+'&hl=en_US&fs=1&rel=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="320" height="265" wmode="transparent"></embed></object><br /><br />';
                var video_title = $(id + "VideoTitle").value;
                var video_description = $(id + "VideoDescription").value;                

                if(video_description != $(id + "VideoDescription").attributes["defaultText"].value)
                {
                    $("videoPreview").getElementsBySelector("[id=videoDescription]")[0].update(video_description);
                }
                if(video_title != $(id + "VideoTitle").attributes["defaultText"].value)
                {
                    $("videoPreview").getElementsBySelector("[id=videoTitle]")[0].update(video_title);   
                }             
                $("videoPreview").getElementsBySelector("[id=videoEmbed]")[0].update(video_embed);
                $("videoPreview").show();
            }
            
            $("commentPreview").hide();
            $("reviewPreview").hide();
            $("questionPreview").hide();            
        }              
                 
        if($(id + "OwnThis").checked)
        {
            $(id + "OwnsThisName").show();
            $(id + "OwnsThisText").update("owns this product");
        }
        else
        {        
           $(id + "OwnsThisName").hide();
           $(id + "OwnsThisText").update("");
        }
        $(id + "OwnsThisName").update(displayName);
        $(id + "PreviewName").update(displayName);                
        $(id + "PreviewPanel").show();
        $(id + "WallLoginPanel").removeClassName("login");
        $(id + "WallLoginPanel").addClassName("loginPreview");
        $(id + "WallLoginPanel").childElements()[2].update("Login and Post");
        $(id + "WallLoginPanel").childElements()[3].childElements()[0].update("Login with Facebook and Post");
    } 
 } 

// function to show image preview
// RT 7/9/2010 
function ShowImagePreview(id, imgPath, imgError)
{
    if(imgError == "") 
    {
        var imageTitleInput = $(id + "ImageTitle");
        var imageTextInput = $(id + "ImageText");
        if(imageTitleInput.value != imageTitleInput.attributes["defaultText"].value)
        {
            $("imagePreview").getElementsBySelector("[id=ImageTitle]")[0].update($(id + "ImageTitle").value);
        }
        if(imageTextInput.value != imageTextInput.attributes["defaultText"].value)
        {
            $("imagePreview").getElementsBySelector("[id=ImageText]")[0].update($(id + "ImageText").value);
        }
        $("imagePhoto").src = imgPath;
        $(id+"ImagePath").value = imgPath.match(/(.*)[\/\\]([^\/\\]+\.\w+)$/)[2]; //filename without path
        $("imagePreview").show();
     }
     else
     {
        // show error
     }
} 
 
// hides the preview panel and shows the editable fields
// YH 5/17/10 
function EditPost(id)
{
    //if the type is comment and the id is standAlone then we need to get the actual type from the radio button
    if(postType = 'comment' && id == 'standAlone')
    {
        postType = $('form1').getInputs('radio', 'standAlonePostType').find(function(radio) { return radio.checked; }).value;
    }

   $(id + "PreviewPanel").hide();   
   $(id + "Post").getElementsBySelector("[id=" + id + "ContentPanel]").invoke("show");
   $(id + "WallLoginPanel").removeClassName("loginPreview");
   $(id + "WallLoginPanel").addClassName("login");  
   $(id + "WallLoginPanel").childElements()[2].update("Login");
   $(id + "WallLoginPanel").childElements()[3].childElements()[0].update("Login with Facebook");
}     

//sets the name and display of the post buttons
// YH 5/17/10
function SetPostButtons(id,postType,loggedIn)
{
    if(postType == "review")
    {
        $(id + 'PostButton').src = ImagePath + "/postReview.gif";
    }
    else if(postType == "commentPost")
    {
        $(id + 'PostButton').src = ImagePath + "/postComment.gif";
    }
    else if(postType == "question")
    {
        $(id + 'PostButton').src = ImagePath + "/postQuestion.gif";
    }
    else if(postType == "upload")
    {
        $(id + 'PostButton').src = ImagePath + "/uploadNow.gif";
    }
    
    if(loggedIn)
    {
        if($(id + 'PostButton') != null)
        {
            $(id + 'PreviewPostButton').src = $(id + 'PostButton').src;
        }
        //$$('img[id $= PostButton]').each(function(element) {element.show();}); //this shows all the post button not on the preview panel
        $(id + 'PostButton').show();
        $$('span[id $= PreviewOrLabel]').each(function(element) {element.hide();});
    }
    else
    {        
        //$$('img[id $= PostButton]').each(function(element) {element.hide();}); //this hides all the post button not on the preview panel
        $(id + 'PostButton').hide();
        $(id + 'PreviewPostButton').src = ImagePath + "/postAnon.gif";
        $(id + 'PreviewPostButton').show(); //make sure that the post button on the preview panel is always shown
        $$('span[id $= PreviewOrLabel]').each(function(element) {element.show();}); 
    }
}   

// validates the post depending on the post type
// YH 5/17/10
function ValidatePost(id,postType)
{
    var validated = true;
    if(postType == "review")
    {
        //call the validation function on the approrpiate panel
        validated = ValidateFields(id + "ReviewPanel");
        // stars + id has to be manually checked
        if(eval("stars" + id) == 0)
        {
            $(id + "ReviewStars").addClassName("validationFailed");
            validated = false;
        }                   
        else
        {
            $(id + "ReviewStars").removeClassName("validationFailed");
        }                    
    }
    else if(postType == "commentPost" || postType == "comment")
    {
        validated = ValidateFields(id + "CommentPanel");
    }
    else if(postType == "question")
    {
        validated = ValidateFields(id + "QuestionPanel");
    }  
    else if(postType == "upload")
    {
        if(uploadType=="video") 
        {
            validated = ValidateFields(id + "VideoForm");
        } 
        else if(uploadType=="photo") 
        {
            validated = ValidateFields(id + "PhotoForm");
            if(validated && $(id + "PreviewPanel").style.display=="none") { //if the rest validates AND we are not in preview mode
                validated = ValidateFields(window.iUploadImage.document.getElementById("imageUpload"));
            }
        }
    }                  
    return validated;                
}  

//validates the fields in the panel sent in. it looks for a field with the "required" class and then uses defaultText to see if the field has been completed
// YH 5/17/10
function ValidateFields(panel)
{
    if(typeof(panel) != 'object')   // if this is a name of an object and not the object itself
        panelToCheck = $(panel);    // RT 7/13/2010
    else
        panelToCheck = panel;

    var validated = true;
    
    try {
        panelToCheck.getElementsBySelector(".required").each(
           function(element){
                var defaultText = element.attributes["defaultText"] || "";
                if(element.value.trim() == defaultText.value || element.value.trim() == "")
                {
                    element.addClassName("validationFailed");
                    validated = false;
                }
                else
                {
                    element.removeClassName("validationFailed");
                }
           });
        panelToCheck.getElementsBySelector(".validate-password").each(
           function(element){
                //allow any character other than ' " and whitespace between 6 and 15 characters
                var pattern = /^[^'"\s]{6,15}$/;
                if(!pattern.test(element.value.trim()))
                {
                    element.addClassName("validationFailed");
                    validated = false;
                }
                else
                {
                    element.removeClassName("validationFailed");
                }
           }); 
        panelToCheck.getElementsBySelector(".validate-email").each(
           function(element){
                var pattern =/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
                if(!pattern.test(element.value.trim()))
                {
                    element.addClassName("validationFailed");
                    validated = false;
                }
                else
                {
                    element.removeClassName("validationFailed");
                }
           });  
       } catch (exc) {}                                    
       return validated;            
} 

//creates the wall post - refreshes the page on success
// button is the calling button
// id is the id of the element (standAlone or a post_id)
// identifier is the sku or question_id
function SubmitWallPost(button,id,type,identifier,wallType,returnUrl,postToFacebook)
{
    //if the type is comment and the id is standAlone then we need to get the actual type from the radio button
    if(type == 'comment' && id == 'standAlone')
    {
        type = $('form1').getInputs('radio', 'standAlonePostType').find(function(radio) { return radio.checked; }).value;
    }
    if(ValidatePost(id,type))
    {
        waitcursor();
        button.hide();
        $$('img[id $= PreviewButton]').each(function(element) {element.hide();});
        $$('img[id $= PreviewEditButton]').each(function(element) {element.hide();});
        button.next().show();        
        var postId = "";
        if(type == "review")
        {
            // only set the pros, cons & recommended fields if they exist in the form - RT, 6/30/2010
            var pros = ($(id + "Pros") == null ? "" : $(id + "Pros").value);
            var cons = ($(id + "Cons") == null ? "" : $(id + "Cons").value);
            var recommended = (eval(id + "Recommended") == null ? "" : eval(id + "Recommended"));
            CreateWallReview($(id + "BottomLine").value,pros,cons,eval("stars" + id),eval(id + "Recommended"),$(id + "OwnThis").checked,identifier,wallType,returnUrl,
                function(response)
                {
                    var result = response.parseJSON(); 
                    if(result.success == "true")
                    {
                        postId = result.pid;
                        WallPostSuccess(button,id,postId,type,returnUrl,"post",postToFacebook);
                    }
                    else
                    {
                        WallPostFailure(button,postId);
                    }
                }                        
            );
        }
        else if(type == "question")
        {
            CreateWallQuestion($(id + "QuestionTitle").value,$(id + "QuestionText").value,$(id + "OwnThis").checked,identifier,wallType,returnUrl,
                function(response)
                {
                    var result = response.parseJSON(); 
                    if(result.success == "true")
                    {
                        postId = result.pid;
                        WallPostSuccess(button,id,postId,type,returnUrl,"post",postToFacebook);
                    }
                    else
                    {
                        WallPostFailure(button,postId);
                    }                    
                }                        
            );                        
        } 
        else if(type == "commentPost")
        {
            CreateWallCommentPost($(id + "Comment").value,$(id + "OwnThis").checked,identifier,wallType,returnUrl,
                function(response)
                {
                    var result = response.parseJSON(); 
                    if(result.success == "true")
                    {
                        postId = result.pid;
                        WallPostSuccess(button,id,postId,type,returnUrl,"post",postToFacebook);
                    }
                    else
                    {
                        WallPostFailure(button,postId);
                    }                    
                }                        
            );                        
        } 
        else if(type == "upload")
        {
            if(uploadType == "video")
            {
                var video_title = $(id + "VideoTitle").value;
                var video_description = $(id + "VideoDescription").value;                

                if(video_description == $(id + "VideoDescription").attributes["defaultText"].value)
                {
                    video_description = "";
                }
                if(video_title == $(id + "VideoTitle").attributes["defaultText"].value)
                {
                    video_title = "";   
                } 
                
                CreateWallVideo(video_title,video_description,$F(id + "VideoPath"),$(id + "OwnThis").checked,identifier,wallType,returnUrl,
                    function(response)
                    {
                        var result = response.parseJSON(); 
                        if(result.success == "true")
                        {
                            postId = result.pid;
                            WallPostSuccess(button,id,postId,type,returnUrl,"post",postToFacebook);
                        }
                        else
                        {
                            WallPostFailure(button,postId);
                        }                    
                    }                        
                );  
            }
            else if(uploadType == "photo")
            {
                var img_title = $F(id + "ImageTitle");
                var img_text = $F(id + "ImageText");                

                if(img_text == $(id + "ImageText").attributes["defaultText"].value)
                {
                    img_text = "";
                }
                if(img_title == $(id + "ImageTitle").attributes["defaultText"].value)
                {
                    img_title = "";   
                } 
                CreateWallImage(img_title,img_text,$(id + "ImagePath").value,$(id + "OwnThis").checked,identifier,wallType,returnUrl,
                    function(response)
                    {
                        var result = response.parseJSON(); 
                        if(result.success == "true")
                        {
                            postId = result.pid;
                            WallPostSuccess(button,id,postId,type,returnUrl,"post",postToFacebook);
                        }
                        else
                        {
                            WallPostFailure(button,postId);
                        }                    
                    }                        
                );  
            }
                              
        } 
        else if(type == "comment")
        {
            CreateWallComment($("commentText_" + id).value,id,$(id + "OwnThis").checked,identifier,wallType,returnUrl,
                function(response)
                {
                    var result = response.parseJSON(); 
                    if(result.success == "true")
                    {
                        postId = result.cid;
                        WallPostSuccess(button,id,postId,type,returnUrl,"comment",postToFacebook);                   
                    }
                    else
                    {
                        WallPostFailure(button,postId);
                    }                    
                }                        
            );                        
        }                                                    
    }
}  

//called if a wall post is successfully posted
// postCategory is eiter post or comment - this is needed for the anchor (#post_id or #comment_id
// id is standAlone or the post id if it's coming from a specific post
// postId is the id of the new post
// postType is review, question, comment of commentPost
// YH 5/26/10
function WallPostSuccess(button,id,postId,postType,returnUrl,postCategory,postToFacebook)
{   
    //this uses jump, and not and anchor (#) because the anchor does not work properly when reloading
    var linkToPost = window.location.protocol + "//" + window.location.hostname + "/" + returnUrl + "?jump=" + postCategory + "_" + postId;
    if(postToFacebook)
    {
        PostToFacebook(id,postType,linkToPost);
    }       
    else
    {
        window.location.replace(linkToPost);
    }
    clearcursor();    
}

function WallPostFailure(button,id)
{
    clearcursor();
    button.next().hide();
    button.show();    
}

// Post a message to the users facebook page
// ObjectName, ObjectImagePath must be set elsewhere for this function to work
//YH 5/28/10
function PostToFacebook(id,postType,linkToPost)
{
    var message,picture,name,link,caption,description;
    picture = ObjectImagePath;
    link = linkToPost;
    caption = ObjectName;
    if(postType == "review")
    {    
        message = "Just posted a review of the " + ObjectName + " and rated it " + eval("stars" + id) + " stars." ;
        name = "";
        description = $(id + "BottomLine").value;
    }
    else if(postType == "question")
    {
        message = "Just asked a question about the " + ObjectName + "." ;
        name = $(id + "QuestionTitle").value;
        description = $(id + "QuestionText").value;                    
    } 
    else if(postType == "commentPost")
    {
        message = "Just posted a comment on the " + ObjectName + "." ;
        name = "";
        description = $(id + "Comment").value;                                          
    } 
    else if(postType == "comment")
    {        
        message = "Just commented on a post about the " + ObjectName + "." ;
        name = "";
        description = $("commentText_" + id).value;                                                               
    }
    else if(uploadType == "photo")
    {        
        message = "Just uploaded a photo of the " + ObjectName + "." ;
        name = "";
        description = $(id + "ImageText").value;                                                               
    }
    else if(uploadType == "video")
    {        
        message = "Just uploaded a video about the " + ObjectName + "." ;
        name = "";
        description = $(id + "VideoDescription").value;                                                               
    }
    
    var url = 'process.aspx';
    var params = 'type=posttofacebook&title=&message='+escape(message)+'&name='+escape(name)+'&description='+escape(description)+'&picture='+escape(picture)+'&link='+escape(link)+'&caption='+escape(caption);
    var myAjax = new Ajax.Request( url, { method: 'post', parameters: params, onComplete: window.location.replace(linkToPost)});       
}

function showSignUp() { $('loginPanel').hide(); $('signupPanel').show(); }
function showLogin() { $('signupPanel').hide(); $('loginPanel').show(); }

//id is the id of the panel containing the login
//panel is the panel to be validated
function WallLogin(id,panel,email,password,rememberMe)
{
    waitcursor(); 
    if(ValidateFields(panel))
    {
        LoginSiteUser(email,password,rememberMe,
            function(response)
            {
                if(response != "error")
                {
                    $("popupLoginError").hide();
                    var result = response.parseJSON();  
                    displayName = result.DisplayName;
                    loggedIn = true;
                    //hide all the login panels
                    $$('div[id $= WallLoginPanel]').each(function(element) {element.hide();});
                    //if the preview is showing, update the names shows
                    if($(id + "PreviewPanel").visible())
                    {
                        //ShowPreview(id);
                        //now we actually do post YH 6/7/10
                        $(id + "PreviewPostButton").onclick();
                    }
                    else
                    {
                        //show the welcome box
                        $(id + "LoggedInDisplayName").update(displayName);
                        $(id + "LoggedIn").show();
                        SetPostButtons(id,postType,true);
                    }
                    ajaxwin.close()
                }
                else
                {
                    $("popupLoginError").show();
                }
            }                        
        );
    }
    clearcursor(); 
}

//id is the id of the panel containing the login
//panel is the panel to be validated
function WallCreateAccount(id,panel,signupDisplayName,email,password,rememberMe)
{
    waitcursor(); 
    if(ValidateFields(panel))
    {
        CreateWallUser(signupDisplayName,email,password,rememberMe,
            function(response)
            {
                if(response != "error")
                {
                    $("popupSignupError").hide();
                    var result = response.parseJSON();  
                    displayName = result.DisplayName;
                    loggedIn = true;
                   //hide all the login panels
                    $$('div[id $= WallLoginPanel]').each(function(element) {element.hide();});
                    //if the preview is showing, update the names shows
                    if($(id + "PreviewPanel").visible())
                    {
                        //ShowPreview(id);
                        //now we actually do the post YH 6/7/10
                        $(id + "PreviewPostButton").onclick();
                    }
                    else
                    {
                        SetPostButtons(id,postType,true);
                    }
                    ajaxwin.close()
                }
                else
                {
                    $("popupSignupError").show();
                }
            }                        
        );
    }
    clearcursor(); 
}               

//end /sites/scripts/wall.js
//start /sites/scripts/wz_tooltip.js
/* This notice must be untouched at all times.
Copyright (c) 2002-2008 Walter Zorn. All rights reserved.

wz_tooltip.js	 v. 5.31

The latest version is available at
http://www.walterzorn.com
or http://www.devira.com
or http://www.walterzorn.de

Created 1.12.2002 by Walter Zorn (Web: http://www.walterzorn.com )
Last modified: 7.11.2008

Easy-to-use cross-browser tooltips.
Just include the script at the beginning of the <body> section, and invoke
Tip('Tooltip text') to show and UnTip() to hide the tooltip, from the desired
HTML eventhandlers. Example:
<a onmouseover="Tip('Some text')" onmouseout="UnTip()" href="index.htm">My home page</a>
No container DIV required.
By default, width and height of tooltips are automatically adapted to content.
Is even capable of dynamically converting arbitrary HTML elements to tooltips
by calling TagToTip('ID_of_HTML_element_to_be_converted') instead of Tip(),
which means you can put important, search-engine-relevant stuff into tooltips.
Appearance & behaviour of tooltips can be individually configured
via commands passed to Tip() or TagToTip().

Tab Width: 4
LICENSE: LGPL

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License (LGPL) as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

For more details on the GNU Lesser General Public License,
see http://www.gnu.org/copyleft/lesser.html
*/

var config = new Object();


//===================  GLOBAL TOOLTIP CONFIGURATION  =========================//
var tt_Debug	= true		// false or true - recommended: false once you release your page to the public
var tt_Enabled	= true		// Allows to (temporarily) suppress tooltips, e.g. by providing the user with a button that sets this global variable to false
var TagsToTip	= true		// false or true - if true, HTML elements to be converted to tooltips via TagToTip() are automatically hidden;
							// if false, you should hide those HTML elements yourself

// For each of the following config variables there exists a command, which is
// just the variablename in uppercase, to be passed to Tip() or TagToTip() to
// configure tooltips individually. Individual commands override global
// configuration. Order of commands is arbitrary.
// Example: onmouseover="Tip('Tooltip text', LEFT, true, BGCOLOR, '#FF9900', FADEIN, 400)"

config. Above			= false		// false or true - tooltip above mousepointer
config. BgColor			= '#f2f2f2'	// Background colour (HTML colour value, in quotes)
config. BgImg			= ''		// Path to background image, none if empty string ''
config. BgRepeat        = 'no-repeat'; //whether bg img repeats
config. BorderColor		= '#787878'
config. BorderStyle		= 'solid'	// Any permitted CSS value, but I recommend 'solid', 'dotted' or 'dashed'
config. BorderWidth		= 1
config. CenterMouse		= false		// false or true - center the tip horizontally below (or above) the mousepointer
config. ClickClose		= false		// false or true - close tooltip if the user clicks somewhere
config. ClickSticky		= false		// false or true - make tooltip sticky if user left-clicks on the hovered element while the tooltip is active
config. CloseBtn		= false		// false or true - closebutton in titlebar
config. CloseBtnColors	= ['#990000', '#FFFFFF', '#DD3333', '#FFFFFF']	// [Background, text, hovered background, hovered text] - use empty strings '' to inherit title colours
config. CloseBtnText	= '&nbsp;X&nbsp;'	// Close button text (may also be an image tag)
config. CopyContent		= true		// When converting a HTML element to a tooltip, copy only the element's content, rather than converting the element by its own
config. Delay			= 200		// Time span in ms until tooltip shows up
config. Duration		= 0			// Time span in ms after which the tooltip disappears; 0 for infinite duration, < 0 for delay in ms _after_ the onmouseout until the tooltip disappears
config. Exclusive		= false		// false or true - no other tooltip can appear until the current one has actively been closed
config. FadeIn			= 20		// Fade-in duration in ms, e.g. 400; 0 for no animation
config. FadeOut			= 20
config. FadeInterval	= 30		// Duration of each fade step in ms (recommended: 30) - shorter is smoother but causes more CPU-load
config. Fix				= null		// Fixated position, two modes. Mode 1: x- an y-coordinates in brackets, e.g. [210, 480]. Mode 2: Show tooltip at a position related to an HTML element: [ID of HTML element, x-offset, y-offset from HTML element], e.g. ['SomeID', 10, 30]. Value null (default) for no fixated positioning.
config. FollowMouse		= true		// false or true - tooltip follows the mouse
config. FontColor		= '#000000'
config. FontFace		= 'Verdana,Geneva,sans-serif'
config. FontSize		= '8pt'		// E.g. '9pt' or '12px' - unit is mandatory
config. FontWeight		= 'normal'	// 'normal' or 'bold';
config. Height			= 0			// Tooltip height; 0 for automatic adaption to tooltip content, < 0 (e.g. -100) for a maximum for automatic adaption
config. JumpHorz		= false		// false or true - jump horizontally to other side of mouse if tooltip would extend past clientarea boundary
config. JumpVert		= true		// false or true - jump vertically		"
config. Left			= false		// false or true - tooltip on the left of the mouse
config. OffsetX			= 14		// Horizontal offset of left-top corner from mousepointer
config. OffsetY			= 8			// Vertical offset
config. Opacity			= 100		// Integer between 0 and 100 - opacity of tooltip in percent
config. Padding			= 3			// Spacing between border and content
config. Shadow			= false		// false or true
config. ShadowColor		= '#C0C0C0'
config. ShadowWidth		= 5
config. Sticky			= false		// false or true - fixate tip, ie. don't follow the mouse and don't hide on mouseout
config. TextAlign		= 'left'	// 'left', 'right' or 'justify'
config. Title			= ''		// Default title text applied to all tips (no default title: empty string '')
config. TitleAlign		= 'left'	// 'left' or 'right' - text alignment inside the title bar
config. TitleBgColor	= ''		// If empty string '', BorderColor will be used
config. TitleFontColor	= '#FFFFFF'	// Color of title text - if '', BgColor (of tooltip body) will be used
config. TitleFontFace	= ''		// If '' use FontFace (boldified)
config. TitleFontSize	= ''		// If '' use FontSize
config. TitlePadding	= 2
config. Width			= 0			// Tooltip width; 0 for automatic adaption to tooltip content; < -1 (e.g. -240) for a maximum width for that automatic adaption;
									// -1: tooltip width confined to the width required for the titlebar
//=======  END OF TOOLTIP CONFIG, DO NOT CHANGE ANYTHING BELOW  ==============//




//=====================  PUBLIC  =============================================//
function Tip()
{
	tt_Tip(arguments, null);
}
function TagToTip()
{
	var t2t = tt_GetElt(arguments[0]);
	if(t2t)
		tt_Tip(arguments, t2t);
}
function UnTip()
{
	tt_OpReHref();
	if(tt_aV[DURATION] < 0 && (tt_iState & 0x2))
		tt_tDurt.Timer("tt_HideInit()", -tt_aV[DURATION], true);
	else if(!(tt_aV[STICKY] && (tt_iState & 0x2)))
		tt_HideInit();
}

//==================  PUBLIC PLUGIN API	 =====================================//
// Extension eventhandlers currently supported:
// OnLoadConfig, OnCreateContentString, OnSubDivsCreated, OnShow, OnMoveBefore,
// OnMoveAfter, OnHideInit, OnHide, OnKill

var tt_aElt = new Array(10), // Container DIV, outer title & body DIVs, inner title & body TDs, closebutton SPAN, shadow DIVs, and IFRAME to cover windowed elements in IE
tt_aV = new Array(),	// Caches and enumerates config data for currently active tooltip
tt_sContent,			// Inner tooltip text or HTML
tt_t2t, tt_t2tDad,		// Tag converted to tip, and its DOM parent element
tt_musX, tt_musY,
tt_over,
tt_x, tt_y, tt_w, tt_h; // Position, width and height of currently displayed tooltip

function tt_Extension()
{
	tt_ExtCmdEnum();
	tt_aExt[tt_aExt.length] = this;
	return this;
}
function tt_SetTipPos(x, y)
{
	var css = tt_aElt[0].style;

	tt_x = x;
	tt_y = y;
	css.left = x + "px";
	css.top = y + "px";
	if(tt_ie56)
	{
		var ifrm = tt_aElt[tt_aElt.length - 1];
		if(ifrm)
		{
			ifrm.style.left = css.left;
			ifrm.style.top = css.top;
		}
	}
}
function tt_HideInit()
{
	if(tt_iState)
	{
		tt_ExtCallFncs(0, "HideInit");
		tt_iState &= ~(0x4 | 0x8);
		if(tt_flagOpa && tt_aV[FADEOUT])
		{
			tt_tFade.EndTimer();
			if(tt_opa)
			{
				var n = Math.round(tt_aV[FADEOUT] / (tt_aV[FADEINTERVAL] * (tt_aV[OPACITY] / tt_opa)));
				tt_Fade(tt_opa, tt_opa, 0, n);
				return;
			}
		}
		tt_tHide.Timer("tt_Hide();", 1, false);
	}
}
function tt_Hide()
{
	if(tt_db && tt_iState)
	{
		tt_OpReHref();
		if(tt_iState & 0x2)
		{
			tt_aElt[0].style.visibility = "hidden";
			tt_ExtCallFncs(0, "Hide");
		}
		tt_tShow.EndTimer();
		tt_tHide.EndTimer();
		tt_tDurt.EndTimer();
		tt_tFade.EndTimer();
		if(!tt_op && !tt_ie)
		{
			tt_tWaitMov.EndTimer();
			tt_bWait = false;
		}
		if(tt_aV[CLICKCLOSE] || tt_aV[CLICKSTICKY])
			tt_RemEvtFnc(document, "mouseup", tt_OnLClick);
		tt_ExtCallFncs(0, "Kill");
		// In case of a TagToTip tip, hide converted DOM node and
		// re-insert it into DOM
		if(tt_t2t && !tt_aV[COPYCONTENT])
			tt_UnEl2Tip();
		tt_iState = 0;
		tt_over = null;
		tt_ResetMainDiv();
		if(tt_aElt[tt_aElt.length - 1])
			tt_aElt[tt_aElt.length - 1].style.display = "none";
	}
}
function tt_GetElt(id)
{
	return(document.getElementById ? document.getElementById(id)
			: document.all ? document.all[id]
			: null);
}
function tt_GetDivW(el)
{
	return(el ? (el.offsetWidth || el.style.pixelWidth || 0) : 0);
}
function tt_GetDivH(el)
{
	return(el ? (el.offsetHeight || el.style.pixelHeight || 0) : 0);
}
function tt_GetScrollX()
{
	return(window.pageXOffset || (tt_db ? (tt_db.scrollLeft || 0) : 0));
}
function tt_GetScrollY()
{
	return(window.pageYOffset || (tt_db ? (tt_db.scrollTop || 0) : 0));
}
function tt_GetClientW()
{
	return tt_GetWndCliSiz("Width");
}
function tt_GetClientH()
{
	return tt_GetWndCliSiz("Height");
}
function tt_GetEvtX(e)
{
	return (e ? ((typeof(e.pageX) != tt_u) ? e.pageX : (e.clientX + tt_GetScrollX())) : 0);
}
function tt_GetEvtY(e)
{
	return (e ? ((typeof(e.pageY) != tt_u) ? e.pageY : (e.clientY + tt_GetScrollY())) : 0);
}
function tt_AddEvtFnc(el, sEvt, PFnc)
{
	if(el)
	{
		if(el.addEventListener)
			el.addEventListener(sEvt, PFnc, false);
		else
			el.attachEvent("on" + sEvt, PFnc);
	}
}
function tt_RemEvtFnc(el, sEvt, PFnc)
{
	if(el)
	{
		if(el.removeEventListener)
			el.removeEventListener(sEvt, PFnc, false);
		else
			el.detachEvent("on" + sEvt, PFnc);
	}
}
function tt_GetDad(el)
{
	return(el.parentNode || el.parentElement || el.offsetParent);
}
function tt_MovDomNode(el, dadFrom, dadTo)
{
	if(dadFrom)
		dadFrom.removeChild(el);
	if(dadTo)
		dadTo.appendChild(el);
}

//======================  PRIVATE  ===========================================//
var tt_aExt = new Array(),	// Array of extension objects

tt_db, tt_op, tt_ie, tt_ie56, tt_bBoxOld,	// Browser flags
tt_body,
tt_ovr_,				// HTML element the mouse is currently over
tt_flagOpa,				// Opacity support: 1=IE, 2=Khtml, 3=KHTML, 4=Moz, 5=W3C
tt_maxPosX, tt_maxPosY,
tt_iState = 0,			// Tooltip active |= 1, shown |= 2, move with mouse |= 4, exclusive |= 8
tt_opa,					// Currently applied opacity
tt_bJmpVert, tt_bJmpHorz,// Tip temporarily on other side of mouse
tt_elDeHref,			// The tag from which we've removed the href attribute
// Timer
tt_tShow = new Number(0), tt_tHide = new Number(0), tt_tDurt = new Number(0),
tt_tFade = new Number(0), tt_tWaitMov = new Number(0),
tt_bWait = false,
tt_u = "undefined";


function tt_Init()
{
	tt_MkCmdEnum();
	// Send old browsers instantly to hell
	if(!tt_Browser() || !tt_MkMainDiv())
		return;
	tt_IsW3cBox();
	tt_OpaSupport();
	tt_AddEvtFnc(document, "mousemove", tt_Move);
	// In Debug mode we search for TagToTip() calls in order to notify
	// the user if they've forgotten to set the TagsToTip config flag
	if(TagsToTip || tt_Debug)
		tt_SetOnloadFnc();
	// Ensure the tip be hidden when the page unloads
	tt_AddEvtFnc(window, "unload", tt_Hide);
}
// Creates command names by translating config variable names to upper case
function tt_MkCmdEnum()
{
	var n = 0;
	for(var i in config)
	    if(i != 'toJSONString')
		eval("window." + i.toString().toUpperCase() + " = " + n++);
	tt_aV.length = n;
}
function tt_Browser()
{
	var n, nv, n6, w3c;

	n = navigator.userAgent.toLowerCase(),
	nv = navigator.appVersion;
	tt_op = (document.defaultView && typeof(eval("w" + "indow" + "." + "o" + "p" + "er" + "a")) != tt_u);
	tt_ie = n.indexOf("msie") != -1 && document.all && !tt_op;
	if(tt_ie)
	{
		var ieOld = (!document.compatMode || document.compatMode == "BackCompat");
		tt_db = !ieOld ? document.documentElement : (document.body || null);
		if(tt_db)
			tt_ie56 = parseFloat(nv.substring(nv.indexOf("MSIE") + 5)) >= 5.5
					&& typeof document.body.style.maxHeight == tt_u;
	}
	else
	{
		tt_db = document.documentElement || document.body ||
				(document.getElementsByTagName ? document.getElementsByTagName("body")[0]
				: null);
		if(!tt_op)
		{
			n6 = document.defaultView && typeof document.defaultView.getComputedStyle != tt_u;
			w3c = !n6 && document.getElementById;
		}
	}
	tt_body = (document.getElementsByTagName ? document.getElementsByTagName("body")[0]
				: (document.body || null));
	if(tt_ie || n6 || tt_op || w3c)
	{
		if(tt_body && tt_db)
		{
			if(document.attachEvent || document.addEventListener)
				return true;
		}
		else
			tt_Err("wz_tooltip.js must be included INSIDE the body section,"
					+ " immediately after the opening <body> tag.", false);
	}
	tt_db = null;
	return false;
}
function tt_MkMainDiv()
{
	// Create the tooltip DIV
	if(tt_body.insertAdjacentHTML)
		tt_body.insertAdjacentHTML("afterBegin", tt_MkMainDivHtm());
	else if(typeof tt_body.innerHTML != tt_u && document.createElement && tt_body.appendChild)
		tt_body.appendChild(tt_MkMainDivDom());
	if(window.tt_GetMainDivRefs /* FireFox Alzheimer */ && tt_GetMainDivRefs())
		return true;
	tt_db = null;
	return false;
}
function tt_MkMainDivHtm()
{
	return(
		'<div id="WzTtDiV"></div>' +
		(tt_ie56 ? ('<iframe id="WzTtIfRm" src="javascript:false" scrolling="no" frameborder="0" style="filter:Alpha(opacity=0);position:absolute;top:0px;left:0px;display:none;"></iframe>')
		: '')
	);
}
function tt_MkMainDivDom()
{
	var el = document.createElement("div");
	if(el)
		el.id = "WzTtDiV";
	return el;
}
function tt_GetMainDivRefs()
{
	tt_aElt[0] = tt_GetElt("WzTtDiV");
	if(tt_ie56 && tt_aElt[0])
	{
		tt_aElt[tt_aElt.length - 1] = tt_GetElt("WzTtIfRm");
		if(!tt_aElt[tt_aElt.length - 1])
			tt_aElt[0] = null;
	}
	if(tt_aElt[0])
	{
		var css = tt_aElt[0].style;

		css.visibility = "hidden";
		css.position = "absolute";
		css.overflow = "hidden";
		return true;
	}
	return false;
}
function tt_ResetMainDiv()
{
	tt_SetTipPos(0, 0);
	tt_aElt[0].innerHTML = "";
	tt_aElt[0].style.width = "0px";
	tt_h = 0;
}
function tt_IsW3cBox()
{
	var css = tt_aElt[0].style;

	css.padding = "10px";
	css.width = "40px";
	tt_bBoxOld = (tt_GetDivW(tt_aElt[0]) == 40);
	css.padding = "0px";
	tt_ResetMainDiv();
}
function tt_OpaSupport()
{
	var css = tt_body.style;

	tt_flagOpa = (typeof(css.KhtmlOpacity) != tt_u) ? 2
				: (typeof(css.KHTMLOpacity) != tt_u) ? 3
				: (typeof(css.MozOpacity) != tt_u) ? 4
				: (typeof(css.opacity) != tt_u) ? 5
				: (typeof(css.filter) != tt_u) ? 1
				: 0;
}
// Ported from http://dean.edwards.name/weblog/2006/06/again/
// (Dean Edwards et al.)
function tt_SetOnloadFnc()
{
	tt_AddEvtFnc(document, "DOMContentLoaded", tt_HideSrcTags);
	tt_AddEvtFnc(window, "load", tt_HideSrcTags);
	if(tt_body.attachEvent)
		tt_body.attachEvent("onreadystatechange",
			function() {
				if(tt_body.readyState == "complete")
					tt_HideSrcTags();
			} );
	if(/WebKit|KHTML/i.test(navigator.userAgent))
	{
		var t = setInterval(function() {
					if(/loaded|complete/.test(document.readyState))
					{
						clearInterval(t);
						tt_HideSrcTags();
					}
				}, 10);
	}
}
function tt_HideSrcTags()
{
	if(!window.tt_HideSrcTags || window.tt_HideSrcTags.done)
		return;
	window.tt_HideSrcTags.done = true;
	if(!tt_HideSrcTagsRecurs(tt_body))
		tt_Err("There are HTML elements to be converted to tooltips.\nIf you"
				+ " want these HTML elements to be automatically hidden, you"
				+ " must edit wz_tooltip.js, and set TagsToTip in the global"
				+ " tooltip configuration to true.", true);
}
function tt_HideSrcTagsRecurs(dad)
{
	var ovr, asT2t;
	// Walk the DOM tree for tags that have an onmouseover or onclick attribute
	// containing a TagToTip('...') call.
	// (.childNodes first since .children is bugous in Safari)
	var a = dad.childNodes || dad.children || null;

	for(var i = a ? a.length : 0; i;)
	{--i;
		if(!tt_HideSrcTagsRecurs(a[i]))
			return false;
		ovr = a[i].getAttribute ? (a[i].getAttribute("onmouseover") || a[i].getAttribute("onclick"))
				: (typeof a[i].onmouseover == "function") ? (a[i].onmouseover || a[i].onclick)
				: null;
		if(ovr)
		{
			asT2t = ovr.toString().match(/TagToTip\s*\(\s*'[^'.]+'\s*[\),]/);
			if(asT2t && asT2t.length)
			{
				if(!tt_HideSrcTag(asT2t[0]))
					return false;
			}
		}
	}
	return true;
}
function tt_HideSrcTag(sT2t)
{
	var id, el;

	// The ID passed to the found TagToTip() call identifies an HTML element
	// to be converted to a tooltip, so hide that element
	id = sT2t.replace(/.+'([^'.]+)'.+/, "$1");
	el = tt_GetElt(id);
	if(el)
	{
		if(tt_Debug && !TagsToTip)
			return false;
		else
			el.style.display = "none";
	}
	else
		tt_Err("Invalid ID\n'" + id + "'\npassed to TagToTip()."
				+ " There exists no HTML element with that ID.", true);
	return true;
}
function tt_Tip(arg, t2t)
{
	if(!tt_db || (tt_iState & 0x8))
		return;
	if(tt_iState)
		tt_Hide();
	if(!tt_Enabled)
		return;
	tt_t2t = t2t;
	if(!tt_ReadCmds(arg))
		return;
	tt_iState = 0x1 | 0x4;
	tt_AdaptConfig1();
	tt_MkTipContent(arg);
	tt_MkTipSubDivs();
	tt_FormatTip();
	tt_bJmpVert = false;
	tt_bJmpHorz = false;
	tt_maxPosX = tt_GetClientW() + tt_GetScrollX() - tt_w - 1;
	tt_maxPosY = tt_GetClientH() + tt_GetScrollY() - tt_h - 1;
	tt_AdaptConfig2();
	// Ensure the tip be shown and positioned before the first onmousemove
	tt_OverInit();
	tt_ShowInit();
	tt_Move();
}
function tt_ReadCmds(a)
{
	var i;

	// First load the global config values, to initialize also values
	// for which no command is passed
	i = 0;
	for(var j in config)
		if(j != 'toJSONString')
		    tt_aV[i++] = config[j];
	// Then replace each cached config value for which a command is
	// passed (ensure the # of command args plus value args be even)
	if(a.length & 1)
	{
		for(i = a.length - 1; i > 0; i -= 2)
			tt_aV[a[i - 1]] = a[i];
		return true;
	}
	tt_Err("Incorrect call of Tip() or TagToTip().\n"
			+ "Each command must be followed by a value.", true);
	return false;
}
function tt_AdaptConfig1()
{
	tt_ExtCallFncs(0, "LoadConfig");
	// Inherit unspecified title formattings from body
	if(!tt_aV[TITLEBGCOLOR].length)
		tt_aV[TITLEBGCOLOR] = tt_aV[BORDERCOLOR];
	if(!tt_aV[TITLEFONTCOLOR].length)
		tt_aV[TITLEFONTCOLOR] = tt_aV[BGCOLOR];
	if(!tt_aV[TITLEFONTFACE].length)
		tt_aV[TITLEFONTFACE] = tt_aV[FONTFACE];
	if(!tt_aV[TITLEFONTSIZE].length)
		tt_aV[TITLEFONTSIZE] = tt_aV[FONTSIZE];
	if(tt_aV[CLOSEBTN])
	{
		// Use title colours for non-specified closebutton colours
		if(!tt_aV[CLOSEBTNCOLORS])
			tt_aV[CLOSEBTNCOLORS] = new Array("", "", "", "");
		for(var i = 4; i;)
		{--i;
			if(!tt_aV[CLOSEBTNCOLORS][i].length)
				tt_aV[CLOSEBTNCOLORS][i] = (i & 1) ? tt_aV[TITLEFONTCOLOR] : tt_aV[TITLEBGCOLOR];
		}
		// Enforce titlebar be shown
		if(!tt_aV[TITLE].length)
			tt_aV[TITLE] = " ";
	}
	// Circumvents broken display of images and fade-in flicker in Geckos < 1.8
	if(tt_aV[OPACITY] == 100 && typeof tt_aElt[0].style.MozOpacity != tt_u && !Array.every)
		tt_aV[OPACITY] = 99;
	// Smartly shorten the delay for fade-in tooltips
	if(tt_aV[FADEIN] && tt_flagOpa && tt_aV[DELAY] > 100)
		tt_aV[DELAY] = Math.max(tt_aV[DELAY] - tt_aV[FADEIN], 100);
}
function tt_AdaptConfig2()
{
	if(tt_aV[CENTERMOUSE])
	{
		tt_aV[OFFSETX] -= ((tt_w - (tt_aV[SHADOW] ? tt_aV[SHADOWWIDTH] : 0)) >> 1);
		tt_aV[JUMPHORZ] = false;
	}
}
// Expose content globally so extensions can modify it
function tt_MkTipContent(a)
{
	if(tt_t2t)
	{
		if(tt_aV[COPYCONTENT])
			tt_sContent = tt_t2t.innerHTML;
		else
			tt_sContent = "";
	}
	else
		tt_sContent = a[0];
	tt_ExtCallFncs(0, "CreateContentString");
}
function tt_MkTipSubDivs()
{
	var sCss = 'position:relative;margin:0px;padding:0px;border-width:0px;left:0px;top:0px;line-height:normal;width:auto;',
	sTbTrTd = ' cellspacing="0" cellpadding="0" border="0" style="' + sCss + '"><tbody style="' + sCss + '"><tr><td ';

	tt_aElt[0].style.width = tt_GetClientW() + "px";
	tt_aElt[0].innerHTML =
		(''
		+ (tt_aV[TITLE].length ?
			('<div id="WzTiTl" style="position:relative;z-index:1;">'
			+ '<table id="WzTiTlTb"' + sTbTrTd + 'id="WzTiTlI" style="' + sCss + '">'
			+ tt_aV[TITLE]
			+ '</td>'
			+ (tt_aV[CLOSEBTN] ?
				('<td align="right" style="' + sCss
				+ 'text-align:right;">'
				+ '<span id="WzClOsE" style="position:relative;left:2px;padding-left:2px;padding-right:2px;'
				+ 'cursor:' + (tt_ie ? 'hand' : 'pointer')
				+ ';" onmouseover="tt_OnCloseBtnOver(1)" onmouseout="tt_OnCloseBtnOver(0)" onclick="tt_HideInit()">'
				+ tt_aV[CLOSEBTNTEXT]
				+ '</span></td>')
				: '')
			+ '</tr></tbody></table></div>')
			: '')
		+ '<div id="WzBoDy" style="position:relative;z-index:0;">'
		+ '<table' + sTbTrTd + 'id="WzBoDyI" style="' + sCss + '">'
		+ tt_sContent
		+ '</td></tr></tbody></table></div>'
		+ (tt_aV[SHADOW]
			? ('<div id="WzTtShDwR" style="position:absolute;overflow:hidden;"></div>'
				+ '<div id="WzTtShDwB" style="position:relative;overflow:hidden;"></div>')
			: '')
		);
	tt_GetSubDivRefs();
	// Convert DOM node to tip
	if(tt_t2t && !tt_aV[COPYCONTENT])
		tt_El2Tip();
	tt_ExtCallFncs(0, "SubDivsCreated");
}
function tt_GetSubDivRefs()
{
	var aId = new Array("WzTiTl", "WzTiTlTb", "WzTiTlI", "WzClOsE", "WzBoDy", "WzBoDyI", "WzTtShDwB", "WzTtShDwR");

	for(var i = aId.length; i; --i)
		tt_aElt[i] = tt_GetElt(aId[i - 1]);
}
function tt_FormatTip()
{
	var css, w, h, pad = tt_aV[PADDING], padT, wBrd = tt_aV[BORDERWIDTH],
	iOffY, iOffSh, iAdd = (pad + wBrd) << 1;

	//--------- Title DIV ----------
	if(tt_aV[TITLE].length)
	{
		padT = tt_aV[TITLEPADDING];
		css = tt_aElt[1].style;
		css.background = tt_aV[TITLEBGCOLOR];
		css.paddingTop = css.paddingBottom = padT + "px";
		css.paddingLeft = css.paddingRight = (padT + 2) + "px";
		css = tt_aElt[3].style;
		css.color = tt_aV[TITLEFONTCOLOR];
		if(tt_aV[WIDTH] == -1)
			css.whiteSpace = "nowrap";
		css.fontFamily = tt_aV[TITLEFONTFACE];
		css.fontSize = tt_aV[TITLEFONTSIZE];
		css.fontWeight = "bold";
		css.textAlign = tt_aV[TITLEALIGN];
		// Close button DIV
		if(tt_aElt[4])
		{
			css = tt_aElt[4].style;
			css.background = tt_aV[CLOSEBTNCOLORS][0];
			css.color = tt_aV[CLOSEBTNCOLORS][1];
			css.fontFamily = tt_aV[TITLEFONTFACE];
			css.fontSize = tt_aV[TITLEFONTSIZE];
			css.fontWeight = "bold";
		}
		if(tt_aV[WIDTH] > 0)
			tt_w = tt_aV[WIDTH];
		else
		{
			tt_w = tt_GetDivW(tt_aElt[3]) + tt_GetDivW(tt_aElt[4]);
			// Some spacing between title DIV and closebutton
			if(tt_aElt[4])
				tt_w += pad;
			// Restrict auto width to max width
			if(tt_aV[WIDTH] < -1 && tt_w > -tt_aV[WIDTH])
				tt_w = -tt_aV[WIDTH];
		}
		// Ensure the top border of the body DIV be covered by the title DIV
		iOffY = -wBrd;
	}
	else
	{
		tt_w = 0;
		iOffY = 0;
	}

	//-------- Body DIV ------------
	css = tt_aElt[5].style;
	css.top = iOffY + "px";
	if(wBrd)
	{
		css.borderColor = tt_aV[BORDERCOLOR];
		css.borderStyle = tt_aV[BORDERSTYLE];
		css.backgroundRepeat = tt_aV[BGREPEAT];
		css.borderWidth = wBrd + "px";
	}
	if(tt_aV[BGCOLOR].length)
		css.background = tt_aV[BGCOLOR];
	if(tt_aV[BGIMG].length)
		css.backgroundImage = "url(" + tt_aV[BGIMG] + ")";
	css.padding = pad + "px";
	css.textAlign = tt_aV[TEXTALIGN];
	if(tt_aV[HEIGHT])
	{
		css.overflow = "auto";
		if(tt_aV[HEIGHT] > 0)
			css.height = (tt_aV[HEIGHT] + iAdd) + "px";
		else
			tt_h = iAdd - tt_aV[HEIGHT];
	}
	// TD inside body DIV
	css = tt_aElt[6].style;
	css.color = tt_aV[FONTCOLOR];
	css.fontFamily = tt_aV[FONTFACE];
	css.fontSize = tt_aV[FONTSIZE];
	css.fontWeight = tt_aV[FONTWEIGHT];
	css.textAlign = tt_aV[TEXTALIGN];
	if(tt_aV[WIDTH] > 0)
		w = tt_aV[WIDTH];
	// Width like title (if existent)
	else if(tt_aV[WIDTH] == -1 && tt_w)
		w = tt_w;
	else
	{
		// Measure width of the body's inner TD, as some browsers would expand
		// the container and outer body DIV to 100%
		w = tt_GetDivW(tt_aElt[6]);
		// Restrict auto width to max width
		if(tt_aV[WIDTH] < -1 && w > -tt_aV[WIDTH])
			w = -tt_aV[WIDTH];
	}
	if(w > tt_w)
		tt_w = w;
	tt_w += iAdd;

	//--------- Shadow DIVs ------------
	if(tt_aV[SHADOW])
	{
		tt_w += tt_aV[SHADOWWIDTH];
		iOffSh = Math.floor((tt_aV[SHADOWWIDTH] * 4) / 3);
		// Bottom shadow
		css = tt_aElt[7].style;
		css.top = iOffY + "px";
		css.left = iOffSh + "px";
		css.width = (tt_w - iOffSh - tt_aV[SHADOWWIDTH]) + "px";
		css.height = tt_aV[SHADOWWIDTH] + "px";
		css.background = tt_aV[SHADOWCOLOR];
		// Right shadow
		css = tt_aElt[8].style;
		css.top = iOffSh + "px";
		css.left = (tt_w - tt_aV[SHADOWWIDTH]) + "px";
		css.width = tt_aV[SHADOWWIDTH] + "px";
		css.background = tt_aV[SHADOWCOLOR];
	}
	else
		iOffSh = 0;

	//-------- Container DIV -------
	tt_SetTipOpa(tt_aV[FADEIN] ? 0 : tt_aV[OPACITY]);
	tt_FixSize(iOffY, iOffSh);
}
// Fixate the size so it can't dynamically change while the tooltip is moving.
function tt_FixSize(iOffY, iOffSh)
{
	var wIn, wOut, h, add, pad = tt_aV[PADDING], wBrd = tt_aV[BORDERWIDTH], i;

	tt_aElt[0].style.width = tt_w + "px";
	tt_aElt[0].style.pixelWidth = tt_w;
	wOut = tt_w - ((tt_aV[SHADOW]) ? tt_aV[SHADOWWIDTH] : 0);
	// Body
	wIn = wOut;
	if(!tt_bBoxOld)
		wIn -= (pad + wBrd) << 1;
	tt_aElt[5].style.width = wIn + "px";
	// Title
	if(tt_aElt[1])
	{
		wIn = wOut - ((tt_aV[TITLEPADDING] + 2) << 1);
		if(!tt_bBoxOld)
			wOut = wIn;
		tt_aElt[1].style.width = wOut + "px";
		tt_aElt[2].style.width = wIn + "px";
	}
	// Max height specified
	if(tt_h)
	{
		h = tt_GetDivH(tt_aElt[5]);
		if(h > tt_h)
		{
			if(!tt_bBoxOld)
				tt_h -= (pad + wBrd) << 1;
			tt_aElt[5].style.height = tt_h + "px";
		}
	}
	tt_h = tt_GetDivH(tt_aElt[0]) + iOffY;
	// Right shadow
	if(tt_aElt[8])
		tt_aElt[8].style.height = (tt_h - iOffSh) + "px";
	i = tt_aElt.length - 1;
	if(tt_aElt[i])
	{
		tt_aElt[i].style.width = tt_w + "px";
		tt_aElt[i].style.height = tt_h + "px";
	}
}
function tt_DeAlt(el)
{
	var aKid;

	if(el)
	{
		if(el.alt)
			el.alt = "";
		if(el.title)
			el.title = "";
		aKid = el.childNodes || el.children || null;
		if(aKid)
		{
			for(var i = aKid.length; i;)
				tt_DeAlt(aKid[--i]);
		}
	}
}
// This hack removes the native tooltips over links in Opera
function tt_OpDeHref(el)
{
	if(!tt_op)
		return;
	if(tt_elDeHref)
		tt_OpReHref();
	while(el)
	{
		if(el.hasAttribute && el.hasAttribute("href"))
		{
			el.t_href = el.getAttribute("href");
			el.t_stats = window.status;
			el.removeAttribute("href");
			el.style.cursor = "hand";
			tt_AddEvtFnc(el, "mousedown", tt_OpReHref);
			window.status = el.t_href;
			tt_elDeHref = el;
			break;
		}
		el = tt_GetDad(el);
	}
}
function tt_OpReHref()
{
	if(tt_elDeHref)
	{
		tt_elDeHref.setAttribute("href", tt_elDeHref.t_href);
		tt_RemEvtFnc(tt_elDeHref, "mousedown", tt_OpReHref);
		window.status = tt_elDeHref.t_stats;
		tt_elDeHref = null;
	}
}
function tt_El2Tip()
{
	var css = tt_t2t.style;

	// Store previous positioning
	tt_t2t.t_cp = css.position;
	tt_t2t.t_cl = css.left;
	tt_t2t.t_ct = css.top;
	tt_t2t.t_cd = css.display;
	// Store the tag's parent element so we can restore that DOM branch
	// when the tooltip is being hidden
	tt_t2tDad = tt_GetDad(tt_t2t);
	tt_MovDomNode(tt_t2t, tt_t2tDad, tt_aElt[6]);
	css.display = "block";
	css.position = "static";
	css.left = css.top = css.marginLeft = css.marginTop = "0px";
}
function tt_UnEl2Tip()
{
	// Restore positioning and display
	var css = tt_t2t.style;

	css.display = tt_t2t.t_cd;
	tt_MovDomNode(tt_t2t, tt_GetDad(tt_t2t), tt_t2tDad);
	css.position = tt_t2t.t_cp;
	css.left = tt_t2t.t_cl;
	css.top = tt_t2t.t_ct;
	tt_t2tDad = null;
}
function tt_OverInit()
{
	if(window.event)
		tt_over = window.event.target || window.event.srcElement;
	else
		tt_over = tt_ovr_;
	tt_DeAlt(tt_over);
	tt_OpDeHref(tt_over);
}
function tt_ShowInit()
{
	tt_tShow.Timer("tt_Show()", tt_aV[DELAY], true);
	if(tt_aV[CLICKCLOSE] || tt_aV[CLICKSTICKY])
		tt_AddEvtFnc(document, "mouseup", tt_OnLClick);
}
function tt_Show()
{
	var css = tt_aElt[0].style;

	// Override the z-index of the topmost wz_dragdrop.js D&D item
	css.zIndex = Math.max((window.dd && dd.z) ? (dd.z + 2) : 0, 1010);
	if(tt_aV[STICKY] || !tt_aV[FOLLOWMOUSE])
		tt_iState &= ~0x4;
	if(tt_aV[EXCLUSIVE])
		tt_iState |= 0x8;
	if(tt_aV[DURATION] > 0)
		tt_tDurt.Timer("tt_HideInit()", tt_aV[DURATION], true);
	tt_ExtCallFncs(0, "Show")
	css.visibility = "visible";
	tt_iState |= 0x2;
	if(tt_aV[FADEIN])
		tt_Fade(0, 0, tt_aV[OPACITY], Math.round(tt_aV[FADEIN] / tt_aV[FADEINTERVAL]));
	tt_ShowIfrm();
}
function tt_ShowIfrm()
{
	if(tt_ie56)
	{
		var ifrm = tt_aElt[tt_aElt.length - 1];
		if(ifrm)
		{
			var css = ifrm.style;
			css.zIndex = tt_aElt[0].style.zIndex - 1;
			css.display = "block";
		}
	}
}
function tt_Move(e)
{
	if(e)
		tt_ovr_ = e.target || e.srcElement;
	e = e || window.event;
	if(e)
	{
		tt_musX = tt_GetEvtX(e);
		tt_musY = tt_GetEvtY(e);
	}
	if(tt_iState & 0x4)
	{
		// Prevent jam of mousemove events
		if(!tt_op && !tt_ie)
		{
			if(tt_bWait)
				return;
			tt_bWait = true;
			tt_tWaitMov.Timer("tt_bWait = false;", 1, true);
		}
		if(tt_aV[FIX])
		{
			tt_iState &= ~0x4;
			tt_PosFix();
		}
		else if(!tt_ExtCallFncs(e, "MoveBefore"))
			tt_SetTipPos(tt_Pos(0), tt_Pos(1));
		tt_ExtCallFncs([tt_musX, tt_musY], "MoveAfter")
	}
}
function tt_Pos(iDim)
{
	var iX, bJmpMod, cmdAlt, cmdOff, cx, iMax, iScrl, iMus, bJmp;

	// Map values according to dimension to calculate
	if(iDim)
	{
		bJmpMod = tt_aV[JUMPVERT];
		cmdAlt = ABOVE;
		cmdOff = OFFSETY;
		cx = tt_h;
		iMax = tt_maxPosY;
		iScrl = tt_GetScrollY();
		iMus = tt_musY;
		bJmp = tt_bJmpVert;
	}
	else
	{
		bJmpMod = tt_aV[JUMPHORZ];
		cmdAlt = LEFT;
		cmdOff = OFFSETX;
		cx = tt_w;
		iMax = tt_maxPosX;
		iScrl = tt_GetScrollX();
		iMus = tt_musX;
		bJmp = tt_bJmpHorz;
	}
	if(bJmpMod)
	{
		if(tt_aV[cmdAlt] && (!bJmp || tt_CalcPosAlt(iDim) >= iScrl + 16))
			iX = tt_PosAlt(iDim);
		else if(!tt_aV[cmdAlt] && bJmp && tt_CalcPosDef(iDim) > iMax - 16)
			iX = tt_PosAlt(iDim);
		else
			iX = tt_PosDef(iDim);
	}
	else
	{
		iX = iMus;
		if(tt_aV[cmdAlt])
			iX -= cx + tt_aV[cmdOff] - (tt_aV[SHADOW] ? tt_aV[SHADOWWIDTH] : 0);
		else
			iX += tt_aV[cmdOff];
	}
	// Prevent tip from extending past clientarea boundary
	if(iX > iMax)
		iX = bJmpMod ? tt_PosAlt(iDim) : iMax;
	// In case of insufficient space on both sides, ensure the left/upper part
	// of the tip be visible
	if(iX < iScrl)
		iX = bJmpMod ? tt_PosDef(iDim) : iScrl;
	return iX;
}
function tt_PosDef(iDim)
{
	if(iDim)
		tt_bJmpVert = tt_aV[ABOVE];
	else
		tt_bJmpHorz = tt_aV[LEFT];
	return tt_CalcPosDef(iDim);
}
function tt_PosAlt(iDim)
{
	if(iDim)
		tt_bJmpVert = !tt_aV[ABOVE];
	else
		tt_bJmpHorz = !tt_aV[LEFT];
	return tt_CalcPosAlt(iDim);
}
function tt_CalcPosDef(iDim)
{
	return iDim ? (tt_musY + tt_aV[OFFSETY]) : (tt_musX + tt_aV[OFFSETX]);
}
function tt_CalcPosAlt(iDim)
{
	var cmdOff = iDim ? OFFSETY : OFFSETX;
	var dx = tt_aV[cmdOff] - (tt_aV[SHADOW] ? tt_aV[SHADOWWIDTH] : 0);
	if(tt_aV[cmdOff] > 0 && dx <= 0)
		dx = 1;
	return((iDim ? (tt_musY - tt_h) : (tt_musX - tt_w)) - dx);
}
function tt_PosFix()
{
	var iX, iY;

	if(typeof(tt_aV[FIX][0]) == "number")
	{
		iX = tt_aV[FIX][0];
		iY = tt_aV[FIX][1];
	}
	else
	{
		if(typeof(tt_aV[FIX][0]) == "string")
			el = tt_GetElt(tt_aV[FIX][0]);
		// First slot in array is direct reference to HTML element
		else
			el = tt_aV[FIX][0];
		iX = tt_aV[FIX][1];
		iY = tt_aV[FIX][2];
		// By default, vert pos is related to bottom edge of HTML element
		if(!tt_aV[ABOVE] && el)
			iY += tt_GetDivH(el);
		for(; el; el = el.offsetParent)
		{
			iX += el.offsetLeft || 0;
			iY += el.offsetTop || 0;
		}
	}
	// For a fixed tip positioned above the mouse, use the bottom edge as anchor
	// (recommended by Christophe Rebeschini, 31.1.2008)
	if(tt_aV[ABOVE])
		iY -= tt_h;
	tt_SetTipPos(iX, iY);
}
function tt_Fade(a, now, z, n)
{
	if(n)
	{
		now += Math.round((z - now) / n);
		if((z > a) ? (now >= z) : (now <= z))
			now = z;
		else
			tt_tFade.Timer(
				"tt_Fade("
				+ a + "," + now + "," + z + "," + (n - 1)
				+ ")",
				tt_aV[FADEINTERVAL],
				true
			);
	}
	now ? tt_SetTipOpa(now) : tt_Hide();
}
function tt_SetTipOpa(opa)
{
	// To circumvent the opacity nesting flaws of IE, we set the opacity
	// for each sub-DIV separately, rather than for the container DIV.
	tt_SetOpa(tt_aElt[5], opa);
	if(tt_aElt[1])
		tt_SetOpa(tt_aElt[1], opa);
	if(tt_aV[SHADOW])
	{
		opa = Math.round(opa * 0.8);
		tt_SetOpa(tt_aElt[7], opa);
		tt_SetOpa(tt_aElt[8], opa);
	}
}
function tt_OnCloseBtnOver(iOver)
{
	var css = tt_aElt[4].style;

	iOver <<= 1;
	css.background = tt_aV[CLOSEBTNCOLORS][iOver];
	css.color = tt_aV[CLOSEBTNCOLORS][iOver + 1];
}
function tt_OnLClick(e)
{
	//  Ignore right-clicks
	e = e || window.event;
	if(!((e.button && e.button & 2) || (e.which && e.which == 3)))
	{
		if(tt_aV[CLICKSTICKY] && (tt_iState & 0x4))
		{
			tt_aV[STICKY] = true;
			tt_iState &= ~0x4;
		}
		else if(tt_aV[CLICKCLOSE])
			tt_HideInit();
	}
}
function tt_Int(x)
{
	var y;

	return(isNaN(y = parseInt(x)) ? 0 : y);
}
Number.prototype.Timer = function(s, iT, bUrge)
{
	if(!this.value || bUrge)
		this.value = window.setTimeout(s, iT);
}
Number.prototype.EndTimer = function()
{
	if(this.value)
	{
		window.clearTimeout(this.value);
		this.value = 0;
	}
}
function tt_GetWndCliSiz(s)
{
	var db, y = window["inner" + s], sC = "client" + s, sN = "number";
	if(typeof y == sN)
	{
		var y2;
		return(
			// Gecko or Opera with scrollbar
			// ... quirks mode
			((db = document.body) && typeof(y2 = db[sC]) == sN && y2 &&  y2 <= y) ? y2 
			// ... strict mode
			: ((db = document.documentElement) && typeof(y2 = db[sC]) == sN && y2 && y2 <= y) ? y2
			// No scrollbar, or clientarea size == 0, or other browser (KHTML etc.)
			: y
		);
	}
	// IE
	return(
		// document.documentElement.client+s functional, returns > 0
		((db = document.documentElement) && (y = db[sC])) ? y
		// ... not functional, in which case document.body.client+s 
		// is the clientarea size, fortunately
		: document.body[sC]
	);
}
function tt_SetOpa(el, opa)
{
	var css = el.style;

	tt_opa = opa;
	if(tt_flagOpa == 1)
	{
		if(opa < 100)
		{
			// Hacks for bugs of IE:
			// 1.) Once a CSS filter has been applied, fonts are no longer
			// anti-aliased, so we store the previous 'non-filter' to be
			// able to restore it
			if(typeof(el.filtNo) == tt_u)
				el.filtNo = css.filter;
			// 2.) A DIV cannot be made visible in a single step if an
			// opacity < 100 has been applied while the DIV was hidden
			var bVis = css.visibility != "hidden";
			// 3.) In IE6, applying an opacity < 100 has no effect if the
			//	   element has no layout (position, size, zoom, ...)
			css.zoom = "100%";
			if(!bVis)
				css.visibility = "visible";
			css.filter = "alpha(opacity=" + opa + ")";
			if(!bVis)
				css.visibility = "hidden";
		}
		else if(typeof(el.filtNo) != tt_u)
			// Restore 'non-filter'
			css.filter = el.filtNo;
	}
	else
	{
		opa /= 100.0;
		switch(tt_flagOpa)
		{
		case 2:
			css.KhtmlOpacity = opa; break;
		case 3:
			css.KHTMLOpacity = opa; break;
		case 4:
			css.MozOpacity = opa; break;
		case 5:
			css.opacity = opa; break;
		}
	}
}
function tt_Err(sErr, bIfDebug)
{
	if(tt_Debug || !bIfDebug)
		alert("Tooltip Script Error Message:\n\n" + sErr);
}

//============  EXTENSION (PLUGIN) MANAGER  ===============//
function tt_ExtCmdEnum()
{
	var s;

	// Add new command(s) to the commands enum
	for(var i in config)
	{
		s = "window." + i.toString().toUpperCase();
		if(eval("typeof(" + s + ") == tt_u"))
		{
			eval(s + " = " + tt_aV.length);
			tt_aV[tt_aV.length] = null;
		}
	}
}
function tt_ExtCallFncs(arg, sFnc)
{
	var b = false;
	for(var i = tt_aExt.length; i;)
	{--i;
		var fnc = tt_aExt[i]["On" + sFnc];
		// Call the method the extension has defined for this event
		if(fnc && fnc(arg))
			b = true;
	}
	return b;
}

tt_Init();
//end /sites/scripts/wz_tooltip.js
//start /sites/scripts/prototype-1.5.1.1-min.js

var Prototype={Version:'1.5.1.1',Browser:{IE:!!(window.attachEvent&&!window.opera),Opera:!!window.opera,WebKit:navigator.userAgent.indexOf('AppleWebKit/')>-1,Gecko:navigator.userAgent.indexOf('Gecko')>-1&&navigator.userAgent.indexOf('KHTML')==-1},BrowserFeatures:{XPath:!!document.evaluate,ElementExtensions:!!window.HTMLElement,SpecificElementExtensions:(document.createElement('div').__proto__!==document.createElement('form').__proto__)},ScriptFragment:'<script[^>]*>([\\S\\s]*?)<\/script>',JSONFilter:/^\/\*-secure-([\s\S]*)\*\/\s*$/,emptyFunction:function(){},K:function(x){return x}}
var Class={create:function(){return function(){this.initialize.apply(this,arguments);}}}
var Abstract=new Object();Object.extend=function(destination,source){for(var property in source){destination[property]=source[property];}
return destination;}
Object.extend(Object,{inspect:function(object){try{if(object===undefined)return'undefined';if(object===null)return'null';return object.inspect?object.inspect():object.toString();}catch(e){if(e instanceof RangeError)return'...';throw e;}},toJSON:function(object){var type=typeof object;switch(type){case'undefined':case'function':case'unknown':return;case'boolean':return object.toString();}
if(object===null)return'null';if(object.toJSON)return object.toJSON();if(object.ownerDocument===document)return;var results=[];for(var property in object){var value=Object.toJSON(object[property]);if(value!==undefined)
results.push(property.toJSON()+': '+value);}
return'{'+results.join(', ')+'}';},keys:function(object){var keys=[];for(var property in object)
keys.push(property);return keys;},values:function(object){var values=[];for(var property in object)
values.push(object[property]);return values;},clone:function(object){return Object.extend({},object);}});Function.prototype.bind=function(){var __method=this,args=$A(arguments),object=args.shift();return function(){return __method.apply(object,args.concat($A(arguments)));}}
Function.prototype.bindAsEventListener=function(object){var __method=this,args=$A(arguments),object=args.shift();return function(event){return __method.apply(object,[event||window.event].concat(args));}}
Object.extend(Number.prototype,{toColorPart:function(){return this.toPaddedString(2,16);},succ:function(){return this+1;},times:function(iterator){$R(0,this,true).each(iterator);return this;},toPaddedString:function(length,radix){var string=this.toString(radix||10);return'0'.times(length-string.length)+string;},toJSON:function(){return isFinite(this)?this.toString():'null';}});Date.prototype.toJSON=function(){return'"'+this.getFullYear()+'-'+
(this.getMonth()+1).toPaddedString(2)+'-'+
this.getDate().toPaddedString(2)+'T'+
this.getHours().toPaddedString(2)+':'+
this.getMinutes().toPaddedString(2)+':'+
this.getSeconds().toPaddedString(2)+'"';};var Try={these:function(){var returnValue;for(var i=0,length=arguments.length;i<length;i++){var lambda=arguments[i];try{returnValue=lambda();break;}catch(e){}}
return returnValue;}}
var PeriodicalExecuter=Class.create();PeriodicalExecuter.prototype={initialize:function(callback,frequency){this.callback=callback;this.frequency=frequency;this.currentlyExecuting=false;this.registerCallback();},registerCallback:function(){this.timer=setInterval(this.onTimerEvent.bind(this),this.frequency*1000);},stop:function(){if(!this.timer)return;clearInterval(this.timer);this.timer=null;},onTimerEvent:function(){if(!this.currentlyExecuting){try{this.currentlyExecuting=true;this.callback(this);}finally{this.currentlyExecuting=false;}}}}
Object.extend(String,{interpret:function(value){return value==null?'':String(value);},specialChar:{'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','\\':'\\\\'}});Object.extend(String.prototype,{gsub:function(pattern,replacement){var result='',source=this,match;replacement=arguments.callee.prepareReplacement(replacement);while(source.length>0){if(match=source.match(pattern)){result+=source.slice(0,match.index);result+=String.interpret(replacement(match));source=source.slice(match.index+match[0].length);}else{result+=source,source='';}}
return result;},sub:function(pattern,replacement,count){replacement=this.gsub.prepareReplacement(replacement);count=count===undefined?1:count;return this.gsub(pattern,function(match){if(--count<0)return match[0];return replacement(match);});},scan:function(pattern,iterator){this.gsub(pattern,iterator);return this;},truncate:function(length,truncation){length=length||30;truncation=truncation===undefined?'...':truncation;return this.length>length?this.slice(0,length-truncation.length)+truncation:this;},strip:function(){return this.replace(/^\s+/,'').replace(/\s+$/,'');},stripTags:function(){return this.replace(/<\/?[^>]+>/gi,'');},stripScripts:function(){return this.replace(new RegExp(Prototype.ScriptFragment,'img'),'');},extractScripts:function(){var matchAll=new RegExp(Prototype.ScriptFragment,'img');var matchOne=new RegExp(Prototype.ScriptFragment,'im');return(this.match(matchAll)||[]).map(function(scriptTag){return(scriptTag.match(matchOne)||['',''])[1];});},evalScripts:function(){return this.extractScripts().map(function(script){return eval(script)});},escapeHTML:function(){var self=arguments.callee;self.text.data=this;return self.div.innerHTML;},unescapeHTML:function(){var div=document.createElement('div');div.innerHTML=this.stripTags();return div.childNodes[0]?(div.childNodes.length>1?$A(div.childNodes).inject('',function(memo,node){return memo+node.nodeValue}):div.childNodes[0].nodeValue):'';},toQueryParams:function(separator){var match=this.strip().match(/([^?#]*)(#.*)?$/);if(!match)return{};return match[1].split(separator||'&').inject({},function(hash,pair){if((pair=pair.split('='))[0]){var key=decodeURIComponent(pair.shift());var value=pair.length>1?pair.join('='):pair[0];if(value!=undefined)value=decodeURIComponent(value);if(key in hash){if(hash[key].constructor!=Array)hash[key]=[hash[key]];hash[key].push(value);}
else hash[key]=value;}
return hash;});},toArray:function(){return this.split('');},succ:function(){return this.slice(0,this.length-1)+
String.fromCharCode(this.charCodeAt(this.length-1)+1);},times:function(count){var result='';for(var i=0;i<count;i++)result+=this;return result;},camelize:function(){var parts=this.split('-'),len=parts.length;if(len==1)return parts[0];var camelized=this.charAt(0)=='-'?parts[0].charAt(0).toUpperCase()+parts[0].substring(1):parts[0];for(var i=1;i<len;i++)
camelized+=parts[i].charAt(0).toUpperCase()+parts[i].substring(1);return camelized;},capitalize:function(){return this.charAt(0).toUpperCase()+this.substring(1).toLowerCase();},underscore:function(){return this.gsub(/::/,'/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase();},dasherize:function(){return this.gsub(/_/,'-');},inspect:function(useDoubleQuotes){var escapedString=this.gsub(/[\x00-\x1f\\]/,function(match){var character=String.specialChar[match[0]];return character?character:'\\u00'+match[0].charCodeAt().toPaddedString(2,16);});if(useDoubleQuotes)return'"'+escapedString.replace(/"/g,'\\"')+'"';return"'"+escapedString.replace(/'/g,'\\\'')+"'";},toJSON:function(){return this.inspect(true);},unfilterJSON:function(filter){return this.sub(filter||Prototype.JSONFilter,'#{1}');},isJSON:function(){var str=this.replace(/\\./g,'@').replace(/"[^"\\\n\r]*"/g,'');return(/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);},evalJSON:function(sanitize){var json=this.unfilterJSON();try{if(!sanitize||json.isJSON())return eval('('+json+')');}catch(e){}
throw new SyntaxError('Badly formed JSON string: '+this.inspect());},include:function(pattern){return this.indexOf(pattern)>-1;},startsWith:function(pattern){return this.indexOf(pattern)===0;},endsWith:function(pattern){var d=this.length-pattern.length;return d>=0&&this.lastIndexOf(pattern)===d;},empty:function(){return this=='';},blank:function(){return/^\s*$/.test(this);}});if(Prototype.Browser.WebKit||Prototype.Browser.IE)Object.extend(String.prototype,{escapeHTML:function(){return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');},unescapeHTML:function(){return this.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>');}});String.prototype.gsub.prepareReplacement=function(replacement){if(typeof replacement=='function')return replacement;var template=new Template(replacement);return function(match){return template.evaluate(match)};}
String.prototype.parseQuery=String.prototype.toQueryParams;Object.extend(String.prototype.escapeHTML,{div:document.createElement('div'),text:document.createTextNode('')});with(String.prototype.escapeHTML)div.appendChild(text);var Template=Class.create();Template.Pattern=/(^|.|\r|\n)(#\{(.*?)\})/;Template.prototype={initialize:function(template,pattern){this.template=template.toString();this.pattern=pattern||Template.Pattern;},evaluate:function(object){return this.template.gsub(this.pattern,function(match){var before=match[1];if(before=='\\')return match[2];return before+String.interpret(object[match[3]]);});}}
var $break={},$continue=new Error('"throw $continue" is deprecated, use "return" instead');var Enumerable={each:function(iterator){var index=0;try{this._each(function(value){iterator(value,index++);});}catch(e){if(e!=$break)throw e;}
return this;},eachSlice:function(number,iterator){var index=-number,slices=[],array=this.toArray();while((index+=number)<array.length)
slices.push(array.slice(index,index+number));return slices.map(iterator);},all:function(iterator){var result=true;this.each(function(value,index){result=result&&!!(iterator||Prototype.K)(value,index);if(!result)throw $break;});return result;},any:function(iterator){var result=false;this.each(function(value,index){if(result=!!(iterator||Prototype.K)(value,index))
throw $break;});return result;},collect:function(iterator){var results=[];this.each(function(value,index){results.push((iterator||Prototype.K)(value,index));});return results;},detect:function(iterator){var result;this.each(function(value,index){if(iterator(value,index)){result=value;throw $break;}});return result;},findAll:function(iterator){var results=[];this.each(function(value,index){if(iterator(value,index))
results.push(value);});return results;},grep:function(pattern,iterator){var results=[];this.each(function(value,index){var stringValue=value.toString();if(stringValue.match(pattern))
results.push((iterator||Prototype.K)(value,index));})
return results;},include:function(object){var found=false;this.each(function(value){if(value==object){found=true;throw $break;}});return found;},inGroupsOf:function(number,fillWith){fillWith=fillWith===undefined?null:fillWith;return this.eachSlice(number,function(slice){while(slice.length<number)slice.push(fillWith);return slice;});},inject:function(memo,iterator){this.each(function(value,index){memo=iterator(memo,value,index);});return memo;},invoke:function(method){var args=$A(arguments).slice(1);return this.map(function(value){return value[method].apply(value,args);});},max:function(iterator){var result;this.each(function(value,index){value=(iterator||Prototype.K)(value,index);if(result==undefined||value>=result)
result=value;});return result;},min:function(iterator){var result;this.each(function(value,index){value=(iterator||Prototype.K)(value,index);if(result==undefined||value<result)
result=value;});return result;},partition:function(iterator){var trues=[],falses=[];this.each(function(value,index){((iterator||Prototype.K)(value,index)?trues:falses).push(value);});return[trues,falses];},pluck:function(property){var results=[];this.each(function(value,index){results.push(value[property]);});return results;},reject:function(iterator){var results=[];this.each(function(value,index){if(!iterator(value,index))
results.push(value);});return results;},sortBy:function(iterator){return this.map(function(value,index){return{value:value,criteria:iterator(value,index)};}).sort(function(left,right){var a=left.criteria,b=right.criteria;return a<b?-1:a>b?1:0;}).pluck('value');},toArray:function(){return this.map();},zip:function(){var iterator=Prototype.K,args=$A(arguments);if(typeof args.last()=='function')
iterator=args.pop();var collections=[this].concat(args).map($A);return this.map(function(value,index){return iterator(collections.pluck(index));});},size:function(){return this.toArray().length;},inspect:function(){return'#<Enumerable:'+this.toArray().inspect()+'>';}}
Object.extend(Enumerable,{map:Enumerable.collect,find:Enumerable.detect,select:Enumerable.findAll,member:Enumerable.include,entries:Enumerable.toArray});var $A=Array.from=function(iterable){if(!iterable)return[];if(iterable.toArray){return iterable.toArray();}else{var results=[];for(var i=0,length=iterable.length;i<length;i++)
results.push(iterable[i]);return results;}}
if(Prototype.Browser.WebKit){$A=Array.from=function(iterable){if(!iterable)return[];if(!(typeof iterable=='function'&&iterable=='[object NodeList]')&&iterable.toArray){return iterable.toArray();}else{var results=[];for(var i=0,length=iterable.length;i<length;i++)
results.push(iterable[i]);return results;}}}
Object.extend(Array.prototype,Enumerable);if(!Array.prototype._reverse)
Array.prototype._reverse=Array.prototype.reverse;Object.extend(Array.prototype,{_each:function(iterator){for(var i=0,length=this.length;i<length;i++)
iterator(this[i]);},clear:function(){this.length=0;return this;},first:function(){return this[0];},last:function(){return this[this.length-1];},compact:function(){return this.select(function(value){return value!=null;});},flatten:function(){return this.inject([],function(array,value){return array.concat(value&&value.constructor==Array?value.flatten():[value]);});},without:function(){var values=$A(arguments);return this.select(function(value){return!values.include(value);});},indexOf:function(object){for(var i=0,length=this.length;i<length;i++)
if(this[i]==object)return i;return-1;},reverse:function(inline){return(inline!==false?this:this.toArray())._reverse();},reduce:function(){return this.length>1?this:this[0];},uniq:function(sorted){return this.inject([],function(array,value,index){if(0==index||(sorted?array.last()!=value:!array.include(value)))
array.push(value);return array;});},clone:function(){return[].concat(this);},size:function(){return this.length;},inspect:function(){return'['+this.map(Object.inspect).join(', ')+']';},toJSON:function(){var results=[];this.each(function(object){var value=Object.toJSON(object);if(value!==undefined)results.push(value);});return'['+results.join(', ')+']';}});Array.prototype.toArray=Array.prototype.clone;function $w(string){string=string.strip();return string?string.split(/\s+/):[];}
if(Prototype.Browser.Opera){Array.prototype.concat=function(){var array=[];for(var i=0,length=this.length;i<length;i++)array.push(this[i]);for(var i=0,length=arguments.length;i<length;i++){if(arguments[i].constructor==Array){for(var j=0,arrayLength=arguments[i].length;j<arrayLength;j++)
array.push(arguments[i][j]);}else{array.push(arguments[i]);}}
return array;}}
var Hash=function(object){if(object instanceof Hash)this.merge(object);else Object.extend(this,object||{});};Object.extend(Hash,{toQueryString:function(obj){var parts=[];parts.add=arguments.callee.addPair;this.prototype._each.call(obj,function(pair){if(!pair.key)return;var value=pair.value;if(value&&typeof value=='object'){if(value.constructor==Array)value.each(function(value){parts.add(pair.key,value);});return;}
parts.add(pair.key,value);});return parts.join('&');},toJSON:function(object){var results=[];this.prototype._each.call(object,function(pair){var value=Object.toJSON(pair.value);if(value!==undefined)results.push(pair.key.toJSON()+': '+value);});return'{'+results.join(', ')+'}';}});Hash.toQueryString.addPair=function(key,value,prefix){key=encodeURIComponent(key);if(value===undefined)this.push(key);else this.push(key+'='+(value==null?'':encodeURIComponent(value)));}
Object.extend(Hash.prototype,Enumerable);Object.extend(Hash.prototype,{_each:function(iterator){for(var key in this){var value=this[key];if(value&&value==Hash.prototype[key])continue;var pair=[key,value];pair.key=key;pair.value=value;iterator(pair);}},keys:function(){return this.pluck('key');},values:function(){return this.pluck('value');},merge:function(hash){return $H(hash).inject(this,function(mergedHash,pair){mergedHash[pair.key]=pair.value;return mergedHash;});},remove:function(){var result;for(var i=0,length=arguments.length;i<length;i++){var value=this[arguments[i]];if(value!==undefined){if(result===undefined)result=value;else{if(result.constructor!=Array)result=[result];result.push(value)}}
delete this[arguments[i]];}
return result;},toQueryString:function(){return Hash.toQueryString(this);},inspect:function(){return'#<Hash:{'+this.map(function(pair){return pair.map(Object.inspect).join(': ');}).join(', ')+'}>';},toJSON:function(){return Hash.toJSON(this);}});function $H(object){if(object instanceof Hash)return object;return new Hash(object);};if(function(){var i=0,Test=function(value){this.key=value};Test.prototype.key='foo';for(var property in new Test('bar'))i++;return i>1;}())Hash.prototype._each=function(iterator){var cache=[];for(var key in this){var value=this[key];if((value&&value==Hash.prototype[key])||cache.include(key))continue;cache.push(key);var pair=[key,value];pair.key=key;pair.value=value;iterator(pair);}};ObjectRange=Class.create();Object.extend(ObjectRange.prototype,Enumerable);Object.extend(ObjectRange.prototype,{initialize:function(start,end,exclusive){this.start=start;this.end=end;this.exclusive=exclusive;},_each:function(iterator){var value=this.start;while(this.include(value)){iterator(value);value=value.succ();}},include:function(value){if(value<this.start)
return false;if(this.exclusive)
return value<this.end;return value<=this.end;}});var $R=function(start,end,exclusive){return new ObjectRange(start,end,exclusive);}
var Ajax={getTransport:function(){return Try.these(function(){return new XMLHttpRequest()},function(){return new ActiveXObject('Msxml2.XMLHTTP')},function(){return new ActiveXObject('Microsoft.XMLHTTP')})||false;},activeRequestCount:0}
Ajax.Responders={responders:[],_each:function(iterator){this.responders._each(iterator);},register:function(responder){if(!this.include(responder))
this.responders.push(responder);},unregister:function(responder){this.responders=this.responders.without(responder);},dispatch:function(callback,request,transport,json){this.each(function(responder){if(typeof responder[callback]=='function'){try{responder[callback].apply(responder,[request,transport,json]);}catch(e){}}});}};Object.extend(Ajax.Responders,Enumerable);Ajax.Responders.register({onCreate:function(){Ajax.activeRequestCount++;},onComplete:function(){Ajax.activeRequestCount--;}});Ajax.Base=function(){};Ajax.Base.prototype={setOptions:function(options){this.options={method:'post',asynchronous:true,contentType:'application/x-www-form-urlencoded',encoding:'UTF-8',parameters:''}
Object.extend(this.options,options||{});this.options.method=this.options.method.toLowerCase();if(typeof this.options.parameters=='string')
this.options.parameters=this.options.parameters.toQueryParams();}}
Ajax.Request=Class.create();Ajax.Request.Events=['Uninitialized','Loading','Loaded','Interactive','Complete'];Ajax.Request.prototype=Object.extend(new Ajax.Base(),{_complete:false,initialize:function(url,options){this.transport=Ajax.getTransport();this.setOptions(options);this.request(url);},request:function(url){this.url=url;this.method=this.options.method;var params=Object.clone(this.options.parameters);if(!['get','post'].include(this.method)){params['_method']=this.method;this.method='post';}
this.parameters=params;if(params=Hash.toQueryString(params)){if(this.method=='get')
this.url+=(this.url.include('?')?'&':'?')+params;else if(/Konqueror|Safari|KHTML/.test(navigator.userAgent))
params+='&_=';}
try{if(this.options.onCreate)this.options.onCreate(this.transport);Ajax.Responders.dispatch('onCreate',this,this.transport);this.transport.open(this.method.toUpperCase(),this.url,this.options.asynchronous);if(this.options.asynchronous)
setTimeout(function(){this.respondToReadyState(1)}.bind(this),10);this.transport.onreadystatechange=this.onStateChange.bind(this);this.setRequestHeaders();this.body=this.method=='post'?(this.options.postBody||params):null;this.transport.send(this.body);if(!this.options.asynchronous&&this.transport.overrideMimeType)
this.onStateChange();}
catch(e){this.dispatchException(e);}},onStateChange:function(){var readyState=this.transport.readyState;if(readyState>1&&!((readyState==4)&&this._complete))
this.respondToReadyState(this.transport.readyState);},setRequestHeaders:function(){var headers={'X-Requested-With':'XMLHttpRequest','X-Prototype-Version':Prototype.Version,'Accept':'text/javascript, text/html, application/xml, text/xml, */*'};if(this.method=='post'){headers['Content-type']=this.options.contentType+
(this.options.encoding?'; charset='+this.options.encoding:'');if(this.transport.overrideMimeType&&(navigator.userAgent.match(/Gecko\/(\d{4})/)||[0,2005])[1]<2005)
headers['Connection']='close';}
if(typeof this.options.requestHeaders=='object'){var extras=this.options.requestHeaders;if(typeof extras.push=='function')
for(var i=0,length=extras.length;i<length;i+=2)
headers[extras[i]]=extras[i+1];else
$H(extras).each(function(pair){headers[pair.key]=pair.value});}
for(var name in headers)if (typeof headers[name] != 'function')
this.transport.setRequestHeader(name,headers[name]);},success:function(){return!this.transport.status||(this.transport.status>=200&&this.transport.status<300);},respondToReadyState:function(readyState){var state=Ajax.Request.Events[readyState];var transport=this.transport,json=this.evalJSON();if(state=='Complete'){try{this._complete=true;(this.options['on'+this.transport.status]||this.options['on'+(this.success()?'Success':'Failure')]||Prototype.emptyFunction)(transport,json);}catch(e){this.dispatchException(e);}
var contentType=this.getHeader('Content-type');if(contentType&&contentType.strip().match(/^(text|application)\/(x-)?(java|ecma)script(;.*)?$/i))
this.evalResponse();}
try{(this.options['on'+state]||Prototype.emptyFunction)(transport,json);Ajax.Responders.dispatch('on'+state,this,transport,json);}catch(e){this.dispatchException(e);}
if(state=='Complete'){this.transport.onreadystatechange=Prototype.emptyFunction;}},getHeader:function(name){try{return this.transport.getResponseHeader(name);}catch(e){return null}},evalJSON:function(){try{var json=this.getHeader('X-JSON');return json?json.evalJSON():null;}catch(e){return null}},evalResponse:function(){try{return eval((this.transport.responseText||'').unfilterJSON());}catch(e){this.dispatchException(e);}},dispatchException:function(exception){(this.options.onException||Prototype.emptyFunction)(this,exception);Ajax.Responders.dispatch('onException',this,exception);}});Ajax.Updater=Class.create();Object.extend(Object.extend(Ajax.Updater.prototype,Ajax.Request.prototype),{initialize:function(container,url,options){this.container={success:(container.success||container),failure:(container.failure||(container.success?null:container))}
this.transport=Ajax.getTransport();this.setOptions(options);var onComplete=this.options.onComplete||Prototype.emptyFunction;this.options.onComplete=(function(transport,param){this.updateContent();onComplete(transport,param);}).bind(this);this.request(url);},updateContent:function(){var receiver=this.container[this.success()?'success':'failure'];var response=this.transport.responseText;if(!this.options.evalScripts)response=response.stripScripts();if(receiver=$(receiver)){if(this.options.insertion)
new this.options.insertion(receiver,response);else
receiver.update(response);}
if(this.success()){if(this.onComplete)
setTimeout(this.onComplete.bind(this),10);}}});Ajax.PeriodicalUpdater=Class.create();Ajax.PeriodicalUpdater.prototype=Object.extend(new Ajax.Base(),{initialize:function(container,url,options){this.setOptions(options);this.onComplete=this.options.onComplete;this.frequency=(this.options.frequency||2);this.decay=(this.options.decay||1);this.updater={};this.container=container;this.url=url;this.start();},start:function(){this.options.onComplete=this.updateComplete.bind(this);this.onTimerEvent();},stop:function(){this.updater.options.onComplete=undefined;clearTimeout(this.timer);(this.onComplete||Prototype.emptyFunction).apply(this,arguments);},updateComplete:function(request){if(this.options.decay){this.decay=(request.responseText==this.lastText?this.decay*this.options.decay:1);this.lastText=request.responseText;}
this.timer=setTimeout(this.onTimerEvent.bind(this),this.decay*this.frequency*1000);},onTimerEvent:function(){this.updater=new Ajax.Updater(this.container,this.url,this.options);}});function $(element){if(arguments.length>1){for(var i=0,elements=[],length=arguments.length;i<length;i++)
elements.push($(arguments[i]));return elements;}
if(typeof element=='string')
element=document.getElementById(element);return Element.extend(element);}
if(Prototype.BrowserFeatures.XPath){document._getElementsByXPath=function(expression,parentElement){var results=[];var query=document.evaluate(expression,$(parentElement)||document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null);for(var i=0,length=query.snapshotLength;i<length;i++)
results.push(query.snapshotItem(i));return results;};document.getElementsByClassName=function(className,parentElement){var q=".//*[contains(concat(' ', @class, ' '), ' "+className+" ')]";return document._getElementsByXPath(q,parentElement);}}else document.getElementsByClassName=function(className,parentElement){var children=($(parentElement)||document.body).getElementsByTagName('*');var elements=[],child,pattern=new RegExp("(^|\\s)"+className+"(\\s|$)");for(var i=0,length=children.length;i<length;i++){child=children[i];var elementClassName=child.className;if(elementClassName.length==0)continue;if(elementClassName==className||elementClassName.match(pattern))
elements.push(Element.extend(child));}
return elements;};if(!window.Element)var Element={};Element.extend=function(element){var F=Prototype.BrowserFeatures;if(!element||!element.tagName||element.nodeType==3||element._extended||F.SpecificElementExtensions||element==window)
return element;var methods={},tagName=element.tagName,cache=Element.extend.cache,T=Element.Methods.ByTag;if(!F.ElementExtensions){Object.extend(methods,Element.Methods),Object.extend(methods,Element.Methods.Simulated);}
if(T[tagName])Object.extend(methods,T[tagName]);for(var property in methods){var value=methods[property];if(typeof value=='function'&&!(property in element))
element[property]=cache.findOrStore(value);}
element._extended=Prototype.emptyFunction;return element;};Element.extend.cache={findOrStore:function(value){return this[value]=this[value]||function(){return value.apply(null,[this].concat($A(arguments)));}}};Element.Methods={visible:function(element){return $(element).style.display!='none';},toggle:function(element){element=$(element);Element[Element.visible(element)?'hide':'show'](element);return element;},hide:function(element){$(element).style.display='none';return element;},show:function(element){$(element).style.display='';return element;},remove:function(element){element=$(element);element.parentNode.removeChild(element);return element;},update:function(element,html){html=typeof html=='undefined'?'':html.toString();$(element).innerHTML=html.stripScripts();setTimeout(function(){html.evalScripts()},10);return element;},replace:function(element,html){element=$(element);html=typeof html=='undefined'?'':html.toString();if(element.outerHTML){element.outerHTML=html.stripScripts();}else{var range=element.ownerDocument.createRange();range.selectNodeContents(element);element.parentNode.replaceChild(range.createContextualFragment(html.stripScripts()),element);}
setTimeout(function(){html.evalScripts()},10);return element;},inspect:function(element){element=$(element);var result='<'+element.tagName.toLowerCase();$H({'id':'id','className':'class'}).each(function(pair){var property=pair.first(),attribute=pair.last();var value=(element[property]||'').toString();if(value)result+=' '+attribute+'='+value.inspect(true);});return result+'>';},recursivelyCollect:function(element,property){element=$(element);var elements=[];while(element=element[property])
if(element.nodeType==1)
elements.push(Element.extend(element));return elements;},ancestors:function(element){return $(element).recursivelyCollect('parentNode');},descendants:function(element){return $A($(element).getElementsByTagName('*')).each(Element.extend);},firstDescendant:function(element){element=$(element).firstChild;while(element&&element.nodeType!=1)element=element.nextSibling;return $(element);},immediateDescendants:function(element){if(!(element=$(element).firstChild))return[];while(element&&element.nodeType!=1)element=element.nextSibling;if(element)return[element].concat($(element).nextSiblings());return[];},previousSiblings:function(element){return $(element).recursivelyCollect('previousSibling');},nextSiblings:function(element){return $(element).recursivelyCollect('nextSibling');},siblings:function(element){element=$(element);return element.previousSiblings().reverse().concat(element.nextSiblings());},match:function(element,selector){if(typeof selector=='string')
selector=new Selector(selector);return selector.match($(element));},up:function(element,expression,index){element=$(element);if(arguments.length==1)return $(element.parentNode);var ancestors=element.ancestors();return expression?Selector.findElement(ancestors,expression,index):ancestors[index||0];},down:function(element,expression,index){element=$(element);if(arguments.length==1)return element.firstDescendant();var descendants=element.descendants();return expression?Selector.findElement(descendants,expression,index):descendants[index||0];},previous:function(element,expression,index){element=$(element);if(arguments.length==1)return $(Selector.handlers.previousElementSibling(element));var previousSiblings=element.previousSiblings();return expression?Selector.findElement(previousSiblings,expression,index):previousSiblings[index||0];},next:function(element,expression,index){element=$(element);if(arguments.length==1)return $(Selector.handlers.nextElementSibling(element));var nextSiblings=element.nextSiblings();return expression?Selector.findElement(nextSiblings,expression,index):nextSiblings[index||0];},getElementsBySelector:function(){var args=$A(arguments),element=$(args.shift());return Selector.findChildElements(element,args);},getElementsByClassName:function(element,className){return document.getElementsByClassName(className,element);},readAttribute:function(element,name){element=$(element);if(Prototype.Browser.IE){if(!element.attributes)return null;var t=Element._attributeTranslations;if(t.values[name])return t.values[name](element,name);if(t.names[name])name=t.names[name];var attribute=element.attributes[name];return attribute?attribute.nodeValue:null;}
return element.getAttribute(name);},getHeight:function(element){return $(element).getDimensions().height;},getWidth:function(element){return $(element).getDimensions().width;},classNames:function(element){return new Element.ClassNames(element);},hasClassName:function(element,className){if(!(element=$(element)))return;var elementClassName=element.className;if(elementClassName.length==0)return false;if(elementClassName==className||elementClassName.match(new RegExp("(^|\\s)"+className+"(\\s|$)")))
return true;return false;},addClassName:function(element,className){if(!(element=$(element)))return;Element.classNames(element).add(className);return element;},removeClassName:function(element,className){if(!(element=$(element)))return;Element.classNames(element).remove(className);return element;},toggleClassName:function(element,className){if(!(element=$(element)))return;Element.classNames(element)[element.hasClassName(className)?'remove':'add'](className);return element;},observe:function(){Event.observe.apply(Event,arguments);return $A(arguments).first();},stopObserving:function(){Event.stopObserving.apply(Event,arguments);return $A(arguments).first();},cleanWhitespace:function(element){element=$(element);var node=element.firstChild;while(node){var nextNode=node.nextSibling;if(node.nodeType==3&&!/\S/.test(node.nodeValue))
element.removeChild(node);node=nextNode;}
return element;},empty:function(element){return $(element).innerHTML.blank();},descendantOf:function(element,ancestor){element=$(element),ancestor=$(ancestor);while(element=element.parentNode)
if(element==ancestor)return true;return false;},scrollTo:function(element){element=$(element);var pos=Position.cumulativeOffset(element);window.scrollTo(pos[0],pos[1]);return element;},getStyle:function(element,style){element=$(element);style=style=='float'?'cssFloat':style.camelize();var value=element.style[style];if(!value){var css=document.defaultView.getComputedStyle(element,null);value=css?css[style]:null;}
if(style=='opacity')return value?parseFloat(value):1.0;return value=='auto'?null:value;},getOpacity:function(element){return $(element).getStyle('opacity');},setStyle:function(element,styles,camelized){element=$(element);var elementStyle=element.style;for(var property in styles)
if(property=='opacity')element.setOpacity(styles[property])
else
elementStyle[(property=='float'||property=='cssFloat')?(elementStyle.styleFloat===undefined?'cssFloat':'styleFloat'):(camelized?property:property.camelize())]=styles[property];return element;},setOpacity:function(element,value){element=$(element);element.style.opacity=(value==1||value==='')?'':(value<0.00001)?0:value;return element;},getDimensions:function(element){element=$(element);var display=$(element).getStyle('display');if(display!='none'&&display!=null)
return{width:element.offsetWidth,height:element.offsetHeight};var els=element.style;var originalVisibility=els.visibility;var originalPosition=els.position;var originalDisplay=els.display;els.visibility='hidden';els.position='absolute';els.display='block';var originalWidth=element.clientWidth;var originalHeight=element.clientHeight;els.display=originalDisplay;els.position=originalPosition;els.visibility=originalVisibility;return{width:originalWidth,height:originalHeight};},makePositioned:function(element){element=$(element);var pos=Element.getStyle(element,'position');if(pos=='static'||!pos){element._madePositioned=true;element.style.position='relative';if(window.opera){element.style.top=0;element.style.left=0;}}
return element;},undoPositioned:function(element){element=$(element);if(element._madePositioned){element._madePositioned=undefined;element.style.position=element.style.top=element.style.left=element.style.bottom=element.style.right='';}
return element;},makeClipping:function(element){element=$(element);if(element._overflow)return element;element._overflow=element.style.overflow||'auto';if((Element.getStyle(element,'overflow')||'visible')!='hidden')
element.style.overflow='hidden';return element;},undoClipping:function(element){element=$(element);if(!element._overflow)return element;element.style.overflow=element._overflow=='auto'?'':element._overflow;element._overflow=null;return element;}};Object.extend(Element.Methods,{childOf:Element.Methods.descendantOf,childElements:Element.Methods.immediateDescendants});if(Prototype.Browser.Opera){Element.Methods._getStyle=Element.Methods.getStyle;Element.Methods.getStyle=function(element,style){switch(style){case'left':case'top':case'right':case'bottom':if(Element._getStyle(element,'position')=='static')return null;default:return Element._getStyle(element,style);}};}
else if(Prototype.Browser.IE){Element.Methods.getStyle=function(element,style){element=$(element);style=(style=='float'||style=='cssFloat')?'styleFloat':style.camelize();var value=element.style[style];if(!value&&element.currentStyle)value=element.currentStyle[style];if(style=='opacity'){if(value=(element.getStyle('filter')||'').match(/alpha\(opacity=(.*)\)/))
if(value[1])return parseFloat(value[1])/100;return 1.0;}
if(value=='auto'){if((style=='width'||style=='height')&&(element.getStyle('display')!='none'))
return element['offset'+style.capitalize()]+'px';return null;}
return value;};Element.Methods.setOpacity=function(element,value){element=$(element);var filter=element.getStyle('filter'),style=element.style;if(value==1||value===''){style.filter=filter.replace(/alpha\([^\)]*\)/gi,'');return element;}else if(value<0.00001)value=0;style.filter=filter.replace(/alpha\([^\)]*\)/gi,'')+'alpha(opacity='+(value*100)+')';return element;};Element.Methods.update=function(element,html){element=$(element);html=typeof html=='undefined'?'':html.toString();var tagName=element.tagName.toUpperCase();if(['THEAD','TBODY','TR','TD'].include(tagName)){var div=document.createElement('div');switch(tagName){case'THEAD':case'TBODY':div.innerHTML='<table><tbody>'+html.stripScripts()+'</tbody></table>';depth=2;break;case'TR':div.innerHTML='<table><tbody><tr>'+html.stripScripts()+'</tr></tbody></table>';depth=3;break;case'TD':div.innerHTML='<table><tbody><tr><td>'+html.stripScripts()+'</td></tr></tbody></table>';depth=4;}
$A(element.childNodes).each(function(node){element.removeChild(node)});depth.times(function(){div=div.firstChild});$A(div.childNodes).each(function(node){element.appendChild(node)});}else{element.innerHTML=html.stripScripts();}
setTimeout(function(){html.evalScripts()},10);return element;}}
else if(Prototype.Browser.Gecko){Element.Methods.setOpacity=function(element,value){element=$(element);element.style.opacity=(value==1)?0.999999:(value==='')?'':(value<0.00001)?0:value;return element;};}
Element._attributeTranslations={names:{colspan:"colSpan",rowspan:"rowSpan",valign:"vAlign",datetime:"dateTime",accesskey:"accessKey",tabindex:"tabIndex",enctype:"encType",maxlength:"maxLength",readonly:"readOnly",longdesc:"longDesc"},values:{_getAttr:function(element,attribute){return element.getAttribute(attribute,2);},_flag:function(element,attribute){return $(element).hasAttribute(attribute)?attribute:null;},style:function(element){return element.style.cssText.toLowerCase();},title:function(element){var node=element.getAttributeNode('title');return node.specified?node.nodeValue:null;}}};(function(){Object.extend(this,{href:this._getAttr,src:this._getAttr,type:this._getAttr,disabled:this._flag,checked:this._flag,readonly:this._flag,multiple:this._flag});}).call(Element._attributeTranslations.values);Element.Methods.Simulated={hasAttribute:function(element,attribute){var t=Element._attributeTranslations,node;attribute=t.names[attribute]||attribute;node=$(element).getAttributeNode(attribute);return node&&node.specified;}};Element.Methods.ByTag={};Object.extend(Element,Element.Methods);if(!Prototype.BrowserFeatures.ElementExtensions&&document.createElement('div').__proto__){window.HTMLElement={};window.HTMLElement.prototype=document.createElement('div').__proto__;Prototype.BrowserFeatures.ElementExtensions=true;}
Element.hasAttribute=function(element,attribute){if(element.hasAttribute)return element.hasAttribute(attribute);return Element.Methods.Simulated.hasAttribute(element,attribute);};Element.addMethods=function(methods){var F=Prototype.BrowserFeatures,T=Element.Methods.ByTag;if(!methods){Object.extend(Form,Form.Methods);Object.extend(Form.Element,Form.Element.Methods);Object.extend(Element.Methods.ByTag,{"FORM":Object.clone(Form.Methods),"INPUT":Object.clone(Form.Element.Methods),"SELECT":Object.clone(Form.Element.Methods),"TEXTAREA":Object.clone(Form.Element.Methods)});}
if(arguments.length==2){var tagName=methods;methods=arguments[1];}
if(!tagName)Object.extend(Element.Methods,methods||{});else{if(tagName.constructor==Array)tagName.each(extend);else extend(tagName);}
function extend(tagName){tagName=tagName.toUpperCase();if(!Element.Methods.ByTag[tagName])
Element.Methods.ByTag[tagName]={};Object.extend(Element.Methods.ByTag[tagName],methods);}
function copy(methods,destination,onlyIfAbsent){onlyIfAbsent=onlyIfAbsent||false;var cache=Element.extend.cache;for(var property in methods){var value=methods[property];if(!onlyIfAbsent||!(property in destination))
destination[property]=cache.findOrStore(value);}}
function findDOMClass(tagName){var klass;var trans={"OPTGROUP":"OptGroup","TEXTAREA":"TextArea","P":"Paragraph","FIELDSET":"FieldSet","UL":"UList","OL":"OList","DL":"DList","DIR":"Directory","H1":"Heading","H2":"Heading","H3":"Heading","H4":"Heading","H5":"Heading","H6":"Heading","Q":"Quote","INS":"Mod","DEL":"Mod","A":"Anchor","IMG":"Image","CAPTION":"TableCaption","COL":"TableCol","COLGROUP":"TableCol","THEAD":"TableSection","TFOOT":"TableSection","TBODY":"TableSection","TR":"TableRow","TH":"TableCell","TD":"TableCell","FRAMESET":"FrameSet","IFRAME":"IFrame"};if(trans[tagName])klass='HTML'+trans[tagName]+'Element';if(window[klass])return window[klass];klass='HTML'+tagName+'Element';if(window[klass])return window[klass];klass='HTML'+tagName.capitalize()+'Element';if(window[klass])return window[klass];window[klass]={};window[klass].prototype=document.createElement(tagName).__proto__;return window[klass];}
if(F.ElementExtensions){copy(Element.Methods,HTMLElement.prototype);copy(Element.Methods.Simulated,HTMLElement.prototype,true);}
if(F.SpecificElementExtensions){for(var tag in Element.Methods.ByTag){var klass=findDOMClass(tag);if(typeof klass=="undefined")continue;copy(T[tag],klass.prototype);}}
Object.extend(Element,Element.Methods);delete Element.ByTag;};var Toggle={display:Element.toggle};Abstract.Insertion=function(adjacency){this.adjacency=adjacency;}
Abstract.Insertion.prototype={initialize:function(element,content){this.element=$(element);this.content=content.stripScripts();if(this.adjacency&&this.element.insertAdjacentHTML){try{this.element.insertAdjacentHTML(this.adjacency,this.content);}catch(e){var tagName=this.element.tagName.toUpperCase();if(['TBODY','TR'].include(tagName)){this.insertContent(this.contentFromAnonymousTable());}else{throw e;}}}else{this.range=this.element.ownerDocument.createRange();if(this.initializeRange)this.initializeRange();this.insertContent([this.range.createContextualFragment(this.content)]);}
setTimeout(function(){content.evalScripts()},10);},contentFromAnonymousTable:function(){var div=document.createElement('div');div.innerHTML='<table><tbody>'+this.content+'</tbody></table>';return $A(div.childNodes[0].childNodes[0].childNodes);}}
var Insertion=new Object();Insertion.Before=Class.create();Insertion.Before.prototype=Object.extend(new Abstract.Insertion('beforeBegin'),{initializeRange:function(){this.range.setStartBefore(this.element);},insertContent:function(fragments){fragments.each((function(fragment){this.element.parentNode.insertBefore(fragment,this.element);}).bind(this));}});Insertion.Top=Class.create();Insertion.Top.prototype=Object.extend(new Abstract.Insertion('afterBegin'),{initializeRange:function(){this.range.selectNodeContents(this.element);this.range.collapse(true);},insertContent:function(fragments){fragments.reverse(false).each((function(fragment){this.element.insertBefore(fragment,this.element.firstChild);}).bind(this));}});Insertion.Bottom=Class.create();Insertion.Bottom.prototype=Object.extend(new Abstract.Insertion('beforeEnd'),{initializeRange:function(){this.range.selectNodeContents(this.element);this.range.collapse(this.element);},insertContent:function(fragments){fragments.each((function(fragment){this.element.appendChild(fragment);}).bind(this));}});Insertion.After=Class.create();Insertion.After.prototype=Object.extend(new Abstract.Insertion('afterEnd'),{initializeRange:function(){this.range.setStartAfter(this.element);},insertContent:function(fragments){fragments.each((function(fragment){this.element.parentNode.insertBefore(fragment,this.element.nextSibling);}).bind(this));}});Element.ClassNames=Class.create();Element.ClassNames.prototype={initialize:function(element){this.element=$(element);},_each:function(iterator){this.element.className.split(/\s+/).select(function(name){return name.length>0;})._each(iterator);},set:function(className){this.element.className=className;},add:function(classNameToAdd){if(this.include(classNameToAdd))return;this.set($A(this).concat(classNameToAdd).join(' '));},remove:function(classNameToRemove){if(!this.include(classNameToRemove))return;this.set($A(this).without(classNameToRemove).join(' '));},toString:function(){return $A(this).join(' ');}};Object.extend(Element.ClassNames.prototype,Enumerable);var Selector=Class.create();Selector.prototype={initialize:function(expression){this.expression=expression.strip();this.compileMatcher();},compileMatcher:function(){if(Prototype.BrowserFeatures.XPath&&!(/\[[\w-]*?:/).test(this.expression))
return this.compileXPathMatcher();var e=this.expression,ps=Selector.patterns,h=Selector.handlers,c=Selector.criteria,le,p,m;if(Selector._cache[e]){this.matcher=Selector._cache[e];return;}
this.matcher=["this.matcher = function(root) {","var r = root, h = Selector.handlers, c = false, n;"];while(e&&le!=e&&(/\S/).test(e)){le=e;for(var i in ps){p=ps[i];if(m=e.match(p)){this.matcher.push(typeof c[i]=='function'?c[i](m):new Template(c[i]).evaluate(m));e=e.replace(m[0],'');break;}}}
this.matcher.push("return h.unique(n);\n}");eval(this.matcher.join('\n'));Selector._cache[this.expression]=this.matcher;},compileXPathMatcher:function(){var e=this.expression,ps=Selector.patterns,x=Selector.xpath,le,m;if(Selector._cache[e]){this.xpath=Selector._cache[e];return;}
this.matcher=['.//*'];while(e&&le!=e&&(/\S/).test(e)){le=e;for(var i in ps){if(m=e.match(ps[i])){this.matcher.push(typeof x[i]=='function'?x[i](m):new Template(x[i]).evaluate(m));e=e.replace(m[0],'');break;}}}
this.xpath=this.matcher.join('');Selector._cache[this.expression]=this.xpath;},findElements:function(root){root=root||document;if(this.xpath)return document._getElementsByXPath(this.xpath,root);return this.matcher(root);},match:function(element){return this.findElements(document).include(element);},toString:function(){return this.expression;},inspect:function(){return"#<Selector:"+this.expression.inspect()+">";}};Object.extend(Selector,{_cache:{},xpath:{descendant:"//*",child:"/*",adjacent:"/following-sibling::*[1]",laterSibling:'/following-sibling::*',tagName:function(m){if(m[1]=='*')return'';return"[local-name()='"+m[1].toLowerCase()+"' or local-name()='"+m[1].toUpperCase()+"']";},className:"[contains(concat(' ', @class, ' '), ' #{1} ')]",id:"[@id='#{1}']",attrPresence:"[@#{1}]",attr:function(m){m[3]=m[5]||m[6];return new Template(Selector.xpath.operators[m[2]]).evaluate(m);},pseudo:function(m){var h=Selector.xpath.pseudos[m[1]];if(!h)return'';if(typeof h==='function')return h(m);return new Template(Selector.xpath.pseudos[m[1]]).evaluate(m);},operators:{'=':"[@#{1}='#{3}']",'!=':"[@#{1}!='#{3}']",'^=':"[starts-with(@#{1}, '#{3}')]",'$=':"[substring(@#{1}, (string-length(@#{1}) - string-length('#{3}') + 1))='#{3}']",'*=':"[contains(@#{1}, '#{3}')]",'~=':"[contains(concat(' ', @#{1}, ' '), ' #{3} ')]",'|=':"[contains(concat('-', @#{1}, '-'), '-#{3}-')]"},pseudos:{'first-child':'[not(preceding-sibling::*)]','last-child':'[not(following-sibling::*)]','only-child':'[not(preceding-sibling::* or following-sibling::*)]','empty':"[count(*) = 0 and (count(text()) = 0 or translate(text(), ' \t\r\n', '') = '')]",'checked':"[@checked]",'disabled':"[@disabled]",'enabled':"[not(@disabled)]",'not':function(m){var e=m[6],p=Selector.patterns,x=Selector.xpath,le,m,v;var exclusion=[];while(e&&le!=e&&(/\S/).test(e)){le=e;for(var i in p){if(m=e.match(p[i])){v=typeof x[i]=='function'?x[i](m):new Template(x[i]).evaluate(m);exclusion.push("("+v.substring(1,v.length-1)+")");e=e.replace(m[0],'');break;}}}
return"[not("+exclusion.join(" and ")+")]";},'nth-child':function(m){return Selector.xpath.pseudos.nth("(count(./preceding-sibling::*) + 1) ",m);},'nth-last-child':function(m){return Selector.xpath.pseudos.nth("(count(./following-sibling::*) + 1) ",m);},'nth-of-type':function(m){return Selector.xpath.pseudos.nth("position() ",m);},'nth-last-of-type':function(m){return Selector.xpath.pseudos.nth("(last() + 1 - position()) ",m);},'first-of-type':function(m){m[6]="1";return Selector.xpath.pseudos['nth-of-type'](m);},'last-of-type':function(m){m[6]="1";return Selector.xpath.pseudos['nth-last-of-type'](m);},'only-of-type':function(m){var p=Selector.xpath.pseudos;return p['first-of-type'](m)+p['last-of-type'](m);},nth:function(fragment,m){var mm,formula=m[6],predicate;if(formula=='even')formula='2n+0';if(formula=='odd')formula='2n+1';if(mm=formula.match(/^(\d+)$/))
return'['+fragment+"= "+mm[1]+']';if(mm=formula.match(/^(-?\d*)?n(([+-])(\d+))?/)){if(mm[1]=="-")mm[1]=-1;var a=mm[1]?Number(mm[1]):1;var b=mm[2]?Number(mm[2]):0;predicate="[((#{fragment} - #{b}) mod #{a} = 0) and "+"((#{fragment} - #{b}) div #{a} >= 0)]";return new Template(predicate).evaluate({fragment:fragment,a:a,b:b});}}}},criteria:{tagName:'n = h.tagName(n, r, "#{1}", c);   c = false;',className:'n = h.className(n, r, "#{1}", c); c = false;',id:'n = h.id(n, r, "#{1}", c);        c = false;',attrPresence:'n = h.attrPresence(n, r, "#{1}"); c = false;',attr:function(m){m[3]=(m[5]||m[6]);return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}"); c = false;').evaluate(m);},pseudo:function(m){if(m[6])m[6]=m[6].replace(/"/g,'\\"');return new Template('n = h.pseudo(n, "#{1}", "#{6}", r, c); c = false;').evaluate(m);},descendant:'c = "descendant";',child:'c = "child";',adjacent:'c = "adjacent";',laterSibling:'c = "laterSibling";'},patterns:{laterSibling:/^\s*~\s*/,child:/^\s*>\s*/,adjacent:/^\s*\+\s*/,descendant:/^\s/,tagName:/^\s*(\*|[\w\-]+)(\b|$)?/,id:/^#([\w\-\*]+)(\b|$)/,className:/^\.([\w\-\*]+)(\b|$)/,pseudo:/^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|\s|(?=:))/,attrPresence:/^\[([\w]+)\]/,attr:/\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\]]*?)\4|([^'"][^\]]*?)))?\]/},handlers:{concat:function(a,b){for(var i=0,node;node=b[i];i++)
a.push(node);return a;},mark:function(nodes){for(var i=0,node;node=nodes[i];i++)
node._counted=true;return nodes;},unmark:function(nodes){for(var i=0,node;node=nodes[i];i++)
node._counted=undefined;return nodes;},index:function(parentNode,reverse,ofType){parentNode._counted=true;if(reverse){for(var nodes=parentNode.childNodes,i=nodes.length-1,j=1;i>=0;i--){node=nodes[i];if(node.nodeType==1&&(!ofType||node._counted))node.nodeIndex=j++;}}else{for(var i=0,j=1,nodes=parentNode.childNodes;node=nodes[i];i++)
if(node.nodeType==1&&(!ofType||node._counted))node.nodeIndex=j++;}},unique:function(nodes){if(nodes.length==0)return nodes;var results=[],n;for(var i=0,l=nodes.length;i<l;i++)
if(!(n=nodes[i])._counted){n._counted=true;results.push(Element.extend(n));}
return Selector.handlers.unmark(results);},descendant:function(nodes){var h=Selector.handlers;for(var i=0,results=[],node;node=nodes[i];i++)
h.concat(results,node.getElementsByTagName('*'));return results;},child:function(nodes){var h=Selector.handlers;for(var i=0,results=[],node;node=nodes[i];i++){for(var j=0,children=[],child;child=node.childNodes[j];j++)
if(child.nodeType==1&&child.tagName!='!')results.push(child);}
return results;},adjacent:function(nodes){for(var i=0,results=[],node;node=nodes[i];i++){var next=this.nextElementSibling(node);if(next)results.push(next);}
return results;},laterSibling:function(nodes){var h=Selector.handlers;for(var i=0,results=[],node;node=nodes[i];i++)
h.concat(results,Element.nextSiblings(node));return results;},nextElementSibling:function(node){while(node=node.nextSibling)
if(node.nodeType==1)return node;return null;},previousElementSibling:function(node){while(node=node.previousSibling)
if(node.nodeType==1)return node;return null;},tagName:function(nodes,root,tagName,combinator){tagName=tagName.toUpperCase();var results=[],h=Selector.handlers;if(nodes){if(combinator){if(combinator=="descendant"){for(var i=0,node;node=nodes[i];i++)
h.concat(results,node.getElementsByTagName(tagName));return results;}else nodes=this[combinator](nodes);if(tagName=="*")return nodes;}
for(var i=0,node;node=nodes[i];i++)
if(node.tagName.toUpperCase()==tagName)results.push(node);return results;}else return root.getElementsByTagName(tagName);},id:function(nodes,root,id,combinator){var targetNode=$(id),h=Selector.handlers;if(!nodes&&root==document)return targetNode?[targetNode]:[];if(nodes){if(combinator){if(combinator=='child'){for(var i=0,node;node=nodes[i];i++)
if(targetNode.parentNode==node)return[targetNode];}else if(combinator=='descendant'){for(var i=0,node;node=nodes[i];i++)
if(Element.descendantOf(targetNode,node))return[targetNode];}else if(combinator=='adjacent'){for(var i=0,node;node=nodes[i];i++)
if(Selector.handlers.previousElementSibling(targetNode)==node)
return[targetNode];}else nodes=h[combinator](nodes);}
for(var i=0,node;node=nodes[i];i++)
if(node==targetNode)return[targetNode];return[];}
return(targetNode&&Element.descendantOf(targetNode,root))?[targetNode]:[];},className:function(nodes,root,className,combinator){if(nodes&&combinator)nodes=this[combinator](nodes);return Selector.handlers.byClassName(nodes,root,className);},byClassName:function(nodes,root,className){if(!nodes)nodes=Selector.handlers.descendant([root]);var needle=' '+className+' ';for(var i=0,results=[],node,nodeClassName;node=nodes[i];i++){nodeClassName=node.className;if(nodeClassName.length==0)continue;if(nodeClassName==className||(' '+nodeClassName+' ').include(needle))
results.push(node);}
return results;},attrPresence:function(nodes,root,attr){var results=[];for(var i=0,node;node=nodes[i];i++)
if(Element.hasAttribute(node,attr))results.push(node);return results;},attr:function(nodes,root,attr,value,operator){if(!nodes)nodes=root.getElementsByTagName("*");var handler=Selector.operators[operator],results=[];for(var i=0,node;node=nodes[i];i++){var nodeValue=Element.readAttribute(node,attr);if(nodeValue===null)continue;if(handler(nodeValue,value))results.push(node);}
return results;},pseudo:function(nodes,name,value,root,combinator){if(nodes&&combinator)nodes=this[combinator](nodes);if(!nodes)nodes=root.getElementsByTagName("*");return Selector.pseudos[name](nodes,value,root);}},pseudos:{'first-child':function(nodes,value,root){for(var i=0,results=[],node;node=nodes[i];i++){if(Selector.handlers.previousElementSibling(node))continue;results.push(node);}
return results;},'last-child':function(nodes,value,root){for(var i=0,results=[],node;node=nodes[i];i++){if(Selector.handlers.nextElementSibling(node))continue;results.push(node);}
return results;},'only-child':function(nodes,value,root){var h=Selector.handlers;for(var i=0,results=[],node;node=nodes[i];i++)
if(!h.previousElementSibling(node)&&!h.nextElementSibling(node))
results.push(node);return results;},'nth-child':function(nodes,formula,root){return Selector.pseudos.nth(nodes,formula,root);},'nth-last-child':function(nodes,formula,root){return Selector.pseudos.nth(nodes,formula,root,true);},'nth-of-type':function(nodes,formula,root){return Selector.pseudos.nth(nodes,formula,root,false,true);},'nth-last-of-type':function(nodes,formula,root){return Selector.pseudos.nth(nodes,formula,root,true,true);},'first-of-type':function(nodes,formula,root){return Selector.pseudos.nth(nodes,"1",root,false,true);},'last-of-type':function(nodes,formula,root){return Selector.pseudos.nth(nodes,"1",root,true,true);},'only-of-type':function(nodes,formula,root){var p=Selector.pseudos;return p['last-of-type'](p['first-of-type'](nodes,formula,root),formula,root);},getIndices:function(a,b,total){if(a==0)return b>0?[b]:[];return $R(1,total).inject([],function(memo,i){if(0==(i-b)%a&&(i-b)/a>=0)memo.push(i);return memo;});},nth:function(nodes,formula,root,reverse,ofType){if(nodes.length==0)return[];if(formula=='even')formula='2n+0';if(formula=='odd')formula='2n+1';var h=Selector.handlers,results=[],indexed=[],m;h.mark(nodes);for(var i=0,node;node=nodes[i];i++){if(!node.parentNode._counted){h.index(node.parentNode,reverse,ofType);indexed.push(node.parentNode);}}
if(formula.match(/^\d+$/)){formula=Number(formula);for(var i=0,node;node=nodes[i];i++)
if(node.nodeIndex==formula)results.push(node);}else if(m=formula.match(/^(-?\d*)?n(([+-])(\d+))?/)){if(m[1]=="-")m[1]=-1;var a=m[1]?Number(m[1]):1;var b=m[2]?Number(m[2]):0;var indices=Selector.pseudos.getIndices(a,b,nodes.length);for(var i=0,node,l=indices.length;node=nodes[i];i++){for(var j=0;j<l;j++)
if(node.nodeIndex==indices[j])results.push(node);}}
h.unmark(nodes);h.unmark(indexed);return results;},'empty':function(nodes,value,root){for(var i=0,results=[],node;node=nodes[i];i++){if(node.tagName=='!'||(node.firstChild&&!node.innerHTML.match(/^\s*$/)))continue;results.push(node);}
return results;},'not':function(nodes,selector,root){var h=Selector.handlers,selectorType,m;var exclusions=new Selector(selector).findElements(root);h.mark(exclusions);for(var i=0,results=[],node;node=nodes[i];i++)
if(!node._counted)results.push(node);h.unmark(exclusions);return results;},'enabled':function(nodes,value,root){for(var i=0,results=[],node;node=nodes[i];i++)
if(!node.disabled)results.push(node);return results;},'disabled':function(nodes,value,root){for(var i=0,results=[],node;node=nodes[i];i++)
if(node.disabled)results.push(node);return results;},'checked':function(nodes,value,root){for(var i=0,results=[],node;node=nodes[i];i++)
if(node.checked)results.push(node);return results;}},operators:{'=':function(nv,v){return nv==v;},'!=':function(nv,v){return nv!=v;},'^=':function(nv,v){return nv.startsWith(v);},'$=':function(nv,v){return nv.endsWith(v);},'*=':function(nv,v){return nv.include(v);},'~=':function(nv,v){return(' '+nv+' ').include(' '+v+' ');},'|=':function(nv,v){return('-'+nv.toUpperCase()+'-').include('-'+v.toUpperCase()+'-');}},matchElements:function(elements,expression){var matches=new Selector(expression).findElements(),h=Selector.handlers;h.mark(matches);for(var i=0,results=[],element;element=elements[i];i++)
if(element._counted)results.push(element);h.unmark(matches);return results;},findElement:function(elements,expression,index){if(typeof expression=='number'){index=expression;expression=false;}
return Selector.matchElements(elements,expression||'*')[index||0];},findChildElements:function(element,expressions){var exprs=expressions.join(','),expressions=[];exprs.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/,function(m){expressions.push(m[1].strip());});var results=[],h=Selector.handlers;for(var i=0,l=expressions.length,selector;i<l;i++){selector=new Selector(expressions[i].strip());h.concat(results,selector.findElements(element));}
return(l>1)?h.unique(results):results;}});function $$(){return Selector.findChildElements(document,$A(arguments));}
var Form={reset:function(form){$(form).reset();return form;},serializeElements:function(elements,getHash){var data=elements.inject({},function(result,element){if(!element.disabled&&element.name){var key=element.name,value=$(element).getValue();if(value!=null){if(key in result){if(result[key].constructor!=Array)result[key]=[result[key]];result[key].push(value);}
else result[key]=value;}}
return result;});return getHash?data:Hash.toQueryString(data);}};Form.Methods={serialize:function(form,getHash){return Form.serializeElements(Form.getElements(form),getHash);},getElements:function(form){return $A($(form).getElementsByTagName('*')).inject([],function(elements,child){if(Form.Element.Serializers[child.tagName.toLowerCase()])
elements.push(Element.extend(child));return elements;});},getInputs:function(form,typeName,name){form=$(form);var inputs=form.getElementsByTagName('input');if(!typeName&&!name)return $A(inputs).map(Element.extend);for(var i=0,matchingInputs=[],length=inputs.length;i<length;i++){var input=inputs[i];if((typeName&&input.type!=typeName)||(name&&input.name!=name))
continue;matchingInputs.push(Element.extend(input));}
return matchingInputs;},disable:function(form){form=$(form);Form.getElements(form).invoke('disable');return form;},enable:function(form){form=$(form);Form.getElements(form).invoke('enable');return form;},findFirstElement:function(form){return $(form).getElements().find(function(element){return element.type!='hidden'&&!element.disabled&&['input','select','textarea'].include(element.tagName.toLowerCase());});},focusFirstElement:function(form){form=$(form);form.findFirstElement().activate();return form;},request:function(form,options){form=$(form),options=Object.clone(options||{});var params=options.parameters;options.parameters=form.serialize(true);if(params){if(typeof params=='string')params=params.toQueryParams();Object.extend(options.parameters,params);}
if(form.hasAttribute('method')&&!options.method)
options.method=form.method;return new Ajax.Request(form.readAttribute('action'),options);}}
Form.Element={focus:function(element){$(element).focus();return element;},select:function(element){$(element).select();return element;}}
Form.Element.Methods={serialize:function(element){element=$(element);if(!element.disabled&&element.name){var value=element.getValue();if(value!=undefined){var pair={};pair[element.name]=value;return Hash.toQueryString(pair);}}
return'';},getValue:function(element){element=$(element);var method=element.tagName.toLowerCase();return Form.Element.Serializers[method](element);},clear:function(element){$(element).value='';return element;},present:function(element){return $(element).value!='';},activate:function(element){element=$(element);try{element.focus();if(element.select&&(element.tagName.toLowerCase()!='input'||!['button','reset','submit'].include(element.type)))
element.select();}catch(e){}
return element;},disable:function(element){element=$(element);element.blur();element.disabled=true;return element;},enable:function(element){element=$(element);element.disabled=false;return element;}}
var Field=Form.Element;var $F=Form.Element.Methods.getValue;Form.Element.Serializers={input:function(element){switch(element.type.toLowerCase()){case'checkbox':case'radio':return Form.Element.Serializers.inputSelector(element);default:return Form.Element.Serializers.textarea(element);}},inputSelector:function(element){return element.checked?element.value:null;},textarea:function(element){return element.value;},select:function(element){return this[element.type=='select-one'?'selectOne':'selectMany'](element);},selectOne:function(element){var index=element.selectedIndex;return index>=0?this.optionValue(element.options[index]):null;},selectMany:function(element){var values,length=element.length;if(!length)return null;for(var i=0,values=[];i<length;i++){var opt=element.options[i];if(opt.selected)values.push(this.optionValue(opt));}
return values;},optionValue:function(opt){return Element.extend(opt).hasAttribute('value')?opt.value:opt.text;}}
Abstract.TimedObserver=function(){}
Abstract.TimedObserver.prototype={initialize:function(element,frequency,callback){this.frequency=frequency;this.element=$(element);this.callback=callback;this.lastValue=this.getValue();this.registerCallback();},registerCallback:function(){setInterval(this.onTimerEvent.bind(this),this.frequency*1000);},onTimerEvent:function(){var value=this.getValue();var changed=('string'==typeof this.lastValue&&'string'==typeof value?this.lastValue!=value:String(this.lastValue)!=String(value));if(changed){this.callback(this.element,value);this.lastValue=value;}}}
Form.Element.Observer=Class.create();Form.Element.Observer.prototype=Object.extend(new Abstract.TimedObserver(),{getValue:function(){return Form.Element.getValue(this.element);}});Form.Observer=Class.create();Form.Observer.prototype=Object.extend(new Abstract.TimedObserver(),{getValue:function(){return Form.serialize(this.element);}});Abstract.EventObserver=function(){}
Abstract.EventObserver.prototype={initialize:function(element,callback){this.element=$(element);this.callback=callback;this.lastValue=this.getValue();if(this.element.tagName.toLowerCase()=='form')
this.registerFormCallbacks();else
this.registerCallback(this.element);},onElementEvent:function(){var value=this.getValue();if(this.lastValue!=value){this.callback(this.element,value);this.lastValue=value;}},registerFormCallbacks:function(){Form.getElements(this.element).each(this.registerCallback.bind(this));},registerCallback:function(element){if(element.type){switch(element.type.toLowerCase()){case'checkbox':case'radio':Event.observe(element,'click',this.onElementEvent.bind(this));break;default:Event.observe(element,'change',this.onElementEvent.bind(this));break;}}}}
Form.Element.EventObserver=Class.create();Form.Element.EventObserver.prototype=Object.extend(new Abstract.EventObserver(),{getValue:function(){return Form.Element.getValue(this.element);}});Form.EventObserver=Class.create();Form.EventObserver.prototype=Object.extend(new Abstract.EventObserver(),{getValue:function(){return Form.serialize(this.element);}});if(!window.Event){var Event=new Object();}
Object.extend(Event,{KEY_BACKSPACE:8,KEY_TAB:9,KEY_RETURN:13,KEY_ESC:27,KEY_LEFT:37,KEY_UP:38,KEY_RIGHT:39,KEY_DOWN:40,KEY_DELETE:46,KEY_HOME:36,KEY_END:35,KEY_PAGEUP:33,KEY_PAGEDOWN:34,element:function(event){return $(event.target||event.srcElement);},isLeftClick:function(event){return(((event.which)&&(event.which==1))||((event.button)&&(event.button==1)));},pointerX:function(event){return event.pageX||(event.clientX+
(document.documentElement.scrollLeft||document.body.scrollLeft));},pointerY:function(event){return event.pageY||(event.clientY+
(document.documentElement.scrollTop||document.body.scrollTop));},stop:function(event){if(event.preventDefault){event.preventDefault();event.stopPropagation();}else{event.returnValue=false;event.cancelBubble=true;}},findElement:function(event,tagName){var element=Event.element(event);while(element.parentNode&&(!element.tagName||(element.tagName.toUpperCase()!=tagName.toUpperCase())))
element=element.parentNode;return element;},observers:false,_observeAndCache:function(element,name,observer,useCapture){if(!this.observers)this.observers=[];if(element.addEventListener){this.observers.push([element,name,observer,useCapture]);element.addEventListener(name,observer,useCapture);}else if(element.attachEvent){this.observers.push([element,name,observer,useCapture]);element.attachEvent('on'+name,observer);}},unloadCache:function(){if(!Event.observers)return;for(var i=0,length=Event.observers.length;i<length;i++){Event.stopObserving.apply(this,Event.observers[i]);Event.observers[i][0]=null;}
Event.observers=false;},observe:function(element,name,observer,useCapture){element=$(element);useCapture=useCapture||false;if(name=='keypress'&&(Prototype.Browser.WebKit||element.attachEvent))
name='keydown';Event._observeAndCache(element,name,observer,useCapture);},stopObserving:function(element,name,observer,useCapture){element=$(element);useCapture=useCapture||false;if(name=='keypress'&&(Prototype.Browser.WebKit||element.attachEvent))
name='keydown';if(element.removeEventListener){element.removeEventListener(name,observer,useCapture);}else if(element.detachEvent){try{element.detachEvent('on'+name,observer);}catch(e){}}}});if(Prototype.Browser.IE)
Event.observe(window,'unload',Event.unloadCache,false);var Position={includeScrollOffsets:false,prepare:function(){this.deltaX=window.pageXOffset||document.documentElement.scrollLeft||document.body.scrollLeft||0;this.deltaY=window.pageYOffset||document.documentElement.scrollTop||document.body.scrollTop||0;},realOffset:function(element){var valueT=0,valueL=0;do{valueT+=element.scrollTop||0;valueL+=element.scrollLeft||0;element=element.parentNode;}while(element);return[valueL,valueT];},cumulativeOffset:function(element){var valueT=0,valueL=0;do{valueT+=element.offsetTop||0;valueL+=element.offsetLeft||0;element=element.offsetParent;}while(element);return[valueL,valueT];},positionedOffset:function(element){var valueT=0,valueL=0;do{valueT+=element.offsetTop||0;valueL+=element.offsetLeft||0;element=element.offsetParent;if(element){if(element.tagName=='BODY')break;var p=Element.getStyle(element,'position');if(p=='relative'||p=='absolute')break;}}while(element);return[valueL,valueT];},offsetParent:function(element){if(element.offsetParent)return element.offsetParent;if(element==document.body)return element;while((element=element.parentNode)&&element!=document.body)
if(Element.getStyle(element,'position')!='static')
return element;return document.body;},within:function(element,x,y){if(this.includeScrollOffsets)
return this.withinIncludingScrolloffsets(element,x,y);this.xcomp=x;this.ycomp=y;this.offset=this.cumulativeOffset(element);return(y>=this.offset[1]&&y<this.offset[1]+element.offsetHeight&&x>=this.offset[0]&&x<this.offset[0]+element.offsetWidth);},withinIncludingScrolloffsets:function(element,x,y){var offsetcache=this.realOffset(element);this.xcomp=x+offsetcache[0]-this.deltaX;this.ycomp=y+offsetcache[1]-this.deltaY;this.offset=this.cumulativeOffset(element);return(this.ycomp>=this.offset[1]&&this.ycomp<this.offset[1]+element.offsetHeight&&this.xcomp>=this.offset[0]&&this.xcomp<this.offset[0]+element.offsetWidth);},overlap:function(mode,element){if(!mode)return 0;if(mode=='vertical')
return((this.offset[1]+element.offsetHeight)-this.ycomp)/element.offsetHeight;if(mode=='horizontal')
return((this.offset[0]+element.offsetWidth)-this.xcomp)/element.offsetWidth;},page:function(forElement){var valueT=0,valueL=0;var element=forElement;do{valueT+=element.offsetTop||0;valueL+=element.offsetLeft||0;if(element.offsetParent==document.body)
if(Element.getStyle(element,'position')=='absolute')break;}while(element=element.offsetParent);element=forElement;do{if(!window.opera||element.tagName=='BODY'){valueT-=element.scrollTop||0;valueL-=element.scrollLeft||0;}}while(element=element.parentNode);return[valueL,valueT];},clone:function(source,target){var options=Object.extend({setLeft:true,setTop:true,setWidth:true,setHeight:true,offsetTop:0,offsetLeft:0},arguments[2]||{})
source=$(source);var p=Position.page(source);target=$(target);var delta=[0,0];var parent=null;if(Element.getStyle(target,'position')=='absolute'){parent=Position.offsetParent(target);delta=Position.page(parent);}
if(parent==document.body){delta[0]-=document.body.offsetLeft;delta[1]-=document.body.offsetTop;}
if(options.setLeft)target.style.left=(p[0]-delta[0]+options.offsetLeft)+'px';if(options.setTop)target.style.top=(p[1]-delta[1]+options.offsetTop)+'px';if(options.setWidth)target.style.width=source.offsetWidth+'px';if(options.setHeight)target.style.height=source.offsetHeight+'px';},absolutize:function(element){element=$(element);if(element.style.position=='absolute')return;Position.prepare();var offsets=Position.positionedOffset(element);var top=offsets[1];var left=offsets[0];var width=element.clientWidth;var height=element.clientHeight;element._originalLeft=left-parseFloat(element.style.left||0);element._originalTop=top-parseFloat(element.style.top||0);element._originalWidth=element.style.width;element._originalHeight=element.style.height;element.style.position='absolute';element.style.top=top+'px';element.style.left=left+'px';element.style.width=width+'px';element.style.height=height+'px';},relativize:function(element){element=$(element);if(element.style.position=='relative')return;Position.prepare();element.style.position='relative';var top=parseFloat(element.style.top||0)-(element._originalTop||0);var left=parseFloat(element.style.left||0)-(element._originalLeft||0);element.style.top=top+'px';element.style.left=left+'px';element.style.height=element._originalHeight;element.style.width=element._originalWidth;}}
if(Prototype.Browser.WebKit){Position.cumulativeOffset=function(element){var valueT=0,valueL=0;do{valueT+=element.offsetTop||0;valueL+=element.offsetLeft||0;if(element.offsetParent==document.body)
if(Element.getStyle(element,'position')=='absolute')break;element=element.offsetParent;}while(element);return[valueL,valueT];}}
Element.addMethods();

/* ---------------------------------------------------------*/
/* --->>> onDOMReady Extension for prototype v1.5 <<<-------*/
/* ---------------------------------------------------------*/


Object.extend(Event, {
  _domReady : function() {
    if (arguments.callee.done) return;
    arguments.callee.done = true;

    if (this._timer)  clearInterval(this._timer);
    
    this._readyCallbacks.each(function(f) { f() });
    this._readyCallbacks = null;
},
  onDOMReady : function(f) {
    if (!this._readyCallbacks) {
      var domReady = this._domReady.bind(this);
      
      if (document.addEventListener)
        document.addEventListener("DOMContentLoaded", domReady, false);
        
        /*@cc_on @*/
        /*@if (@_win32)
            document.write("<script id=__ie_onload defer src=//:><\/script>");
            document.getElementById("__ie_onload").onreadystatechange = function() {
                if (this.readyState == "complete") domReady(); 
            };
        /*@end @*/
        
        if (/WebKit/i.test(navigator.userAgent)) { 
          this._timer = setInterval(function() {
            if (/loaded|complete/.test(document.readyState)) domReady(); 
          }, 10);
        }
        
        Event.observe(window, 'load', domReady);
        Event._readyCallbacks =  [];
    }
    Event._readyCallbacks.push(f);
  }
});
//end DOM ready for prototype 1.5

//end /sites/scripts/prototype-1.5.1.1-min.js
//start /sites/scripts/scriptaculous.js
// Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// 
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

var Scriptaculous = {
  Version: '1.5.0',
  require: function(libraryName) {
    // inserting via DOM fails in Safari 2.0, so brute force approach
    document.write('<script type="text/javascript" src="'+libraryName+'"></script>');
  },
  load: function() {
    if((typeof Prototype=='undefined') ||
      parseFloat(Prototype.Version.split(".")[0] + "." +
                 Prototype.Version.split(".")[1]) < 1.4)
      throw("script.aculo.us requires the Prototype JavaScript framework >= 1.4.0");
    var scriptTags = document.getElementsByTagName("script");
    for(var i=0;i<scriptTags.length;i++) {
      if(scriptTags[i].src && scriptTags[i].src.match(/scriptaculous\.js(\?.*)?$/)) {
        var path = scriptTags[i].src.replace(/scriptaculous\.js(\?.*)?$/,'');
        //this.require(path + 'builder.js');
        //this.require(path + 'effects.js');
        //this.require(path + 'dragdrop.js');
        //this.require(path + 'controls.js');
        //this.require(path + 'slider.js');
        break;
      }
    }
  }
}

Scriptaculous.load();
//end /sites/scripts/scriptaculous.js
//start /sites/scripts/builder.js
// Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//
// See scriptaculous.js for full license.

var Builder = {
  NODEMAP: {
    AREA: 'map',
    CAPTION: 'table',
    COL: 'table',
    COLGROUP: 'table',
    LEGEND: 'fieldset',
    OPTGROUP: 'select',
    OPTION: 'select',
    PARAM: 'object',
    TBODY: 'table',
    TD: 'table',
    TFOOT: 'table',
    TH: 'table',
    THEAD: 'table',
    TR: 'table'
  },
  // note: For Firefox < 1.5, OPTION and OPTGROUP tags are currently broken,
  //       due to a Firefox bug
  node: function(elementName) {
    elementName = elementName.toUpperCase();
    
    // try innerHTML approach
    var parentTag = this.NODEMAP[elementName] || 'div';
    var parentElement = document.createElement(parentTag);
    try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707
      parentElement.innerHTML = "<" + elementName + "></" + elementName + ">";
    } catch(e) {}
    var element = parentElement.firstChild || null;
      
    // see if browser added wrapping tags
    if(element && (element.tagName != elementName))
      element = element.getElementsByTagName(elementName)[0];
    
    // fallback to createElement approach
    if(!element) element = document.createElement(elementName);
    
    // abort if nothing could be created
    if(!element) return;

    // attributes (or text)
    if(arguments[1])
      if(this._isStringOrNumber(arguments[1]) ||
        (arguments[1] instanceof Array)) {
          this._children(element, arguments[1]);
        } else {
          var attrs = this._attributes(arguments[1]);
          if(attrs.length) {
            try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707
              parentElement.innerHTML = "<" +elementName + " " +
                attrs + "></" + elementName + ">";
            } catch(e) {}
            element = parentElement.firstChild || null;
            // workaround firefox 1.0.X bug
            if(!element) {
              element = document.createElement(elementName);
              for(attr in arguments[1]) 
                element[attr == 'class' ? 'className' : attr] = arguments[1][attr];
            }
            if(element.tagName != elementName)
              element = parentElement.getElementsByTagName(elementName)[0];
            }
        } 

    // text, or array of children
    if(arguments[2])
      this._children(element, arguments[2]);

     return element;
  },
  _text: function(text) {
     return document.createTextNode(text);
  },
  _attributes: function(attributes) {
    var attrs = [];
    for(attribute in attributes)
      attrs.push((attribute=='className' ? 'class' : attribute) +
          '="' + attributes[attribute].toString().escapeHTML() + '"');
    return attrs.join(" ");
  },
  _children: function(element, children) {
    if(typeof children=='object') { // array can hold nodes and text
      children.flatten().each( function(e) {
        if(typeof e=='object')
          element.appendChild(e)
        else
          if(Builder._isStringOrNumber(e))
            element.appendChild(Builder._text(e));
      });
    } else
      if(Builder._isStringOrNumber(children)) 
         element.appendChild(Builder._text(children));
  },
  _isStringOrNumber: function(param) {
    return(typeof param=='string' || typeof param=='number');
  }
}

//end /sites/scripts/builder.js
//start /sites/infonotmercial/scripts/dhtmlwindow.js
// -------------------------------------------------------------------
// DHTML Window Widget- By Dynamic Drive, available at: http://www.dynamicdrive.com
// v1.0: Script created Feb 15th, 07'
// v1.01: Feb 21th, 07' (see changelog.txt)
// v1.02: March 26th, 07' (see changelog.txt)
// v1.03: May 5th, 07' (see changelog.txt)
// v1.1:  Oct 29th, 07' (see changelog.txt)
// -------------------------------------------------------------------

var dhtmlwindow={
imagefiles:['/sites/infonotmercial/images/spacer.gif', '/sites/infonotmercial/images/new/puCloseButton.gif', '/sites/infonotmercial/images/spacer.gif', '/sites/infonotmercial/images/spacer.gif'], //Path to 4 images used by script, in that order
ajaxbustcache: true, //Bust caching when fetching a file via Ajax?
ajaxloadinghtml: '<table width="680px"><tr><td><b>Loading Page. Please wait...</b></td></tr>', //HTML to show while window fetches Ajax Content?

minimizeorder: 0,
zIndexvalue:1550,
tobjects: [], //object to contain references to dhtml window divs, for cleanup purposes
lastactivet: {}, //reference to last active DHTML window

init:function(t){
	var domwindow=document.createElement("div"); //create dhtml window div
	domwindow.id=t;
	domwindow.className="dhtmlwindow";
	var domwindowdata='';
	domwindowdata='<table cellpadding="0" cellspacing="0" width="102%"><tr><td><div class="drag-window"><div class="drag-handle">';
	domwindowdata+='DHTML Window <div class="drag-controls"><img src="'+this.imagefiles[0]+'" title="Minimize" /><img src="'+this.imagefiles[1]+'" title="Close" /></div>'
	domwindowdata+='</div>';
	domwindowdata+='<div class="drag-contentarea"></div>';
	domwindowdata+='<div class="drag-statusarea"><div class="drag-resizearea" style="background: transparent url('+this.imagefiles[3]+') top right no-repeat;">&nbsp;</div></div>'
	domwindowdata+='</div></div></td></tr>'
	domwindowdata+='</table>';
	domwindow.innerHTML=domwindowdata;
	document.getElementById("dhtmlwindowholder").appendChild(domwindow)
	//this.zIndexvalue=(this.zIndexvalue)? this.zIndexvalue+1 : 100 //z-index value for DHTML window: starts at 0, increments whenever a window has focus
	var t=document.getElementById(t)
	var divs=t.getElementsByTagName("div")
	for (var i=0; i<divs.length; i++){ //go through divs inside dhtml window and extract all those with class="drag-" prefix
		if (/drag-/.test(divs[i].className))
			t[divs[i].className.replace(/drag-/, "")]=divs[i] //take out the "drag-" prefix for shorter access by name
	}
	//t.style.zIndex=this.zIndexvalue //set z-index of this dhtml window
	t.handle._parent=t //store back reference to dhtml window
	t.resizearea._parent=t //same
	t.controls._parent=t //same
	t.onclose=function(){return true} //custom event handler "onclose"
	t.onmousedown=function(){dhtmlwindow.setfocus(this)} //Increase z-index of window when focus is on it
	t.handle.onmousedown=dhtmlwindow.setupdrag //set up drag behavior when mouse down on handle div
	t.resizearea.onmousedown=dhtmlwindow.setupdrag //set up drag behavior when mouse down on resize div
	t.controls.onclick=dhtmlwindow.enablecontrols
	t.show=function(){dhtmlwindow.show(this)} //public function for showing dhtml window
	t.hide=function(){dhtmlwindow.hide(this)} //public function for hiding dhtml window
	t.close=function(){grayOut(false);dhtmlwindow.close(this)} //public function for closing dhtml window (also empties DHTML window content)
	t.setSize=function(w, h){dhtmlwindow.setSize(this, w, h)} //public function for setting window dimensions
	t.moveTo=function(x, y){dhtmlwindow.moveTo(this, x, y)} //public function for moving dhtml window (relative to viewpoint)
	t.isResize=function(bol){dhtmlwindow.isResize(this, bol)} //public function for specifying if window is resizable
	t.isScrolling=function(bol){dhtmlwindow.isScrolling(this, bol)} //public function for specifying if window content contains scrollbars
	t.load=function(contenttype, contentsource, title){dhtmlwindow.load(this, contenttype, contentsource, title)} //public function for loading content into window
	this.tobjects[this.tobjects.length]=t
	return t //return reference to dhtml window div
},

open:function(t, contenttype, contentsource, title, attr, recalonload){
	var d=dhtmlwindow //reference dhtml window object
	function getValue(Name){
		var config=new RegExp(Name+"=([^,]+)", "i") //get name/value config pair (ie: width=400px,)
		return (config.test(attr))? parseInt(RegExp.$1) : 0 //return value portion (int), or 0 (false) if none found
	}
	if (document.getElementById(t)==null) //if window doesn't exist yet, create it
		t=this.init(t) //return reference to dhtml window div
	else
		t=document.getElementById(t)
	this.setfocus(t)
	t.setSize(getValue(("width")), (getValue("height"))) //Set dimensions of window
	var xpos=getValue("center")? "middle" : getValue("left") //Get x coord of window
	var ypos=getValue("center")? "middle" : getValue("top") //Get y coord of window
	//t.moveTo(xpos, ypos) //Position window
	if (typeof recalonload!="undefined" && recalonload=="recal" && this.scroll_top==0){ //reposition window when page fully loads with updated window viewpoints?
		if (window.attachEvent && !window.opera) //In IE, add another 400 milisecs on page load (viewpoint properties may return 0 b4 then)
			this.addEvent(window, function(){setTimeout(function(){t.moveTo(xpos, ypos)}, 400)}, "load")
		else
			this.addEvent(window, function(){t.moveTo(xpos, ypos)}, "load")
	}
	t.isResize(getValue("resize")) //Set whether window is resizable
	t.isScrolling(getValue("scrolling")) //Set whether window should contain scrollbars
	t.style.visibility="visible"
	t.style.display="block"
	t.contentarea.style.display="block"
	t.moveTo(xpos, ypos) //Position window
	t.load(contenttype, contentsource, title)
	if (t.state=="minimized" && t.controls.firstChild.title=="Restore"){ //If window exists and is currently minimized?
		t.controls.firstChild.setAttribute("src", dhtmlwindow.imagefiles[0]) //Change "restore" icon within window interface to "minimize" icon
		t.controls.firstChild.setAttribute("title", "Minimize")
		t.state="fullview" //indicate the state of the window as being "fullview"
	}
	return t
},

setSize:function(t, w, h){ //set window size (min is 150px wide by 100px tall)
	t.style.width=Math.max(parseInt(w), 150)+"px"
	t.contentarea.style.height=Math.max(parseInt(h), 100)+"px"
},

moveTo:function(t, x, y){ //move window. Position includes current viewpoint of document
	this.getviewpoint() //Get current viewpoint numbers
	t.style.left=(x=="middle")? this.scroll_left+(this.docwidth-t.offsetWidth)/2+"px" : this.scroll_left+parseInt(x)+"px"
	t.style.top=(y=="middle")? this.scroll_top+(this.docheight-t.offsetHeight)/2+"px" : this.scroll_top+parseInt(y)+"px"
},

isResize:function(t, bol){ //show or hide resize inteface (part of the status bar)
	t.statusarea.style.display=(bol)? "block" : "none"
	t.resizeBool=(bol)? 1 : 0
},

isScrolling:function(t, bol){ //set whether loaded content contains scrollbars
	t.contentarea.style.overflow=(bol)? "auto" : "hidden"
},

load:function(t, contenttype, contentsource, title){ //loads content into window plus set its title (3 content types: "inline", "iframe", or "ajax")
	if (t.isClosed){
		//alert("DHTML Window has been closed, so no window to load contents into. Open/Create the window again.")
		return
	}
	var contenttype=contenttype.toLowerCase() //convert string to lower case
	if (typeof title!="undefined")
		t.handle.firstChild.nodeValue=title
	if (contenttype=="inline")
		t.contentarea.innerHTML=contentsource
	else if (contenttype=="div"){
		var inlinedivref=document.getElementById(contentsource)
		t.contentarea.innerHTML=(inlinedivref.defaultHTML || inlinedivref.innerHTML) //Populate window with contents of inline div on page
		if (!inlinedivref.defaultHTML)
			inlinedivref.defaultHTML=inlinedivref.innerHTML //save HTML within inline DIV
		inlinedivref.innerHTML="" //then, remove HTML within inline DIV (to prevent duplicate IDs, NAME attributes etc in contents of DHTML window
		inlinedivref.style.display="none" //hide that div
	}
	else if (contenttype=="iframe"){
		t.contentarea.style.overflow="hidden" //disable window scrollbars, as iframe already contains scrollbars
		if (!t.contentarea.firstChild || t.contentarea.firstChild.tagName!="IFRAME") //If iframe tag doesn't exist already, create it first
			t.contentarea.innerHTML='<iframe src="" style="margin:0; padding:0; width:100%; height: 100%" name="_iframe-'+t.id+'"></iframe>'
		window.frames["_iframe-"+t.id].location.replace(contentsource) //set location of iframe window to specified URL
		}
	else if (contenttype=="ajax"){
		this.ajax_connect(contentsource, t) //populate window with external contents fetched via Ajax
	}
	t.contentarea.datatype=contenttype //store contenttype of current window for future reference
},

setupdrag:function(e){
	var d=dhtmlwindow //reference dhtml window object
	var t=this._parent //reference dhtml window div
	d.etarget=this //remember div mouse is currently held down on ("handle" or "resize" div)
	var e=window.event || e
	d.initmousex=e.clientX //store x position of mouse onmousedown
	d.initmousey=e.clientY
	d.initx=parseInt(t.offsetLeft) //store offset x of window div onmousedown
	d.inity=parseInt(t.offsetTop)
	d.width=parseInt(t.offsetWidth) //store width of window div
	d.contentheight=parseInt(t.contentarea.offsetHeight) //store height of window div's content div
	if (t.contentarea.datatype=="iframe"){ //if content of this window div is "iframe"
		t.style.backgroundColor="#F8F8F8" //colorize and hide content div (while window is being dragged)
		t.contentarea.style.visibility="hidden"
	}
	document.onmousemove=d.getdistance //get distance travelled by mouse as it moves
	document.onmouseup=function(){
		if (t.contentarea.datatype=="iframe"){ //restore color and visibility of content div onmouseup
			t.contentarea.style.backgroundColor="white"
			t.contentarea.style.visibility="visible"
		}
		d.stop()
	}
	return false
},

getdistance:function(e){
	var d=dhtmlwindow
	var etarget=d.etarget
	var e=window.event || e
	d.distancex=e.clientX-d.initmousex //horizontal distance travelled relative to starting point
	d.distancey=e.clientY-d.initmousey
	if (etarget.className=="drag-handle") //if target element is "handle" div
		d.move(etarget._parent, e)
	else if (etarget.className=="drag-resizearea") //if target element is "resize" div
		d.resize(etarget._parent, e)
	return false //cancel default dragging behavior
},

getviewpoint:function(){ //get window viewpoint numbers
	var ie=document.all && !window.opera
	var domclientWidth=document.documentElement && parseInt(document.documentElement.clientWidth) || 100000 //Preliminary doc width in non IE browsers
	this.standardbody=(document.compatMode=="CSS1Compat")? document.documentElement : document.body //create reference to common "body" across doctypes
	this.scroll_top=(ie)? this.standardbody.scrollTop : window.pageYOffset
	this.scroll_left=(ie)? this.standardbody.scrollLeft : window.pageXOffset
	this.docwidth=(ie)? this.standardbody.clientWidth : (/Safari/i.test(navigator.userAgent))? window.innerWidth : Math.min(domclientWidth, window.innerWidth-16)
	this.docheight=(ie)? this.standardbody.clientHeight: window.innerHeight
},

rememberattrs:function(t){ //remember certain attributes of the window when it's minimized or closed, such as dimensions, position on page
	this.getviewpoint() //Get current window viewpoint numbers
	t.lastx=parseInt((t.style.left || t.offsetLeft))-dhtmlwindow.scroll_left //store last known x coord of window just before minimizing
	t.lasty=parseInt((t.style.top || t.offsetTop))-dhtmlwindow.scroll_top
	t.lastwidth=parseInt(t.style.width) //store last known width of window just before minimizing/ closing
},

move:function(t, e){
	t.style.left=dhtmlwindow.distancex+dhtmlwindow.initx+"px"
	t.style.top=dhtmlwindow.distancey+dhtmlwindow.inity+"px"
},

resize:function(t, e){
	t.style.width=Math.max(dhtmlwindow.width+dhtmlwindow.distancex, 150)+"px"
	t.contentarea.style.height=Math.max(dhtmlwindow.contentheight+dhtmlwindow.distancey, 100)+"px"
},

enablecontrols:function(e){
	var d=dhtmlwindow
	var sourceobj=window.event? window.event.srcElement : e.target //Get element within "handle" div mouse is currently on (the controls)
	if (/Minimize/i.test(sourceobj.getAttribute("title"))) //if this is the "minimize" control
		d.minimize(sourceobj, this._parent)
	else if (/Restore/i.test(sourceobj.getAttribute("title"))) //if this is the "restore" control
		d.restore(sourceobj, this._parent)
	else if (/Close/i.test(sourceobj.getAttribute("title"))) //if this is the "close" control
		d.close(this._parent)
	return false
},

minimize:function(button, t){
	dhtmlwindow.rememberattrs(t)
	button.setAttribute("src", dhtmlwindow.imagefiles[2])
	button.setAttribute("title", "Restore")
	t.state="minimized" //indicate the state of the window as being "minimized"
	t.contentarea.style.display="none"
	t.statusarea.style.display="none"
	if (typeof t.minimizeorder=="undefined"){ //stack order of minmized window on screen relative to any other minimized windows
		dhtmlwindow.minimizeorder++ //increment order
		t.minimizeorder=dhtmlwindow.minimizeorder
	}
	t.style.left="10px" //left coord of minmized window
	t.style.width="200px"
	var windowspacing=t.minimizeorder*10 //spacing (gap) between each minmized window(s)
	t.style.top=dhtmlwindow.scroll_top+dhtmlwindow.docheight-(t.handle.offsetHeight*t.minimizeorder)-windowspacing+"px"
},

restore:function(button, t){
	dhtmlwindow.getviewpoint()
	button.setAttribute("src", dhtmlwindow.imagefiles[0])
	button.setAttribute("title", "Minimize")
	t.state="fullview" //indicate the state of the window as being "fullview"
	t.style.display="block"
	t.contentarea.style.display="block"
	if (t.resizeBool) //if this window is resizable, enable the resize icon
		t.statusarea.style.display="block"
	t.style.left=parseInt(t.lastx)+dhtmlwindow.scroll_left+"px" //position window to last known x coord just before minimizing
	t.style.top=parseInt(t.lasty)+dhtmlwindow.scroll_top+"px"
	t.style.width=parseInt(t.lastwidth)+"px"
},


close:function(t){
    try{
        grayOut(false);
    }
    catch(err){
        //do nothing
    }
	try{
		var closewinbol=t.onclose()
	}
	catch(err){ //In non IE browsers, all errors are caught, so just run the below
		var closewinbol=true
 }
	finally{ //In IE, not all errors are caught, so check if variable isn't defined in IE in those cases
		if (typeof closewinbol=="undefined"){
			//alert("An error has occured somwhere inside your \"onclose\" event handler")
			var closewinbol=true
		}
	}
	if (closewinbol){ //if custom event handler function returns true
		if (t.state!="minimized") //if this window isn't currently minimized
			dhtmlwindow.rememberattrs(t) //remember window's dimensions/position on the page before closing
		if (window.frames["_iframe-"+t.id]) //if this is an IFRAME DHTML window
			window.frames["_iframe-"+t.id].location.replace("about:blank")
		else
			t.contentarea.innerHTML=""
		t.style.display="none"
		t.isClosed=true //tell script this window is closed (for detection in t.show())
	}
	return closewinbol
},


setopacity:function(targetobject, value){ //Sets the opacity of targetobject based on the passed in value setting (0 to 1 and in between)
	if (!targetobject)
		return
	if (targetobject.filters && targetobject.filters[0]){ //IE syntax
		if (typeof targetobject.filters[0].opacity=="number") //IE6
			targetobject.filters[0].opacity=value*100
		else //IE 5.5
			targetobject.style.filter="alpha(opacity="+value*100+")"
		}
	else if (typeof targetobject.style.MozOpacity!="undefined") //Old Mozilla syntax
		targetobject.style.MozOpacity=value
	else if (typeof targetobject.style.opacity!="undefined") //Standard opacity syntax
		targetobject.style.opacity=value
},

setfocus:function(t){ //Sets focus to the currently active window
	this.zIndexvalue++
	t.style.zIndex=this.zIndexvalue
	t.isClosed=false //tell script this window isn't closed (for detection in t.show())
	this.setopacity(this.lastactivet.handle, 0.5) //unfocus last active window
	this.setopacity(t.handle, 1) //focus currently active window
	this.lastactivet=t //remember last active window
},


show:function(t){
	if (t.isClosed){
		alert("DHTML Window has been closed, so nothing to show. Open/Create the window again.")
		return
	}
	if (t.lastx) //If there exists previously stored information such as last x position on window attributes (meaning it's been minimized or closed)
		dhtmlwindow.restore(t.controls.firstChild, t) //restore the window using that info
	else
		t.style.display="block"
	this.setfocus(t)
	t.state="fullview" //indicate the state of the window as being "fullview"
},

hide:function(t){
	t.style.display="none"
},

ajax_connect:function(url, t){
	var page_request = false
	var bustcacheparameter=""
	if (window.XMLHttpRequest) // if Mozilla, IE7, Safari etc
		page_request = new XMLHttpRequest()
	else if (window.ActiveXObject){ // if IE6 or below
		try {
		page_request = new ActiveXObject("Msxml2.XMLHTTP")
		} 
		catch (e){
			try{
			page_request = new ActiveXObject("Microsoft.XMLHTTP")
			}
			catch (e){}
		}
	}
	else
		return false
	t.contentarea.innerHTML=this.ajaxloadinghtml
	page_request.onreadystatechange=function(){dhtmlwindow.ajax_loadpage(page_request, t)}
	if (this.ajaxbustcache) //if bust caching of external page
		bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
	page_request.open('GET', url+bustcacheparameter, true)
	page_request.send(null)
},

ajax_loadpage:function(page_request, t){
	if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1)){
	t.contentarea.innerHTML=page_request.responseText
	}
},


stop:function(){
	dhtmlwindow.etarget=null //clean up
	document.onmousemove=null
	document.onmouseup=null
},

addEvent:function(target, functionref, tasktype){ //assign a function to execute to an event handler (ie: onunload)
	var tasktype=(window.addEventListener)? tasktype : "on"+tasktype
	if (target.addEventListener)
		target.addEventListener(tasktype, functionref, false)
	else if (target.attachEvent)
		target.attachEvent(tasktype, functionref)
},

cleanup:function(){
	for (var i=0; i<dhtmlwindow.tobjects.length; i++){
		dhtmlwindow.tobjects[i].handle._parent=dhtmlwindow.tobjects[i].resizearea._parent=dhtmlwindow.tobjects[i].controls._parent=null
	}
	window.onload=null
}

} //End dhtmlwindow object

document.write('<div id="dhtmlwindowholder"><span style="display:none">.</span></div>') //container that holds all dhtml window divs on page
window.onunload=dhtmlwindow.cleanup

//end /sites/infonotmercial/scripts/dhtmlwindow.js
//start /sites/scripts/effects.js
// Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// Contributors:
//  Justin Palmer (http://encytemedia.com/)
//  Mark Pilgrim (http://diveintomark.org/)
//  Martin Bialasinki
// 
// See scriptaculous.js for full license.  

/* ------------- element ext -------------- */  
 
// converts rgb() and #xxx to #xxxxxx format,  
// returns self (or first argument) if not convertable  
String.prototype.parseColor = function() {  
  var color = '#';  
  if(this.slice(0,4) == 'rgb(') {  
    var cols = this.slice(4,this.length-1).split(',');  
    var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3);  
  } else {  
    if(this.slice(0,1) == '#') {  
      if(this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase();  
      if(this.length==7) color = this.toLowerCase();  
    }  
  }  
  return(color.length==7 ? color : (arguments[0] || this));  
}  

Element.collectTextNodesIgnoreClass = function(element, ignoreclass) {  
  var children = $(element).childNodes;  
  var text     = '';  
  var classtest = new RegExp('^([^ ]+ )*' + ignoreclass+ '( [^ ]+)*$','i');  
 
  for (var i = 0; i < children.length; i++) {  
    if(children[i].nodeType==3) {  
      text+=children[i].nodeValue;  
    } else {  
      if((!children[i].className.match(classtest)) && children[i].hasChildNodes())  
        text += Element.collectTextNodesIgnoreClass(children[i], ignoreclass);  
    }  
  }  
 
  return text;
}

Element.setStyle = function(element, style) {
  element = $(element);
  for(k in style) element.style[k.camelize()] = style[k];
}

Element.setContentZoom = function(element, percent) {  
  Element.setStyle(element, {fontSize: (percent/100) + 'em'});   
  if(navigator.appVersion.indexOf('AppleWebKit')>0) window.scrollBy(0,0);  
}

Element.getOpacity = function(element){  
  var opacity;
  if (opacity = Element.getStyle(element, 'opacity'))  
    return parseFloat(opacity);  
  if (opacity = (Element.getStyle(element, 'filter') || '').match(/alpha\(opacity=(.*)\)/))  
    if(opacity[1]) return parseFloat(opacity[1]) / 100;  
  return 1.0;  
}

Element.setOpacity = function(element, value){  
  element= $(element);  
  if (value == 1){
    Element.setStyle(element, { opacity: 
      (/Gecko/.test(navigator.userAgent) && !/Konqueror|Safari|KHTML/.test(navigator.userAgent)) ? 
      0.999999 : null });
    if(/MSIE/.test(navigator.userAgent))  
      Element.setStyle(element, {filter: Element.getStyle(element,'filter').replace(/alpha\([^\)]*\)/gi,'')});  
  } else {  
    if(value < 0.00001) value = 0;  
    Element.setStyle(element, {opacity: value});
    if(/MSIE/.test(navigator.userAgent))  
     Element.setStyle(element, 
       { filter: Element.getStyle(element,'filter').replace(/alpha\([^\)]*\)/gi,'') +
                 'alpha(opacity='+value*100+')' });  
  }   
}  
 
Element.getInlineOpacity = function(element){  
  return $(element).style.opacity || '';
}  

Element.childrenWithClassName = function(element, className) {  
  return $A($(element).getElementsByTagName('*')).select(
    function(c) { return Element.hasClassName(c, className) });
}

Array.prototype.call = function() {
  var args = arguments;
  this.each(function(f){ f.apply(this, args) });
}

/*--------------------------------------------------------------------------*/

var Effect = {
  tagifyText: function(element) {
    var tagifyStyle = 'position:relative';
    if(/MSIE/.test(navigator.userAgent)) tagifyStyle += ';zoom:1';
    element = $(element);
    $A(element.childNodes).each( function(child) {
      if(child.nodeType==3) {
        child.nodeValue.toArray().each( function(character) {
          element.insertBefore(
            Builder.node('span',{style: tagifyStyle},
              character == ' ' ? String.fromCharCode(160) : character), 
              child);
        });
        Element.remove(child);
      }
    });
  },
  multiple: function(element, effect) {
    var elements;
    if(((typeof element == 'object') || 
        (typeof element == 'function')) && 
       (element.length))
      elements = element;
    else
      elements = $(element).childNodes;
      
    var options = Object.extend({
      speed: 0.1,
      delay: 0.0
    }, arguments[2] || {});
    var masterDelay = options.delay;

    $A(elements).each( function(element, index) {
      new effect(element, Object.extend(options, { delay: index * options.speed + masterDelay }));
    });
  }
};

var Effect2 = Effect; // deprecated

/* ------------- transitions ------------- */

Effect.Transitions = {}

Effect.Transitions.linear = function(pos) {
  return pos;
}
Effect.Transitions.sinoidal = function(pos) {
  return (-Math.cos(pos*Math.PI)/2) + 0.5;
}
Effect.Transitions.reverse  = function(pos) {
  return 1-pos;
}
Effect.Transitions.flicker = function(pos) {
  return ((-Math.cos(pos*Math.PI)/4) + 0.75) + Math.random()/4;
}
Effect.Transitions.wobble = function(pos) {
  return (-Math.cos(pos*Math.PI*(9*pos))/2) + 0.5;
}
Effect.Transitions.pulse = function(pos) {
  return (Math.floor(pos*10) % 2 == 0 ? 
    (pos*10-Math.floor(pos*10)) : 1-(pos*10-Math.floor(pos*10)));
}
Effect.Transitions.none = function(pos) {
  return 0;
}
Effect.Transitions.full = function(pos) {
  return 1;
}

/* ------------- core effects ------------- */

Effect.Queue = {
  effects:  [],
  _each: function(iterator) {
    this.effects._each(iterator);
  },
  interval: null,
  add: function(effect) {
    var timestamp = new Date().getTime();
    
    switch(effect.options.queue) {
      case 'front':
        // move unstarted effects after this effect  
        this.effects.findAll(function(e){ return e.state=='idle' }).each( function(e) {
            e.startOn  += effect.finishOn;
            e.finishOn += effect.finishOn;
          });
        break;
      case 'end':
        // start effect after last queued effect has finished
        timestamp = this.effects.pluck('finishOn').max() || timestamp;
        break;
    }
    
    effect.startOn  += timestamp;
    effect.finishOn += timestamp;
    this.effects.push(effect);
    if(!this.interval) 
      this.interval = setInterval(this.loop.bind(this), 40);
  },
  remove: function(effect) {
    this.effects = this.effects.reject(function(e) { return e==effect });
    if(this.effects.length == 0) {
      clearInterval(this.interval);
      this.interval = null;
    }
  },
  loop: function() {
    var timePos = new Date().getTime();
    this.effects.invoke('loop', timePos);
  }
}
Object.extend(Effect.Queue, Enumerable);

Effect.Base = function() {};
Effect.Base.prototype = {
  position: null,
  setOptions: function(options) {
    this.options = Object.extend({
      transition: Effect.Transitions.sinoidal,
      duration:   1.0,   // seconds
      fps:        25.0,  // max. 25fps due to Effect.Queue implementation
      sync:       false, // true for combining
      from:       0.0,
      to:         1.0,
      delay:      0.0,
      queue:      'parallel'
    }, options || {});
  },
  start: function(options) {
    this.setOptions(options || {});
    this.currentFrame = 0;
    this.state        = 'idle';
    this.startOn      = this.options.delay*1000;
    this.finishOn     = this.startOn + (this.options.duration*1000);
    this.event('beforeStart');
    if(!this.options.sync) Effect.Queue.add(this);
  },
  loop: function(timePos) {
    if(timePos >= this.startOn) {
      if(timePos >= this.finishOn) {
        this.render(1.0);
        this.cancel();
        this.event('beforeFinish');
        if(this.finish) this.finish(); 
        this.event('afterFinish');
        return;  
      }
      var pos   = (timePos - this.startOn) / (this.finishOn - this.startOn);
      var frame = Math.round(pos * this.options.fps * this.options.duration);
      if(frame > this.currentFrame) {
        this.render(pos);
        this.currentFrame = frame;
      }
    }
  },
  render: function(pos) {
    if(this.state == 'idle') {
      this.state = 'running';
      this.event('beforeSetup');
      if(this.setup) this.setup();
      this.event('afterSetup');
    }
    if(this.state == 'running') {
      if(this.options.transition) pos = this.options.transition(pos);
      pos *= (this.options.to-this.options.from);
      pos += this.options.from;
      this.position = pos;
      this.event('beforeUpdate');
      if(this.update) this.update(pos);
      this.event('afterUpdate');
    }
  },
  cancel: function() {
    if(!this.options.sync) Effect.Queue.remove(this);
    this.state = 'finished';
  },
  event: function(eventName) {
    if(this.options[eventName + 'Internal']) this.options[eventName + 'Internal'](this);
    if(this.options[eventName]) this.options[eventName](this);
  },
  inspect: function() {
    return '#<Effect:' + $H(this).inspect() + ',options:' + $H(this.options).inspect() + '>';
  }
}

Effect.Parallel = Class.create();
Object.extend(Object.extend(Effect.Parallel.prototype, Effect.Base.prototype), {
  initialize: function(effects) {
    this.effects = effects || [];
    this.start(arguments[1]);
  },
  update: function(position) {
    this.effects.invoke('render', position);
  },
  finish: function(position) {
    this.effects.each( function(effect) {
      effect.render(1.0);
      effect.cancel();
      effect.event('beforeFinish');
      if(effect.finish) effect.finish(position);
      effect.event('afterFinish');
    });
  }
});

Effect.Opacity = Class.create();
Object.extend(Object.extend(Effect.Opacity.prototype, Effect.Base.prototype), {
  initialize: function(element) {
    this.element = $(element);
    // make this work on IE on elements without 'layout'
    if(/MSIE/.test(navigator.userAgent) && (!this.element.hasLayout))
      Element.setStyle(this.element, {zoom: 1});
    var options = Object.extend({
      from: Element.getOpacity(this.element) || 0.0,
      to:   1.0
    }, arguments[1] || {});
    this.start(options);
  },
  update: function(position) {
    Element.setOpacity(this.element, position);
  }
});

Effect.MoveBy = Class.create();
Object.extend(Object.extend(Effect.MoveBy.prototype, Effect.Base.prototype), {
  initialize: function(element, toTop, toLeft) {
    this.element      = $(element);
    this.toTop        = toTop;
    this.toLeft       = toLeft;
    this.start(arguments[3]);
  },
  setup: function() {
    // Bug in Opera: Opera returns the "real" position of a static element or
    // relative element that does not have top/left explicitly set.
    // ==> Always set top and left for position relative elements in your stylesheets 
    // (to 0 if you do not need them) 
    Element.makePositioned(this.element);
    this.originalTop  = parseFloat(Element.getStyle(this.element,'top')  || '0');
    this.originalLeft = parseFloat(Element.getStyle(this.element,'left') || '0');
  },
  update: function(position) {
    Element.setStyle(this.element, {
      top:  this.toTop  * position + this.originalTop + 'px',
      left: this.toLeft * position + this.originalLeft + 'px'
    });
  }
});

Effect.Scale = Class.create();
Object.extend(Object.extend(Effect.Scale.prototype, Effect.Base.prototype), {
  initialize: function(element, percent) {
    this.element = $(element)
    var options = Object.extend({
      scaleX: true,
      scaleY: true,
      scaleContent: true,
      scaleFromCenter: false,
      scaleMode: 'box',        // 'box' or 'contents' or {} with provided values
      scaleFrom: 100.0,
      scaleTo:   percent
    }, arguments[2] || {});
    this.start(options);
  },
  setup: function() {
    this.restoreAfterFinish = this.options.restoreAfterFinish || false;
    this.elementPositioning = Element.getStyle(this.element,'position');
    
    this.originalStyle = {};
    ['top','left','width','height','fontSize'].each( function(k) {
      this.originalStyle[k] = this.element.style[k];
    }.bind(this));
      
    this.originalTop  = this.element.offsetTop;
    this.originalLeft = this.element.offsetLeft;
    
    var fontSize = Element.getStyle(this.element,'font-size') || '100%';
    ['em','px','%'].each( function(fontSizeType) {
      if(fontSize.indexOf(fontSizeType)>0) {
        this.fontSize     = parseFloat(fontSize);
        this.fontSizeType = fontSizeType;
      }
    }.bind(this));
    
    this.factor = (this.options.scaleTo - this.options.scaleFrom)/100;
    
    this.dims = null;
    if(this.options.scaleMode=='box')
      this.dims = [this.element.offsetHeight, this.element.offsetWidth];
    if(/^content/.test(this.options.scaleMode))
      this.dims = [this.element.scrollHeight, this.element.scrollWidth];
    if(!this.dims)
      this.dims = [this.options.scaleMode.originalHeight,
                   this.options.scaleMode.originalWidth];
  },
  update: function(position) {
    var currentScale = (this.options.scaleFrom/100.0) + (this.factor * position);
    if(this.options.scaleContent && this.fontSize)
      Element.setStyle(this.element, {fontSize: this.fontSize * currentScale + this.fontSizeType });
    this.setDimensions(this.dims[0] * currentScale, this.dims[1] * currentScale);
  },
  finish: function(position) {
    if (this.restoreAfterFinish) Element.setStyle(this.element, this.originalStyle);
  },
  setDimensions: function(height, width) {
    var d = {};
    if(this.options.scaleX) d.width = width + 'px';
    if(this.options.scaleY) d.height = height + 'px';
    if(this.options.scaleFromCenter) {
      var topd  = (height - this.dims[0])/2;
      var leftd = (width  - this.dims[1])/2;
      if(this.elementPositioning == 'absolute') {
        if(this.options.scaleY) d.top = this.originalTop-topd + 'px';
        if(this.options.scaleX) d.left = this.originalLeft-leftd + 'px';
      } else {
        if(this.options.scaleY) d.top = -topd + 'px';
        if(this.options.scaleX) d.left = -leftd + 'px';
      }
    }
    Element.setStyle(this.element, d);
  }
});

Effect.Highlight = Class.create();
Object.extend(Object.extend(Effect.Highlight.prototype, Effect.Base.prototype), {
  initialize: function(element) {
    this.element = $(element);
    var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || {});
    this.start(options);
  },
  setup: function() {
    // Prevent executing on elements not in the layout flow
    if(Element.getStyle(this.element, 'display')=='none') { this.cancel(); return; }
    // Disable background image during the effect
    this.oldStyle = {
      backgroundImage: Element.getStyle(this.element, 'background-image') };
    Element.setStyle(this.element, {backgroundImage: 'none'});
    if(!this.options.endcolor)
      this.options.endcolor = Element.getStyle(this.element, 'background-color').parseColor('#ffffff');
    if(!this.options.restorecolor)
      this.options.restorecolor = Element.getStyle(this.element, 'background-color');
    // init color calculations
    this._base  = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this));
    this._delta = $R(0,2).map(function(i){ return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i] }.bind(this));
  },
  update: function(position) {
    Element.setStyle(this.element,{backgroundColor: $R(0,2).inject('#',function(m,v,i){
      return m+(Math.round(this._base[i]+(this._delta[i]*position)).toColorPart()); }.bind(this)) });
  },
  finish: function() {
    Element.setStyle(this.element, Object.extend(this.oldStyle, {
      backgroundColor: this.options.restorecolor
    }));
  }
});

Effect.ScrollTo = Class.create();
Object.extend(Object.extend(Effect.ScrollTo.prototype, Effect.Base.prototype), {
  initialize: function(element) {
    this.element = $(element);
    this.start(arguments[1] || {});
  },
  setup: function() {
    Position.prepare();
    var offsets = Position.cumulativeOffset(this.element);
    if(this.options.offset) offsets[1] += this.options.offset;
    var max = window.innerHeight ? 
      window.height - window.innerHeight :
      document.body.scrollHeight - 
        (document.documentElement.clientHeight ? 
          document.documentElement.clientHeight : document.body.clientHeight);
    this.scrollStart = Position.deltaY;
    this.delta = (offsets[1] > max ? max : offsets[1]) - this.scrollStart;
  },
  update: function(position) {
    Position.prepare();
    window.scrollTo(Position.deltaX, 
      this.scrollStart + (position*this.delta));
  }
});

/* ------------- combination effects ------------- */

Effect.Fade = function(element) {
  var oldOpacity = Element.getInlineOpacity(element);
  var options = Object.extend({
  from: Element.getOpacity(element) || 1.0,
  to:   0.0,
  afterFinishInternal: function(effect) { with(Element) { 
    if(effect.options.to!=0) return;
    hide(effect.element);
    setStyle(effect.element, {opacity: oldOpacity}); }}
  }, arguments[1] || {});
  return new Effect.Opacity(element,options);
}

Effect.Appear = function(element) {
  var options = Object.extend({
  from: (Element.getStyle(element, 'display') == 'none' ? 0.0 : Element.getOpacity(element) || 0.0),
  to:   1.0,
  beforeSetup: function(effect) { with(Element) {
    setOpacity(effect.element, effect.options.from);
    show(effect.element); }}
  }, arguments[1] || {});
  return new Effect.Opacity(element,options);
}

Effect.Puff = function(element) {
  element = $(element);
  var oldStyle = { opacity: Element.getInlineOpacity(element), position: Element.getStyle(element, 'position') };
  return new Effect.Parallel(
   [ new Effect.Scale(element, 200, 
      { sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }), 
     new Effect.Opacity(element, { sync: true, to: 0.0 } ) ], 
     Object.extend({ duration: 1.0, 
      beforeSetupInternal: function(effect) { with(Element) {
        setStyle(effect.effects[0].element, {position: 'absolute'}); }},
      afterFinishInternal: function(effect) { with(Element) {
         hide(effect.effects[0].element);
         setStyle(effect.effects[0].element, oldStyle); }}
     }, arguments[1] || {})
   );
}

Effect.BlindUp = function(element) {
  element = $(element);
  Element.makeClipping(element);
  return new Effect.Scale(element, 0, 
    Object.extend({ scaleContent: false, 
      scaleX: false, 
      restoreAfterFinish: true,
      afterFinishInternal: function(effect) { with(Element) {
        [hide, undoClipping].call(effect.element); }} 
    }, arguments[1] || {})
  );
}

Effect.BlindDown = function(element) {
  element = $(element);
  var oldHeight = Element.getStyle(element, 'height');
  var elementDimensions = Element.getDimensions(element);
  return new Effect.Scale(element, 100, 
    Object.extend({ scaleContent: false, 
      scaleX: false,
      scaleFrom: 0,
      scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
      restoreAfterFinish: true,
      afterSetup: function(effect) { with(Element) {
        makeClipping(effect.element);
        setStyle(effect.element, {height: '0px'});
        show(effect.element); 
      }},  
      afterFinishInternal: function(effect) { with(Element) {
        undoClipping(effect.element);
        setStyle(effect.element, {height: oldHeight});
      }}
    }, arguments[1] || {})
  );
}

Effect.SwitchOff = function(element) {
  element = $(element);
  var oldOpacity = Element.getInlineOpacity(element);
  return new Effect.Appear(element, { 
    duration: 0.4,
    from: 0,
    transition: Effect.Transitions.flicker,
    afterFinishInternal: function(effect) {
      new Effect.Scale(effect.element, 1, { 
        duration: 0.3, scaleFromCenter: true,
        scaleX: false, scaleContent: false, restoreAfterFinish: true,
        beforeSetup: function(effect) { with(Element) {
          [makePositioned,makeClipping].call(effect.element);
        }},
        afterFinishInternal: function(effect) { with(Element) {
          [hide,undoClipping,undoPositioned].call(effect.element);
          setStyle(effect.element, {opacity: oldOpacity});
        }}
      })
    }
  });
}

Effect.DropOut = function(element) {
  element = $(element);
  var oldStyle = {
    top: Element.getStyle(element, 'top'),
    left: Element.getStyle(element, 'left'),
    opacity: Element.getInlineOpacity(element) };
  return new Effect.Parallel(
    [ new Effect.MoveBy(element, 100, 0, { sync: true }), 
      new Effect.Opacity(element, { sync: true, to: 0.0 }) ],
    Object.extend(
      { duration: 0.5,
        beforeSetup: function(effect) { with(Element) {
          makePositioned(effect.effects[0].element); }},
        afterFinishInternal: function(effect) { with(Element) {
          [hide, undoPositioned].call(effect.effects[0].element);
          setStyle(effect.effects[0].element, oldStyle); }} 
      }, arguments[1] || {}));
}

Effect.Shake = function(element) {
  element = $(element);
  var oldStyle = {
    top: Element.getStyle(element, 'top'),
    left: Element.getStyle(element, 'left') };
  return new Effect.MoveBy(element, 0, 20, 
    { duration: 0.05, afterFinishInternal: function(effect) {
  new Effect.MoveBy(effect.element, 0, -40, 
    { duration: 0.1, afterFinishInternal: function(effect) {
  new Effect.MoveBy(effect.element, 0, 40, 
    { duration: 0.1, afterFinishInternal: function(effect) {
  new Effect.MoveBy(effect.element, 0, -40, 
    { duration: 0.1, afterFinishInternal: function(effect) {
  new Effect.MoveBy(effect.element, 0, 40, 
    { duration: 0.1, afterFinishInternal: function(effect) {
  new Effect.MoveBy(effect.element, 0, -20, 
    { duration: 0.05, afterFinishInternal: function(effect) { with(Element) {
        undoPositioned(effect.element);
        setStyle(effect.element, oldStyle);
  }}}) }}) }}) }}) }}) }});
}

Effect.SlideDown = function(element) {
  element = $(element);
  Element.cleanWhitespace(element);
  // SlideDown need to have the content of the element wrapped in a container element with fixed height!
  var oldInnerBottom = Element.getStyle(element.firstChild, 'bottom');
  var elementDimensions = Element.getDimensions(element);
  return new Effect.Scale(element, 100, Object.extend({ 
    scaleContent: false, 
    scaleX: false, 
    scaleFrom: 0,
    scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
    restoreAfterFinish: true,
    afterSetup: function(effect) { with(Element) {
      makePositioned(effect.element);
      makePositioned(effect.element.firstChild);
      if(window.opera) setStyle(effect.element, {top: ''});
      makeClipping(effect.element);
      setStyle(effect.element, {height: '0px'});
      show(element); }},
    afterUpdateInternal: function(effect) { with(Element) {
      setStyle(effect.element.firstChild, {bottom:
        (effect.dims[0] - effect.element.clientHeight) + 'px' }); }},
    afterFinishInternal: function(effect) { with(Element) {
      undoClipping(effect.element); 
      undoPositioned(effect.element.firstChild);
      undoPositioned(effect.element);
      setStyle(effect.element.firstChild, {bottom: oldInnerBottom}); }}
    }, arguments[1] || {})
  );
}
  
Effect.SlideUp = function(element) {
  element = $(element);
  Element.cleanWhitespace(element);
  var oldInnerBottom = Element.getStyle(element.firstChild, 'bottom');
  return new Effect.Scale(element, 0, 
   Object.extend({ scaleContent: false, 
    scaleX: false, 
    scaleMode: 'box',
    scaleFrom: 100,
    restoreAfterFinish: true,
    beforeStartInternal: function(effect) { with(Element) {
      makePositioned(effect.element);
      makePositioned(effect.element.firstChild);
      if(window.opera) setStyle(effect.element, {top: ''});
      makeClipping(effect.element);
      show(element); }},  
    afterUpdateInternal: function(effect) { with(Element) {
      setStyle(effect.element.firstChild, {bottom:
        (effect.dims[0] - effect.element.clientHeight) + 'px' }); }},
    afterFinishInternal: function(effect) { with(Element) {
        [hide, undoClipping].call(effect.element); 
        undoPositioned(effect.element.firstChild);
        undoPositioned(effect.element);
        setStyle(effect.element.firstChild, {bottom: oldInnerBottom}); }}
   }, arguments[1] || {})
  );
}

// Bug in opera makes the TD containing this element expand for a instance after finish 
Effect.Squish = function(element) {
  return new Effect.Scale(element, window.opera ? 1 : 0, 
    { restoreAfterFinish: true,
      beforeSetup: function(effect) { with(Element) {
        makeClipping(effect.element); }},  
      afterFinishInternal: function(effect) { with(Element) {
        hide(effect.element); 
        undoClipping(effect.element); }}
  });
}

Effect.Grow = function(element) {
  element = $(element);
  var options = Object.extend({
    direction: 'center',
    moveTransistion: Effect.Transitions.sinoidal,
    scaleTransition: Effect.Transitions.sinoidal,
    opacityTransition: Effect.Transitions.full
  }, arguments[1] || {});
  var oldStyle = {
    top: element.style.top,
    left: element.style.left,
    height: element.style.height,
    width: element.style.width,
    opacity: Element.getInlineOpacity(element) };

  var dims = Element.getDimensions(element);    
  var initialMoveX, initialMoveY;
  var moveX, moveY;
  
  switch (options.direction) {
    case 'top-left':
      initialMoveX = initialMoveY = moveX = moveY = 0; 
      break;
    case 'top-right':
      initialMoveX = dims.width;
      initialMoveY = moveY = 0;
      moveX = -dims.width;
      break;
    case 'bottom-left':
      initialMoveX = moveX = 0;
      initialMoveY = dims.height;
      moveY = -dims.height;
      break;
    case 'bottom-right':
      initialMoveX = dims.width;
      initialMoveY = dims.height;
      moveX = -dims.width;
      moveY = -dims.height;
      break;
    case 'center':
      initialMoveX = dims.width / 2;
      initialMoveY = dims.height / 2;
      moveX = -dims.width / 2;
      moveY = -dims.height / 2;
      break;
  }
  
  return new Effect.MoveBy(element, initialMoveY, initialMoveX, { 
    duration: 0.01, 
    beforeSetup: function(effect) { with(Element) {
      hide(effect.element);
      makeClipping(effect.element);
      makePositioned(effect.element);
    }},
    afterFinishInternal: function(effect) {
      new Effect.Parallel(
        [ new Effect.Opacity(effect.element, { sync: true, to: 1.0, from: 0.0, transition: options.opacityTransition }),
          new Effect.MoveBy(effect.element, moveY, moveX, { sync: true, transition: options.moveTransition }),
          new Effect.Scale(effect.element, 100, {
            scaleMode: { originalHeight: dims.height, originalWidth: dims.width }, 
            sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true})
        ], Object.extend({
             beforeSetup: function(effect) { with(Element) {
               setStyle(effect.effects[0].element, {height: '0px'});
               show(effect.effects[0].element); }},
             afterFinishInternal: function(effect) { with(Element) {
               [undoClipping, undoPositioned].call(effect.effects[0].element); 
               setStyle(effect.effects[0].element, oldStyle); }}
           }, options)
      )
    }
  });
}

Effect.Shrink = function(element) {
  element = $(element);
  var options = Object.extend({
    direction: 'center',
    moveTransistion: Effect.Transitions.sinoidal,
    scaleTransition: Effect.Transitions.sinoidal,
    opacityTransition: Effect.Transitions.none
  }, arguments[1] || {});
  var oldStyle = {
    top: element.style.top,
    left: element.style.left,
    height: element.style.height,
    width: element.style.width,
    opacity: Element.getInlineOpacity(element) };

  var dims = Element.getDimensions(element);
  var moveX, moveY;
  
  switch (options.direction) {
    case 'top-left':
      moveX = moveY = 0;
      break;
    case 'top-right':
      moveX = dims.width;
      moveY = 0;
      break;
    case 'bottom-left':
      moveX = 0;
      moveY = dims.height;
      break;
    case 'bottom-right':
      moveX = dims.width;
      moveY = dims.height;
      break;
    case 'center':  
      moveX = dims.width / 2;
      moveY = dims.height / 2;
      break;
  }
  
  return new Effect.Parallel(
    [ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }),
      new Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}),
      new Effect.MoveBy(element, moveY, moveX, { sync: true, transition: options.moveTransition })
    ], Object.extend({            
         beforeStartInternal: function(effect) { with(Element) {
           [makePositioned, makeClipping].call(effect.effects[0].element) }},
         afterFinishInternal: function(effect) { with(Element) {
           [hide, undoClipping, undoPositioned].call(effect.effects[0].element);
           setStyle(effect.effects[0].element, oldStyle); }}
       }, options)
  );
}

Effect.Pulsate = function(element) {
  element = $(element);
  var options    = arguments[1] || {};
  var oldOpacity = Element.getInlineOpacity(element);
  var transition = options.transition || Effect.Transitions.sinoidal;
  var reverser   = function(pos){ return transition(1-Effect.Transitions.pulse(pos)) };
  reverser.bind(transition);
  return new Effect.Opacity(element, 
    Object.extend(Object.extend({  duration: 3.0, from: 0,
      afterFinishInternal: function(effect) { Element.setStyle(effect.element, {opacity: oldOpacity}); }
    }, options), {transition: reverser}));
}

Effect.Fold = function(element) {
  element = $(element);
  var oldStyle = {
    top: element.style.top,
    left: element.style.left,
    width: element.style.width,
    height: element.style.height };
  Element.makeClipping(element);
  return new Effect.Scale(element, 5, Object.extend({   
    scaleContent: false,
    scaleX: false,
    afterFinishInternal: function(effect) {
    new Effect.Scale(element, 1, { 
      scaleContent: false, 
      scaleY: false,
      afterFinishInternal: function(effect) { with(Element) {
        [hide, undoClipping].call(effect.element); 
        setStyle(effect.element, oldStyle);
      }} });
  }}, arguments[1] || {}));
}
//end /sites/scripts/effects.js
//start /sites/scripts/date-format.js

/*
 * Date Format 1.2.3
 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
 * MIT license
 *
 * Includes enhancements by Scott Trenda <scott.trenda.net>
 * and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */

var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date;
		if (isNaN(date)) throw SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'",
	shortDateTime:  "m/d/yyyy h:MM:ss TT"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};


//end /sites/scripts/date-format.js
//start /sites/infonotmercial/scripts/swfobject.js
/**
 * SWFObject v1.5: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
if(typeof deconcept=="undefined"){var deconcept=new Object();}if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a){if(!document.getElementById){return;}this.DETECT_KEY=_a?_a:"detectflash";this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);this.params=new Object();this.variables=new Object();this.attributes=new Array();if(_1){this.setAttribute("swf",_1);}if(id){this.setAttribute("id",id);}if(w){this.setAttribute("width",w);}if(h){this.setAttribute("height",h);}if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();if(!window.opera&&document.all&&this.installedVer.major>7){deconcept.SWFObject.doPrepUnload=true;}if(c){this.addParam("bgcolor",c);}var q=_7?_7:"high";this.addParam("quality",q);this.setAttribute("useExpressInstall",false);this.setAttribute("doExpressInstall",false);var _c=(_8)?_8:window.location;this.setAttribute("xiRedirectUrl",_c);this.setAttribute("redirectUrl","");if(_9){this.setAttribute("redirectUrl",_9);}};deconcept.SWFObject.prototype={useExpressInstall:function(_d){this.xiSWFPath=!_d?"expressinstall.swf":_d;this.setAttribute("useExpressInstall",true);},setAttribute:function(_e,_f){this.attributes[_e]=_f;},getAttribute:function(_10){return this.attributes[_10];},addParam:function(_11,_12){this.params[_11]=_12;},getParams:function(){return this.params;},addVariable:function(_13,_14){this.variables[_13]=_14;},getVariable:function(_15){return this.variables[_15];},getVariables:function(){return this.variables;},getVariablePairs:function(){var _16=new Array();var key;var _18=this.getVariables();for(key in _18){_16[_16.length]=key+"="+_18[key];}return _16;},getSWFHTML:function(){var _19="";if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");this.setAttribute("swf",this.xiSWFPath);}_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\"";_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";var _1a=this.getParams();for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}var _1c=this.getVariablePairs().join("&");if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");this.setAttribute("swf",this.xiSWFPath);}_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\">";_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";var _1d=this.getParams();for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}var _1f=this.getVariablePairs().join("&");if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}return _19;},write:function(_20){if(this.getAttribute("useExpressInstall")){var _21=new deconcept.PlayerVersion([6,0,65]);if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){this.setAttribute("doExpressInstall",true);this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));document.title=document.title.slice(0,47)+" - Flash Player Installation";this.addVariable("MMdoctitle",document.title);}}if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){var n=(typeof _20=="string")?document.getElementById(_20):_20;n.innerHTML=this.getSWFHTML();return true;}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}return false;}};deconcept.SWFObjectUtil.getPlayerVersion=function(){var _23=new deconcept.PlayerVersion([0,0,0]);if(navigator.plugins&&navigator.mimeTypes.length){var x=navigator.plugins["Shockwave Flash"];if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}}else{if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;var _26=3;while(axo){try{_26++;axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+_26);_23=new deconcept.PlayerVersion([_26,0,0]);}catch(e){axo=null;}}}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}}return _23;};deconcept.PlayerVersion=function(_29){this.major=_29[0]!=null?parseInt(_29[0]):0;this.minor=_29[1]!=null?parseInt(_29[1]):0;this.rev=_29[2]!=null?parseInt(_29[2]):0;};deconcept.PlayerVersion.prototype.versionIsValid=function(fv){if(this.major<fv.major){return false;}if(this.major>fv.major){return true;}if(this.minor<fv.minor){return false;}if(this.minor>fv.minor){return true;}if(this.rev<fv.rev){return false;}return true;};deconcept.util={getRequestParameter:function(_2b){var q=document.location.search||document.location.hash;if(_2b==null){return q;}if(q){var _2d=q.substring(1).split("&");for(var i=0;i<_2d.length;i++){if(_2d[i].substring(0,_2d[i].indexOf("="))==_2b){return _2d[i].substring((_2d[i].indexOf("=")+1));}}}return "";}};deconcept.SWFObjectUtil.cleanupSWFs=function(){var _2f=document.getElementsByTagName("OBJECT");for(var i=_2f.length-1;i>=0;i--){_2f[i].style.display="none";for(var x in _2f[i]){if(typeof _2f[i][x]=="function"){_2f[i][x]=function(){};}}}};if(deconcept.SWFObject.doPrepUnload){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);};window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);deconcept.unloadSet=true;}}if(!document.getElementById&&document.all){document.getElementById=function(id){return document.all[id];};}var getQueryParamValue=deconcept.util.getRequestParameter;var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject;
//end /sites/infonotmercial/scripts/swfobject.js
//start /sites/infonotmercial/scripts/slide_show.js
function make_hover(elmnt) {
	elmnt.className='red_border';
	}
	
function remove_hover(elmnt) {
	elmnt.className='';
	}	
	
	
function star_active (elmnt, item_no){
	if(item_no==1){
		elmnt.className='active';
		document.getElementById('star2').className = '';
		document.getElementById('star3').className = '';
		document.getElementById('star4').className = '';
		document.getElementById('star5').className = '';
	}
	else if(item_no==2){
		document.getElementById('star1').className = 'active';
		elmnt.className='active';
		document.getElementById('star3').className = '';
		document.getElementById('star4').className = '';
		document.getElementById('star5').className = '';
	}
	else if(item_no == 3){
		document.getElementById('star1').className = 'active';
		document.getElementById('star2').className = 'active';
		elmnt.className='active';
		document.getElementById('star4').className = '';
		document.getElementById('star5').className = '';
	}
	else if(item_no == 4){
		document.getElementById('star1').className = 'active';
		document.getElementById('star2').className = 'active';
		document.getElementById('star3').className = 'active';
		elmnt.className='active';
		document.getElementById('star5').className = '';
	}
	else{
		document.getElementById('star1').className = 'active';
		document.getElementById('star2').className = 'active';
		document.getElementById('star3').className = 'active';
		document.getElementById('star4').className = 'active';
		elmnt.className='active';
	}	
}

function checkthis(elmnt, choice){
	if(choice == 'yes'){
		document.getElementById('no').className = 'no';
		elmnt.className = 'yes active'
	}
	else{
		document.getElementById('yes').className = 'yes';
		elmnt.className = 'no active'
	}
}

function btn_hover(elmnt) {
	elmnt.className+=' btn_hover';
	}
	
function btn_h_remove(elmnt) {
	var newclasname = elmnt.className.replace(' btn_hover', '');
	elmnt.className = newclasname;
}	

function getObject(obj) { 
	var theObj; 
	if(document.all) { 
		if(typeof obj=="string") { 
			return document.all(obj); 
		}
		else { 
			return obj.style; 
		} 
	} 
	if(document.getElementById) { 
		if(typeof obj=="string") {
			return document.getElementById(obj); 
		}
		else { 
			return obj.style; 
		} 
	} 
	return null; 
} 

//Contador de caracteres. 
function Contar(entrada,salida,texto,caracteres) { 
var entradaObj=getObject(entrada); 
var salidaObj=getObject(salida); 
var longitud=caracteres - entradaObj.value.length;

if(longitud <= 0) { 
longitud=0; 
texto='<span class="disable">'+texto+'</span>'; 
entradaObj.value=entradaObj.value.substr(0,caracteres); 
} 
salidaObj.innerHTML = texto.replace("{CHAR}",entradaObj.value.length); 
}

//end /sites/infonotmercial/scripts/slide_show.js
//start /sites/scripts/wall.js
/* document must also have the wz_tooltip and json javascript script in it */

function WallVote(logged_in, sku, pid, pos, type, wurl)
{
    if(!logged_in)
    {
        Tip('Hey, <u><a href="/controller.aspx?type=view&info=WallLogin&wtype=product&url='+wurl+'&sku='+sku+'&pid='+pid+'&a=vote&pos='+pos+'&ptype='+type+'">login</a></u> to vote!', CLICKCLOSE, true, STICKY, true, FADEOUT, 200);
        pageTracker._trackEvent('Wall', 'attemptedVoteOn'+type, sku);
    }
    else
    {
        var url = 'process.aspx';
        var params = 'type=wallRating&url='+wurl+'&sku='+sku+'&pid='+pid+'&pos='+pos+'&post_type='+type;
        
        waitcursor();
        var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: wallVoteResult });
    }
}

function wallVoteResult(result){
    clearcursor();
    var response = result.responseText.parseJSON();
    if(response.success == "true")
    {
        window.location = "/" + response.url + "?success=true&pid="+response.pid+"&ptype="+response.type+"&a=vote#"+response.type+"_"+response.pid; 
    }
    else
    {
        $(response.type+"VoteResponse_"+response.pid).style.display = "inline";
        $(response.type+"VoteResponse_"+response.pid).innerHTML = response.error;   
    }        
}
function DeleteWallPost(pid)
{
    var url = 'process.aspx';
    var params = 'type=deleteWallPost&pid='+pid;

    waitcursor();
    var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: deletePostResult });
}

function deletePostResult(result){
    clearcursor();
    var response = result.responseText.parseJSON();
    if(response.success == "true")
    {
        $$("#postDiv_"+response.pid).each(function(s) { s.className = "deletedPost"; });
        $$("#postDiv_"+response.pid).each(function(s) { s.innerHTML = "Your post has been deleted."; });
    }
    else
    {
         $("postDiv_"+response.pid).innerHTML = "<span class='error'>You do not have permission to delete this post.</span>" + $("postDiv_"+response.pid).innerHTML;
    }        
}
function FollowWallPost(pid)
{
    var url = 'process.aspx';
    var params = 'type=followpost&pid='+pid;

    waitcursor();
    var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: followWallPostResult });
}

function followWallPostResult(result){
    clearcursor();
    var response = result.responseText.parseJSON();
    if(response.success == "true")
    {
        $("postNotification_"+response.pid).innerHTML="You got it!  You are now subscribed to this post.";
    }
    else
    {
         $("postNotification_"+response.pid).innerHTML = "<span class='error'>Unable to set up email notification at this time.</span>";
    }        
}
function DeleteWallComment(pid)
{
    var url = 'process.aspx';
    var params = 'type=deleteWallComment&pid='+pid;

    waitcursor();
    var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: deleteCommentResult });
}

function deleteCommentResult(result){
    clearcursor();
    var response = result.responseText.parseJSON();
    if(response.success == "true")
    {
        $("commentDiv_"+response.pid).className = "deletedComment";
        $("commentDiv_"+response.pid).innerHTML="Your post has been deleted.";
    }
    else
    {
         $("commentDiv_"+response.pid).innerHTML = "<span class='error'>You do not have permission to delete this post.</span>" + $("postDiv_"+response.pid).innerHTML;
    }         
}
function updateWallProfile(bio, location)
{
    var url = 'process.aspx';
    var params = 'type=updatewallprofile&bio='+bio+'&location='+location;

    waitcursor();
    var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: updateWallProfileResult });
}

function updateWallProfileResult(result){
    clearcursor();
    var response = result.responseText.parseJSON();
    if(response.success == "true")
    {
        tt_HideInit();
        $("bio").innerHTML = bio_text;
        $("location").innerHTML = location_text;
    }
    else
    {
        $("profileError").innerHTML = "There has been an error with your submission. Please make sure you are still logged in and try again.";
         //$("postDiv_"+response.pid).innerHTML = "<span class='error'>You do not have permission to delete this post.</span>" + $("postDiv_"+response.pid).innerHTML;
    }        
}
//used for submitting wall reviews that do not have pros, cons or recommended... calls the updated wallreview with "" for pros, cons, recommended
function WallReview(logged_in, sku, title, text, stars, wtype, wurl)
{
    WallReviewFull(logged_in, sku, title, "", "", text, "", stars, wtype, wurl);
}
function WallReviewFull(logged_in, sku, title, pros, cons, text, recommended, stars, wtype, wurl)
{
    if(!logged_in)
    {
        Tip('Hey, <u><a href="/controller.aspx?type=view&info=WallLogin&sku='+sku+'&a=review&wtype='+wtype+'&url='+escape(wurl)+'">login</a></u> to review', CLICKCLOSE, true, STICKY, true, FADEOUT, 200);
    }
    else
    {
        if(stars==0) {$('reviewMsg').innerHTML = "Please choose a star rating."; return; }
        if(text=="") {$('reviewMsg').innerHTML = "Please enter your review."; return; }
        
        var url = 'process.aspx';
        var params = 'type=wallreview&title='+escape(title)+'&text='+escape(text)+'&stars='+stars+'&sku='+sku+'&wtype='+wtype+'&url='+escape(wurl)+'&pros='+pros+'&cons='+cons+'&recommended='+recommended;

        waitcursor();
        var myAjax = new Ajax.Request( url, { method: 'post', parameters: params, onComplete: wallReviewResult });
    }
}

function wallReviewResult(result){
    clearcursor();
    var response = result.responseText.parseJSON();
    if(response.success == "true")
    {
        var url = window.location.href;
        window.location = "/" + response.url + "?success=true&pid="+response.pid+"&ptype=post&a=submit#post_"+response.pid;
        //if(url.indexOf("type=view") == -1){ window.location = url.substring(0, url.indexOf("?")) + "?success=true&pid="+response.pid+"&a=submit#post_"+response.pid; }
        //else{ window.location = url + "&success=true&pid="+response.pid+"&a=submit&#post_"+response.pid; }
    }
    else
    { 
        $('reviewMsg').innerHTML = response.error;   
    }        
}
function WallVideo(logged_in, sku, title, text, video_url, wtype, wurl)
{
    if(!logged_in)
    {
        Tip('Hey, <u><a href="/controller.aspx?type=view&info=WallLogin&sku='+sku+'&a=video&wtype='+wtype+'&url='+escape(wurl)+'">login</a></u> to upload', CLICKCLOSE, true, STICKY, true, FADEOUT, 200);
    }
    else
    {
        if(video_url=="") {$('videoMsg').innerHTML = "Please enter a video URL."; return; }
        if(title=="") {$('videoMsg').innerHTML = "Please enter a title for your video."; return; }
        
        var url = 'process.aspx';
        var params = 'type=wallvideo&title='+escape(title)+'&text='+escape(text)+'&video_url='+escape(video_url)+'&sku='+sku+'&wtype='+wtype+'&url='+escape(wurl);

        waitcursor();
        var myAjax = new Ajax.Request( url, { method: 'post', parameters: params, onComplete: wallVideoResult });
    }
}

function wallVideoResult(result){
    clearcursor();
    var response = result.responseText.parseJSON();
    if(response.success == "true")
    {
        var url = window.location.href;
        window.location = "/" + response.url + "?success=true&pid="+response.pid+"&ptype=post&a=submit#post_"+response.pid;
        //if(url.indexOf("type=view") == -1){ window.location = url.substring(0, url.indexOf("?")) + "?success=true&pid="+response.pid+"&a=submit#post_"+response.pid; }
        //else{ window.location = url + "&success=true&pid="+response.pid+"&a=submit&#post_"+response.pid; }
    }
    else
    { 
        $('videoMsg').innerHTML = response.error;   
    }        
}
function WallQuestion(logged_in, sku, title, text, wtype, wurl)
{
    if(!logged_in)
    {
        Tip('Hey, <u><a href="/controller.aspx?type=view&info=WallLogin&sku='+sku+'&a=question&wtype='+wtype+'&url='+escape(wurl)+'">login</a></u> to ask your question', CLICKCLOSE, true, STICKY, true, FADEOUT, 200);
    }
    else
    {
        if(text=="") {$('reviewMsg').innerHTML = "Please enter your question."; return; }
        
        var url = 'process.aspx';
        var params = 'type=wallquestion&title='+escape(title)+'&text='+escape(text)+'&sku='+sku+'&wtype='+wtype+'&url='+escape(wurl);

        waitcursor();
        var myAjax = new Ajax.Request( url, { method: 'post', parameters: params, onComplete: wallQuestionResult });
    }
}

function wallQuestionResult(result){
    clearcursor();
    var response = result.responseText.parseJSON();
    if(response.success == "true")
    {
        var url = window.location.href;
        window.location = "/" + response.url + "?success=true&pid="+response.pid+"&ptype=post&a=submit#post_"+response.pid;
    }
    else
    {
        $('questionMsg').innerHTML = response.error; 
    }        
}
//DEPRECATED - calls the appropriate function with "product" wall_type selected as default
function WallComment(logged_in, sku, pid, text, wurl) 
{
    WallCommentFull(logged_in, sku, pid, text, 'product', wurl);
}
function WallCommentFull(logged_in, sku, pid, text, wtype, wurl)
{
    if(!logged_in)
    {
        Tip('Hey, <u><a href="/controller.aspx?type=view&info=WallLogin&wtype='+wtype+'&url='+wurl+'&sku='+sku+'&a=review">login</a></u> to respond', CLICKCLOSE, true, STICKY, true,  FADEOUT, 200);
    }
    else
    {
        if(text=="") {$('commentMsg').innerHTML = "Please enter your text here."; return; }
        
        var url = 'process.aspx';
        var params = 'type=wallcomment&pid='+pid+'&text='+escape(text)+'&sku='+sku+'&url='+wurl;

        waitcursor();
        var myAjax = new Ajax.Request( url, { method: 'post', parameters: params, onComplete: wallCommentResult });
    }
}

function wallCommentResult(result){
    clearcursor();
    var response = result.responseText.parseJSON();
    if(response.success == "true")
    {
        var url = window.location.href;
        window.location = "/" + response.url + "?success=true&pid="+response.cid+"&a=submit&ptype=comment#comment_"+response.cid;
        //if(url.indexOf("type=view") == -1){ window.location = url.substring(0, url.indexOf("?")) + "?success=true&pid="+response.pid+"&a=submit#post_"+response.pid; }
        //else{ window.location = url + "&success=true&pid="+response.pid+"&a=submit&#post_"+response.pid; }
    }
    else
    {
        $("commentMsg_"+response.pid).innerHTML = response.error;
    }        
}

function WallFlag(logged_in, sku, pid, text, type)
{
    if(!logged_in)
    {
        Tip('Hey, <u><a href="/controller.aspx?type=view&info=WallLogin&ptype='+type+'&sku='+sku+'&a=flag&pid='+pid+'">login</a></u> to flag', CLICKCLOSE, true, STICKY, true,  FADEOUT, 200);
    }
    else
    {        
        var url = 'process.aspx';
        var params = 'type=wallflag&sku='+sku+'&pid='+pid+'&text='+escape(text)+"&ptype="+type;

        waitcursor();
        var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: wallFlagResult });
    }
}

function wallFlagResult(result){
    clearcursor();
    var response = result.responseText.parseJSON();
    if(response.success == "true")
    {
        var url = window.location.href;
        window.location = "/" + response.sku + ".html?success=true&pid="+response.pid+"&a=flag&ptype=" + response.type + "#" + response.type + "_"+response.pid;
    }
    else
    {
        //what to do on error
    }        
}

function RemoveWallFlag(logged_in, sku, pid, type)
{
    if(!logged_in)
    {
        Tip('Hey, <u><a href="/controller.aspx?type=view&info=WallLogin&ptype='+type+'&sku='+sku+'&a=flag&pid='+pid+'">login</a></u> to remove this flag', CLICKCLOSE, true, STICKY, true,  FADEOUT, 200);
    }
    else
    {        
        var url = 'process.aspx';
        var params = 'type=wallremoveflag&pid='+pid+"&ptype="+type+"&sku="+sku;

        waitcursor();
        var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: wallRemoveFlagResult });
    }
}

function wallRemoveFlagResult(result){
    clearcursor();
    var response = result.responseText.parseJSON();
    if(response.success == "true")
    {
        var url = window.location.href;
        window.location = "/" + response.sku + ".html?success=true&pid="+response.pid+"&a=unflag&ptype="+response.type+"#"+response.type+"_"+response.pid;
    }
    else
    {
        //what to do on error
    }        
}

function ViewFlagged(type, id)
{
    $$("#"+type+"_"+id).each(function(s) { s.style.display='block'; });
    $$("#"+type+'_flag_'+id).each(function(s) { s.style.display='none'; });
}

function OpenFlagForm(logged_in, sku, id, type)
{
    if(!logged_in)
    {
        Tip('Hey, <u><a href="/controller.aspx?type=view&info=WallLogin&ptype='+type+'&sku='+sku+'&a=flag&pid='+id+'">login</a></u> to flag', CLICKCLOSE, true, STICKY, true,  FADEOUT, 200);
    }
    else
    {   
        if($(type+"flagopen_"+id).style.display == 'none') { $(type+"flagopen_"+id).style.display = "block"; }
        else { $(type+"flagopen_"+id).style.display = "none"; }
    }
}

function ShowTooltip(id,text)
{
    Tip(text);
}

function openWallForm(obj, type)
{
    $(type+'InitialInput').style.display="none";
    $(type+'Form').style.display='block';
    if($(type+'FormTitle') != null) { $(type+'FormTitle').focus(); }
    if(isDefined("uploadType")) { uploadType = type; }
}

function closeWallForm(type)
{
    $(type+'Form').style.display='none';
    $(type+'InitialInput').style.display="block";
}
function CloseFlagForm(type, id)
{
    $(type+'flagopen_'+id).style.display='none';
}

function openCommentForm(id)
{
    $('commentInitial_'+id).style.display="none";
    $('commentForm_'+id).style.display='block';
    $('commentText_'+id).focus();
}

function closeCommentForm(id)
{
    $('commentInitial_'+id).style.display="block";
    $('commentForm_'+id).style.display='none';
}

function OpenEditForm(id, type)
{
    $('edit'+type.toTitleCase()+'_'+id).style.display = "block";
}

function CloseEditForm(id, type)
{
    $('edit'+type.toTitleCase()+'_'+id).style.display = "none";
}

function SubmitReviewEdit(sku, id, stars, title, text, wurl)
{
    if(stars==0) {$('reviewEditMsg').innerHTML = "Please choose a star rating."; return; }
    if(text=="") {$('reviewEditMsg').innerHTML = "Please enter your review."; return; }
    
    var url = 'process.aspx';
    var params = 'type=editwallreview&url='+wurl+'&title='+escape(title)+'&text='+escape(text)+'&stars='+stars+'&sku='+sku+'&id='+id;

    waitcursor();
    var myAjax = new Ajax.Request( url, { method: 'post', parameters: params, onComplete: wallReviewEditResult });
}

function wallReviewEditResult(result){
    clearcursor();
    var response = result.responseText.parseJSON();
    if(response.success == "true")
    {
        var url = window.location.href;
        window.location = "/" + response.url + "?success=true&pid="+response.pid+"&ptype=post&a=edit#post_"+response.pid;
        //if(url.indexOf("type=view") == -1){ window.location = url.substring(0, url.indexOf("?")) + "?success=true&pid="+response.pid+"&a=submit#post_"+response.pid; }
        //else{ window.location = url + "&success=true&pid="+response.pid+"&a=submit&#post_"+response.pid; }
    }
    else
    { 
        $('reviewMsg').innerHTML = response.error;   
    }        
}
function SubmitQuestionEdit(sku, id, title, text, wurl)
{
    if(text=="") {$('questionEditMsg_'+id).innerHTML = "Please enter your text."; return; }
    
    var url = 'process.aspx';
    var params = 'type=editwallquestion&title='+escape(title)+'&text='+escape(text)+'&sku='+sku+'&id='+id+"&url="+wurl;

    waitcursor();
    var myAjax = new Ajax.Request( url, { method: 'post', parameters: params, onComplete: wallQuestionEditResult });
}

function wallQuestionEditResult(result){
    clearcursor();
    var response = result.responseText.parseJSON();
    if(response.success == "true")
    {
        var url = window.location.href;
        window.location = "/" + response.url + "?success=true&pid="+response.pid+"&ptype=post&a=edit#post_"+response.pid;
        //if(url.indexOf("type=view") == -1){ window.location = url.substring(0, url.indexOf("?")) + "?success=true&pid="+response.pid+"&a=submit#post_"+response.pid; }
        //else{ window.location = url + "&success=true&pid="+response.pid+"&a=submit&#post_"+response.pid; }
    }
    else
    { 
        $('questionMsg').innerHTML = response.error;   
    }        
}
function SubmitCommentEdit(sku, id, text, wurl)
{
    if(text=="") {$('editcommentMsg').innerHTML = "Please enter your comment."; return; }
    
    var url = 'process.aspx';
    var params = 'type=editwallcomment&text='+escape(text)+'&sku='+sku+'&id='+id+'&url='+wurl;

    waitcursor();
    var myAjax = new Ajax.Request( url, { method: 'post', parameters: params, onComplete: wallCommentEditResult });
}

function wallCommentEditResult(result){
    clearcursor();
    var response = result.responseText.parseJSON();
    if(response.success == "true")
    {
        var url = window.location.href;
        window.location = "/" + response.url + "?success=true&pid="+response.cid+"&ptype=comment&a=edit#comment_"+response.cid;
        //if(url.indexOf("type=view") == -1){ window.location = url.substring(0, url.indexOf("?")) + "?success=true&pid="+response.pid+"&a=submit#post_"+response.pid; }
        //else{ window.location = url + "&success=true&pid="+response.pid+"&a=submit&#post_"+response.pid; }
    }
    else
    { 
        $('editcommentMsg+'+response.pid).innerHTML = response.error;   
    }        
}
function toggleComments(id)
{
    if($("comments_"+id).style.display == "none")
    {
        $("comments_"+id).style.display = "block";
        $("hideCommentsIcon_"+id).src = $("hideCommentsIcon_"+id).src.replace("view", "hide");
    }
    else
    {
        $("comments_"+id).style.display = "none";
        $("hideCommentsIcon_"+id).src = $("hideCommentsIcon_"+id).src.replace("hide", "view");
    }
}

function SetRating(rating)
{
    stars = rating;
    rating_width = rating * 25;
	$('current-rating').style.width = rating_width+'px';
	SetRatingText(rating);
	return stars;
} 

function SetRatingText(n)
{
    switch(n)
    {
        case 0:
            $('ratingText').innerHTML=''; 
        break;
        case 1:
            $('ratingText').innerHTML='Just awful.';
        break;
        case 2:
            $('ratingText').innerHTML='Can\'t Recommend';
        break;
        case 3:
            $('ratingText').innerHTML='It\'s ok.';
        break;
        case 4:
            $('ratingText').innerHTML='Pretty good.';
        break;
        case 5:
            $('ratingText').innerHTML='Awesome!';
        break;
    }
}

function SetEditRating(type, id, rating)
{
    eval("stars"+id+" = rating;");
    rating_width = rating * 25;
	$('current-rating-'+id).style.width = rating_width+'px';
	SetEditRatingText(id, rating);
	return rating;
} 

function SetEditRatingText(type, id, n)
{
    switch(n)
    {
        case 0:
            $(type+'starstext_'+id).innerHTML=''; 
        break;
        case 1:
            $(type+'starstext_'+id).innerHTML='Just awful.';
        break;
        case 2:
            $(type+'starstext_'+id).innerHTML='Can\'t Recommend';
        break;
        case 3:
            $(type+'starstext_'+id).innerHTML='It\'s ok.';
        break;
        case 4:
            $(type+'starstext_'+id).innerHTML='Pretty good.';
        break;
        case 5:
            $(type+'starstext_'+id).innerHTML='Awesome!';
        break;
    }
}

function RemoveRatingText()
{
    SetRatingText(stars);
}

function RemoveEditRatingText(type, id)
{
    SetEditRatingText(type, id, eval('stars' + id));
}

function OpenBioEdit()
{
    TagToTip('bioEdit', CLOSEBTN, true, STICKY, true, WIDTH, 400, DELAY, 0);
    $('WzBoDy').getElementsBySelector('[id="bioTxt"]').each(function(s){s.value=bio_text;});
    $('WzBoDy').getElementsBySelector('[id="locationTxt"]').each(function(s){s.value=location_text;});
}
function OpenInitialBioEdit()
{
    TagToTip('bioEdit', CLOSEBTN, true, STICKY, true, WIDTH, 400, DELAY, 0, FIX, ['location', -8, -160]);
    //$('WzBoDy').getElementsBySelector('[id="bioTxt"]').each(function(s){s.value="What drives you? What's your level of training? How did you get started? Let everyone know a little about yourself.";s.onFocus="this.value='';";});
    //$('WzBoDy').getElementsBySelector('[id="locationTxt"]').each(function(s){s.value="Tell the other community members where you practice.";s.onFocus="this.value='';";});
}

function OpenTagEdit()
{
    TagToTip('tagEdit', CLOSEBTN, true, STICKY, true, WIDTH, 400, DELAY, 0);
    
    $A($('WzBoDy').getElementsByClassName("selectedWallTag")).each(function(s){s.className="";});
    var tags_array = tags_text.split(" // ");
    for(t=0; t<tags_array.length; t++)
    {
        $('WzBoDy').getElementsBySelector('[id="tags'+tags_array[t].split(' ').join('')+'"]').each(function(s){s.className="selectedWallTag";});
    }
}

function addTags(tag, link)
{
    if(tags_text.indexOf(tag) > -1)
    {
        tags_text = tags_text.replace("// " + tag, "");
        tags_text = tags_text.replace(tag, "");
        link.className = "";
    }
    else
    {
        if(tags_text!="") { tags_text = tags_text + " // "; }
        tags_text = tags_text + tag;
        link.className = "selectedWallTag";
    }
    
    var url = 'process.aspx';
    var params = 'type=updatewalltags&tags='+tags_text;

    waitcursor();
    var myAjax = new Ajax.Request( url, { method: 'post', parameters: params, onComplete: addTagsResult });  
}

function addTagsResult(result){
    clearcursor();
    var response = result.responseText.parseJSON();
    if(response.success == "true")
    {
        $("wallTags").innerHTML = tags_text; 
//        tt_HideInit();        
    }
    else
    {
        //what to do on error
    }        

}

function ShowPostType(imagePath,type)
{
    $("all_tab").className= "dark";
    if($("review_tab") != null) { $("review_tab").className= "dark"; }
    $("question_tab").className= "dark";
    $("image_tab").className= "dark";
    
    $(type+"_tab").className= "light";
    

    document.getElementsByClassName("userRemark").each(function(s) { s.style.display="table"; });
    document.getElementsByClassName("userActions").each(function(s) { s.style.display="table"; });

    if(type != "review" && type != "all")
    {
         document.getElementsByClassName("reviewDiv").each(function(s) { s.style.display="none"; }); 
         if($("writeReview") != null)
         {
            $("writeReview").style.display = "none";
         }
    }
    if(type != "question" && type != "all")
    { 
        document.getElementsByClassName("questionDiv").each(function(s) { s.style.display="none"; }); 
         if($("writeQuestion") != null)
         {
            $("writeQuestion").style.display = "none";
         }         
    }
    if(type!= "image" && type!= "all")
    {
        document.getElementsByClassName("imageDiv").each(function(s) { s.style.display="none"; }); 
        document.getElementsByClassName("videoDiv").each(function(s) { s.style.display="none"; }); 
         if($("uploadImageVideo") != null)
         {
            $("uploadImageVideo").style.display = "none";
         }           
    }
    
    pageTracker._trackEvent('Wall', 'changedTab', type);
 }

//calls process.aspx to login the facebook user 
// returns "error" or the user object
//YH 5/10
function LoginFacebookUser(accessToken,userId,returnFunction)
{
        var url = 'process.aspx';
        var params = 'type=fblogin&token=' + accessToken + '&uid=' + userId;       ;
        var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: 
            function(result)
            {
                returnFunction(result.responseText);
            }
        
        });

}

//calls process.aspx to login the site user
// returns "error" or the user object
//YH 5/25/10
function LoginSiteUser(email,password,rememberMe,returnFunction)
{
        var url = 'process.aspx';
        var params = 'type=login_siteuser&email=' + email + '&password=' + password + '&remember_me=' + rememberMe;       
        waitcursor();
        var myAjax = new Ajax.Request( url, { method: 'post', parameters: params, onComplete: 
            function(result)
            {               
                returnFunction(result.responseText);
            }        
        });
}

//calls process.aspx to login the wall user 
// returns "error" or the display name of the user
//YH 5/25/10
function CreateWallUser(displayName,email,password,rememberMe,returnFunction)
{
        var url = 'process.aspx';
        var params = 'type=create_walluser&display_name=' + displayName + '&email=' + email + '&password=' + password + '&remember_me=' + rememberMe;       
        waitcursor();
        var myAjax = new Ajax.Request( url, { method: 'post', parameters: params, onComplete: 
            function(result)
            {               
                returnFunction(result.responseText);
            }        
        });
}


//YH 5/10
function CreateWallReview(text,pros,cons,stars,recommended,owns,sku,wtype,wurl,returnFunction)
{
    var url = 'process.aspx';
    var params = 'type=wallreview&title=&text='+escape(text)+'&stars='+stars+'&sku='+sku+'&wtype='+wtype+'&url='+wurl+'&pros='+escape(pros)+'&cons='+escape(cons)+'&recommended='+recommended+'&owns='+owns+'&allow_anon=true';
    clearcursor();
    var myAjax = new Ajax.Request( url, { method: 'post', parameters: params, onComplete: 
            function(result)
            {
                returnFunction(result.responseText);
            }
        
        });
}

//YH 5/25/10
function CreateWallQuestion(title,text,owns,sku,wtype,wurl,returnFunction)
{
    var url = 'process.aspx';
    var params = 'type=wallquestion&title='+escape(title)+'&text='+escape(text)+'&sku='+sku+'&wtype='+wtype+'&url='+wurl+'&owns='+owns+'&allow_anon=true';
    clearcursor();
    var myAjax = new Ajax.Request( url, { method: 'post', parameters: params, onComplete: 
            function(result)
            {
                returnFunction(result.responseText);
            }
        
        });
}

//this function creates a post of type comment, not to be confused with a wall_comment
//YH 5/25/10
function CreateWallCommentPost(text,owns,sku,wtype,wurl,returnFunction)
{
    var url = 'process.aspx';
    var params = 'type=wallcommentpost&text='+escape(text)+'&sku='+sku+'&wtype='+wtype+'&url='+wurl+'&owns='+owns+'&allow_anon=true';
    clearcursor();
    var myAjax = new Ajax.Request( url, { method: 'post', parameters: params, onComplete: 
            function(result)
            {
                returnFunction(result.responseText);
            }
        
        });
}

//this function creates a post of type video
//RT 7/1/2010
function CreateWallVideo(title,text,video_url,owns,sku,wtype,wurl,returnFunction)
{
    var url = 'process.aspx';
        var params = 'type=wallvideo&title='+escape(title)+'&text='+escape(text)+'&video_url='+escape(video_url)+'&sku='+sku+'&wtype='+wtype+'&url='+escape(wurl);
        clearcursor();
        var myAjax = new Ajax.Request( url, { method: 'post', parameters: params, onComplete: 
            function(result)
            {
                returnFunction(result.responseText);
            }
        
        });
}

//this function creates a post of type video
//RT 7/1/2010
function CreateWallImage(title,text,img_path,owns,sku,wtype,wurl,returnFunction)
{
    var url = 'process.aspx';
        var params = 'type=wallimage&title='+escape(title)+'&text='+escape(text)+'&img_path='+escape(img_path)+'&sku='+sku+'&wtype='+wtype+'&url='+escape(wurl);
        clearcursor();
        var myAjax = new Ajax.Request( url, { method: 'post', parameters: params, onComplete: 
            function(result)
            {
                returnFunction(result.responseText);
            }
        
        });
}

//this function creates a wall_comment
//YH 5/26/10
function CreateWallComment(text,pid,owns,sku,wtype,wurl,returnFunction)
{
    var url = 'process.aspx';
    var params = 'type=wallcomment&pid=' + pid + '&text='+escape(text)+'&sku='+sku+'&wtype='+wtype+'&url='+wurl+'&owns='+owns+'&allow_anon=true';
    clearcursor();
    var myAjax = new Ajax.Request( url, { method: 'post', parameters: params, onComplete: 
            function(result)
            {
                returnFunction(result.responseText);
            }
        
        });
}


function openWallLogin(id,div,title)
{
    loginCallerId = id;
    ajaxwin=dhtmlwindow.open("ajaxbox", "div", div, title, "width=415px,height=250px,left=350px,top=100px,resize=1,scrolling=0")
    ajaxwin.isResize(false);
}

function SetEditRecommended(id,yesorno)
{
    //this function does not use the "checkthis" because checkthis does not take a parameter for the type
    if(yesorno == 'yes'){
        document.getElementById(id + 'No').className = 'no';
        $(id + 'Yes').className = 'yes active'
    }
    else{
        document.getElementById(id + 'Yes').className = 'yes';
        $(id + 'No').className = 'no active'
    }
    eval(id + 'Recommended' + '="' + yesorno + '"');
}

//switches the panel (comment, review or question) shown in the stand alone post section
// YH 5/12/10   
function ShowStandAlonePostPanel(panel)
{
    if(panel == "standAloneCommentPanel")
    {
        $("standAloneCommentPanel").show();
        $("standAloneQuestionPanel").hide();
        $("standAloneReviewPanel").hide();
        if($("standAloneUploadPanel") != null) {$("standAloneUploadPanel").hide(); };
        postType = "commentPost";
    }
    else if(panel == "standAloneReviewPanel")
    {
        //if showing the question panel, put any non default text entered in the comment panel in the bottom line text panel YH 6/4/10
        var commentTextInput = $("standAloneComment");        
        if(commentTextInput.value != commentTextInput.attributes["defaultText"].value && commentTextInput.value != "")
        {
            $("standAloneBottomLine").value = commentTextInput.value;
        }        
    
        $("standAloneCommentPanel").hide();
        $("standAloneQuestionPanel").hide();
        $("standAloneReviewPanel").show();
        if($("standAloneUploadPanel") != null) {$("standAloneUploadPanel").hide(); };
        postType = "review";
    }
    else if(panel == "standAloneQuestionPanel")
    {
        //if showing the question panel, put any non default text entered in the comment panel in the question text panel YH 6/4/10
        var commentTextInput = $("standAloneComment");        
        if(commentTextInput.value != commentTextInput.attributes["defaultText"].value && commentTextInput.value != "")
        {
            $("standAloneQuestionText").value = commentTextInput.value;
        }
        $("standAloneCommentPanel").hide();
        $("standAloneQuestionPanel").show();
        $("standAloneReviewPanel").hide();
        if($("standAloneUploadPanel") != null) {$("standAloneUploadPanel").hide(); };
        postType = "question";
    }  
    else if(panel == "standAloneQuestionPanel")
    {
        //if showing the question panel, put any non default text entered in the comment panel in the question text panel YH 6/4/10
        var commentTextInput = $("standAloneComment");        
        if(commentTextInput.value != commentTextInput.attributes["defaultText"].value && commentTextInput.value != "")
        {
            $("standAloneQuestionText").value = commentTextInput.value;
        }
        $("standAloneCommentPanel").hide();
        $("standAloneQuestionPanel").show();
        $("standAloneReviewPanel").hide();
        if($("standAloneUploadPanel") != null) {$("standAloneUploadPanel").hide(); };
        postType = "question";
    }  
    else if(panel == "standAloneUploadPanel")
    {
        var commentTextInput = $("standAloneComment");        

        $("standAloneCommentPanel").hide();
        $("standAloneQuestionPanel").hide();
        $("standAloneReviewPanel").hide();
        if($("standAloneUploadPanel") != null) {$("standAloneUploadPanel").show(); };
        postType = "upload";
    }  
    SetPostButtons('standAlone',postType,loggedIn);
    $("typeIcon").src = ImagePath + "/wall/" + postType + ".gif";
}     

//displays the login box for facebook
//id is the id of the panel that called the function
// YH 5/12/10       
function FacebookLogin(id,permissions)
{               
    var result;
    FB.login(function(response) {
      if (response.session) {
        if (response.perms) 
        {                                           
            LoginFacebookUser(response.session.access_token,response.session.uid,
                function(response)
                {
                    if(response != "error")
                    {
                        var result = response.parseJSON();                                 
                        $$('div[id $= WallLoginPanel]').each(function(element) {element.hide();});
                        $$('div[id $= PostToFacebookPanel]').each(function(element) {element.show();});
                        displayName = result.DisplayName;
                        loggedIn = true;
                        //if the preview is showing, update the names shows
                        if($(id + "PreviewPanel").visible())
                        {
                            //ShowPreview(id);
                            //now we actually do the post YH 6/7/10
                            $(id + "PreviewPostButton").onclick();
                        }
                        else
                        {
                            //show the welcome box
                            $(id + "LoggedInDisplayName").update(displayName);
                            $(id + "LoggedIn").show();                        
                            SetPostButtons(id,postType,true);
                        }
                    }
                }                        
            );                        
        } 
      } 
      else 
      {
      }
    }, {perms:permissions});                
}  

//shows the preview panel
//id is the id of the panel used
// YH 5/17/10
function ShowPreview(id)
{
    //if the type is comment and the id is standAlone then we need to get the actual type from the radio button
    if(postType == 'comment' && id == 'standAlone')
    {
        postType = $('form1').getInputs('radio', 'standAlonePostType').find(function(radio) { return radio.checked; }).value;
    }
    if(ValidatePost(id,postType))
    {
        //hide the content panel
        $(id + "Post").getElementsBySelector("[id=" + id + "ContentPanel]").invoke("hide");
        $(id + "Post").getElementsBySelector("[id=" + id + "PreviewDate]")[0].update(new Date().format("shortDateTime"));
        if(postType == "review")
        {
            $("reviewPreview").getElementsBySelector("[id=stars]")[0].src = ImagePath + "/stars/red_" + starsstandAlone + ".png";
            if($(id + "Pros") != null) 
            {
                if($(id + "Pros").value == "")
                {
                    $("reviewProsPreview").hide();
                }
                else
                {
                    $("reviewProsPreview").show();
                }
                $("reviewPreview").getElementsBySelector("[id=pros]")[0].update($(id + "Pros").value);
            }
            if($(id + "Cons") != null)
            {
                if($(id + "Cons").value == "")
                {
                    $("reviewConsPreview").hide();
                }
                else
                {
                    $("reviewConsPreview").show();
                }  
                $("reviewPreview").getElementsBySelector("[id=cons]")[0].update($(id + "Cons").value);
            }   
            if($("reviewPreview").getElementsBySelector("[id=recommended]").length > 0) 
            {
                $("reviewPreview").getElementsBySelector("[id=recommended]")[0].update(standAloneRecommended);
            }
            $("reviewPreview").getElementsBySelector("[id=bottomLine]")[0].update($(id + "BottomLine").value);
            $("commentPreview").hide();
            $("reviewPreview").show();
            $("questionPreview").hide();
        }
        else if(postType == "question")
        {
            //if the question title has not been changed from the default text, then we just show nothing for the title
            var questionTitleInput = $(id + "QuestionTitle");
            var questionTitleText = "";
            if(questionTitleInput.value != questionTitleInput.attributes["defaultText"].value)
            {
                questionTitleText = questionTitleInput.value;
            }
            $("questionPreview").getElementsBySelector("[id=questionTitle]")[0].update(questionTitleText);
            $("questionPreview").getElementsBySelector("[id=questionText]")[0].update($(id + "QuestionText").value);
            $("commentPreview").hide();
            $("reviewPreview").hide();
            $("questionPreview").show();

        }
        else if(postType == "commentPost")
        {
            $("commentPreview").getElementsBySelector("[id=commentText]")[0].update($(id + "Comment").value);
            $("commentPreview").show();
            $("reviewPreview").hide();
            $("questionPreview").hide();
        }  
        else if(postType == "comment")
        {
            $(id + "CommentPreview").getElementsBySelector("[id=" + id + "CommentText]")[0].update($("commentText_" + id).value);
            $(id + "CommentPreview").show();
        }  
        else if(postType == "upload")
        {            
            if (uploadType=="photo")
            {
                // upload the photo from the iframe
                window.iUploadImage.__doPostBack("ctl03_File1", "");                
                // when iframe reloads, it will call the function to show the preview or the error
            
            }
            else if (uploadType=="video")
            {
                var video_id = getUrlParam($(id + "VideoPath").value, "v");
                var video_embed = '<object width="320" height="265"><param name="wmode" value="transparent" /><param name="movie" value="http://www.youtube-nocookie.com/v/'+video_id+'&hl=en_US&fs=1&rel=0"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube-nocookie.com/v/'+video_id+'&hl=en_US&fs=1&rel=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="320" height="265" wmode="transparent"></embed></object><br /><br />';
                var video_title = $(id + "VideoTitle").value;
                var video_description = $(id + "VideoDescription").value;                

                if(video_description != $(id + "VideoDescription").attributes["defaultText"].value)
                {
                    $("videoPreview").getElementsBySelector("[id=videoDescription]")[0].update(video_description);
                }
                if(video_title != $(id + "VideoTitle").attributes["defaultText"].value)
                {
                    $("videoPreview").getElementsBySelector("[id=videoTitle]")[0].update(video_title);   
                }             
                $("videoPreview").getElementsBySelector("[id=videoEmbed]")[0].update(video_embed);
                $("videoPreview").show();
            }
            
            $("commentPreview").hide();
            $("reviewPreview").hide();
            $("questionPreview").hide();            
        }              
                 
        if($(id + "OwnThis").checked)
        {
            $(id + "OwnsThisName").show();
            $(id + "OwnsThisText").update("owns this product");
        }
        else
        {        
           $(id + "OwnsThisName").hide();
           $(id + "OwnsThisText").update("");
        }
        $(id + "OwnsThisName").update(displayName);
        $(id + "PreviewName").update(displayName);                
        $(id + "PreviewPanel").show();
        $(id + "WallLoginPanel").removeClassName("login");
        $(id + "WallLoginPanel").addClassName("loginPreview");
        $(id + "WallLoginPanel").childElements()[2].update("Login and Post");
        $(id + "WallLoginPanel").childElements()[3].childElements()[0].update("Login with Facebook and Post");
    } 
 } 

// function to show image preview
// RT 7/9/2010 
function ShowImagePreview(id, imgPath, imgError)
{
    if(imgError == "") 
    {
        var imageTitleInput = $(id + "ImageTitle");
        var imageTextInput = $(id + "ImageText");
        if(imageTitleInput.value != imageTitleInput.attributes["defaultText"].value)
        {
            $("imagePreview").getElementsBySelector("[id=ImageTitle]")[0].update($(id + "ImageTitle").value);
        }
        if(imageTextInput.value != imageTextInput.attributes["defaultText"].value)
        {
            $("imagePreview").getElementsBySelector("[id=ImageText]")[0].update($(id + "ImageText").value);
        }
        $("imagePhoto").src = imgPath;
        $(id+"ImagePath").value = imgPath.match(/(.*)[\/\\]([^\/\\]+\.\w+)$/)[2]; //filename without path
        $("imagePreview").show();
     }
     else
     {
        // show error
     }
} 
 
// hides the preview panel and shows the editable fields
// YH 5/17/10 
function EditPost(id)
{
    //if the type is comment and the id is standAlone then we need to get the actual type from the radio button
    if(postType = 'comment' && id == 'standAlone')
    {
        postType = $('form1').getInputs('radio', 'standAlonePostType').find(function(radio) { return radio.checked; }).value;
    }

   $(id + "PreviewPanel").hide();   
   $(id + "Post").getElementsBySelector("[id=" + id + "ContentPanel]").invoke("show");
   $(id + "WallLoginPanel").removeClassName("loginPreview");
   $(id + "WallLoginPanel").addClassName("login");  
   $(id + "WallLoginPanel").childElements()[2].update("Login");
   $(id + "WallLoginPanel").childElements()[3].childElements()[0].update("Login with Facebook");
}     

//sets the name and display of the post buttons
// YH 5/17/10
function SetPostButtons(id,postType,loggedIn)
{
    if(postType == "review")
    {
        $(id + 'PostButton').src = ImagePath + "/postReview.gif";
    }
    else if(postType == "commentPost")
    {
        $(id + 'PostButton').src = ImagePath + "/postComment.gif";
    }
    else if(postType == "question")
    {
        $(id + 'PostButton').src = ImagePath + "/postQuestion.gif";
    }
    else if(postType == "upload")
    {
        $(id + 'PostButton').src = ImagePath + "/uploadNow.gif";
    }
    
    if(loggedIn)
    {
        if($(id + 'PostButton') != null)
        {
            $(id + 'PreviewPostButton').src = $(id + 'PostButton').src;
        }
        //$$('img[id $= PostButton]').each(function(element) {element.show();}); //this shows all the post button not on the preview panel
        $(id + 'PostButton').show();
        $$('span[id $= PreviewOrLabel]').each(function(element) {element.hide();});
    }
    else
    {        
        //$$('img[id $= PostButton]').each(function(element) {element.hide();}); //this hides all the post button not on the preview panel
        $(id + 'PostButton').hide();
        $(id + 'PreviewPostButton').src = ImagePath + "/postAnon.gif";
        $(id + 'PreviewPostButton').show(); //make sure that the post button on the preview panel is always shown
        $$('span[id $= PreviewOrLabel]').each(function(element) {element.show();}); 
    }
}   

// validates the post depending on the post type
// YH 5/17/10
function ValidatePost(id,postType)
{
    var validated = true;
    if(postType == "review")
    {
        //call the validation function on the approrpiate panel
        validated = ValidateFields(id + "ReviewPanel");
        // stars + id has to be manually checked
        if(eval("stars" + id) == 0)
        {
            $(id + "ReviewStars").addClassName("validationFailed");
            validated = false;
        }                   
        else
        {
            $(id + "ReviewStars").removeClassName("validationFailed");
        }                    
    }
    else if(postType == "commentPost" || postType == "comment")
    {
        validated = ValidateFields(id + "CommentPanel");
    }
    else if(postType == "question")
    {
        validated = ValidateFields(id + "QuestionPanel");
    }  
    else if(postType == "upload")
    {
        if(uploadType=="video") 
        {
            validated = ValidateFields(id + "VideoForm");
        } 
        else if(uploadType=="photo") 
        {
            validated = ValidateFields(id + "PhotoForm");
            if(validated && $(id + "PreviewPanel").style.display=="none") { //if the rest validates AND we are not in preview mode
                validated = ValidateFields(window.iUploadImage.document.getElementById("imageUpload"));
            }
        }
    }                  
    return validated;                
}  

//validates the fields in the panel sent in. it looks for a field with the "required" class and then uses defaultText to see if the field has been completed
// YH 5/17/10
function ValidateFields(panel)
{
    if(typeof(panel) != 'object')   // if this is a name of an object and not the object itself
        panelToCheck = $(panel);    // RT 7/13/2010
    else
        panelToCheck = panel;

    var validated = true;
    
    try {
        panelToCheck.getElementsBySelector(".required").each(
           function(element){
                var defaultText = element.attributes["defaultText"] || "";
                if(element.value.trim() == defaultText.value || element.value.trim() == "")
                {
                    element.addClassName("validationFailed");
                    validated = false;
                }
                else
                {
                    element.removeClassName("validationFailed");
                }
           });
        panelToCheck.getElementsBySelector(".validate-password").each(
           function(element){
                //allow any character other than ' " and whitespace between 6 and 15 characters
                var pattern = /^[^'"\s]{6,15}$/;
                if(!pattern.test(element.value.trim()))
                {
                    element.addClassName("validationFailed");
                    validated = false;
                }
                else
                {
                    element.removeClassName("validationFailed");
                }
           }); 
        panelToCheck.getElementsBySelector(".validate-email").each(
           function(element){
                var pattern =/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
                if(!pattern.test(element.value.trim()))
                {
                    element.addClassName("validationFailed");
                    validated = false;
                }
                else
                {
                    element.removeClassName("validationFailed");
                }
           });  
       } catch (exc) {}                                    
       return validated;            
} 

//creates the wall post - refreshes the page on success
// button is the calling button
// id is the id of the element (standAlone or a post_id)
// identifier is the sku or question_id
function SubmitWallPost(button,id,type,identifier,wallType,returnUrl,postToFacebook)
{
    //if the type is comment and the id is standAlone then we need to get the actual type from the radio button
    if(type == 'comment' && id == 'standAlone')
    {
        type = $('form1').getInputs('radio', 'standAlonePostType').find(function(radio) { return radio.checked; }).value;
    }
    if(ValidatePost(id,type))
    {
        waitcursor();
        button.hide();
        $$('img[id $= PreviewButton]').each(function(element) {element.hide();});
        $$('img[id $= PreviewEditButton]').each(function(element) {element.hide();});
        button.next().show();        
        var postId = "";
        if(type == "review")
        {
            // only set the pros, cons & recommended fields if they exist in the form - RT, 6/30/2010
            var pros = ($(id + "Pros") == null ? "" : $(id + "Pros").value);
            var cons = ($(id + "Cons") == null ? "" : $(id + "Cons").value);
            var recommended = (eval(id + "Recommended") == null ? "" : eval(id + "Recommended"));
            CreateWallReview($(id + "BottomLine").value,pros,cons,eval("stars" + id),eval(id + "Recommended"),$(id + "OwnThis").checked,identifier,wallType,returnUrl,
                function(response)
                {
                    var result = response.parseJSON(); 
                    if(result.success == "true")
                    {
                        postId = result.pid;
                        WallPostSuccess(button,id,postId,type,returnUrl,"post",postToFacebook);
                    }
                    else
                    {
                        WallPostFailure(button,postId);
                    }
                }                        
            );
        }
        else if(type == "question")
        {
            CreateWallQuestion($(id + "QuestionTitle").value,$(id + "QuestionText").value,$(id + "OwnThis").checked,identifier,wallType,returnUrl,
                function(response)
                {
                    var result = response.parseJSON(); 
                    if(result.success == "true")
                    {
                        postId = result.pid;
                        WallPostSuccess(button,id,postId,type,returnUrl,"post",postToFacebook);
                    }
                    else
                    {
                        WallPostFailure(button,postId);
                    }                    
                }                        
            );                        
        } 
        else if(type == "commentPost")
        {
            CreateWallCommentPost($(id + "Comment").value,$(id + "OwnThis").checked,identifier,wallType,returnUrl,
                function(response)
                {
                    var result = response.parseJSON(); 
                    if(result.success == "true")
                    {
                        postId = result.pid;
                        WallPostSuccess(button,id,postId,type,returnUrl,"post",postToFacebook);
                    }
                    else
                    {
                        WallPostFailure(button,postId);
                    }                    
                }                        
            );                        
        } 
        else if(type == "upload")
        {
            if(uploadType == "video")
            {
                var video_title = $(id + "VideoTitle").value;
                var video_description = $(id + "VideoDescription").value;                

                if(video_description == $(id + "VideoDescription").attributes["defaultText"].value)
                {
                    video_description = "";
                }
                if(video_title == $(id + "VideoTitle").attributes["defaultText"].value)
                {
                    video_title = "";   
                } 
                
                CreateWallVideo(video_title,video_description,$F(id + "VideoPath"),$(id + "OwnThis").checked,identifier,wallType,returnUrl,
                    function(response)
                    {
                        var result = response.parseJSON(); 
                        if(result.success == "true")
                        {
                            postId = result.pid;
                            WallPostSuccess(button,id,postId,type,returnUrl,"post",postToFacebook);
                        }
                        else
                        {
                            WallPostFailure(button,postId);
                        }                    
                    }                        
                );  
            }
            else if(uploadType == "photo")
            {
                var img_title = $F(id + "ImageTitle");
                var img_text = $F(id + "ImageText");                

                if(img_text == $(id + "ImageText").attributes["defaultText"].value)
                {
                    img_text = "";
                }
                if(img_title == $(id + "ImageTitle").attributes["defaultText"].value)
                {
                    img_title = "";   
                } 
                CreateWallImage(img_title,img_text,$(id + "ImagePath").value,$(id + "OwnThis").checked,identifier,wallType,returnUrl,
                    function(response)
                    {
                        var result = response.parseJSON(); 
                        if(result.success == "true")
                        {
                            postId = result.pid;
                            WallPostSuccess(button,id,postId,type,returnUrl,"post",postToFacebook);
                        }
                        else
                        {
                            WallPostFailure(button,postId);
                        }                    
                    }                        
                );  
            }
                              
        } 
        else if(type == "comment")
        {
            CreateWallComment($("commentText_" + id).value,id,$(id + "OwnThis").checked,identifier,wallType,returnUrl,
                function(response)
                {
                    var result = response.parseJSON(); 
                    if(result.success == "true")
                    {
                        postId = result.cid;
                        WallPostSuccess(button,id,postId,type,returnUrl,"comment",postToFacebook);                   
                    }
                    else
                    {
                        WallPostFailure(button,postId);
                    }                    
                }                        
            );                        
        }                                                    
    }
}  

//called if a wall post is successfully posted
// postCategory is eiter post or comment - this is needed for the anchor (#post_id or #comment_id
// id is standAlone or the post id if it's coming from a specific post
// postId is the id of the new post
// postType is review, question, comment of commentPost
// YH 5/26/10
function WallPostSuccess(button,id,postId,postType,returnUrl,postCategory,postToFacebook)
{   
    //this uses jump, and not and anchor (#) because the anchor does not work properly when reloading
    var linkToPost = window.location.protocol + "//" + window.location.hostname + "/" + returnUrl + "?jump=" + postCategory + "_" + postId;
    if(postToFacebook)
    {
        PostToFacebook(id,postType,linkToPost);
    }       
    else
    {
        window.location.replace(linkToPost);
    }
    clearcursor();    
}

function WallPostFailure(button,id)
{
    clearcursor();
    button.next().hide();
    button.show();    
}

// Post a message to the users facebook page
// ObjectName, ObjectImagePath must be set elsewhere for this function to work
//YH 5/28/10
function PostToFacebook(id,postType,linkToPost)
{
    var message,picture,name,link,caption,description;
    picture = ObjectImagePath;
    link = linkToPost;
    caption = ObjectName;
    if(postType == "review")
    {    
        message = "Just posted a review of the " + ObjectName + " and rated it " + eval("stars" + id) + " stars." ;
        name = "";
        description = $(id + "BottomLine").value;
    }
    else if(postType == "question")
    {
        message = "Just asked a question about the " + ObjectName + "." ;
        name = $(id + "QuestionTitle").value;
        description = $(id + "QuestionText").value;                    
    } 
    else if(postType == "commentPost")
    {
        message = "Just posted a comment on the " + ObjectName + "." ;
        name = "";
        description = $(id + "Comment").value;                                          
    } 
    else if(postType == "comment")
    {        
        message = "Just commented on a post about the " + ObjectName + "." ;
        name = "";
        description = $("commentText_" + id).value;                                                               
    }
    else if(uploadType == "photo")
    {        
        message = "Just uploaded a photo of the " + ObjectName + "." ;
        name = "";
        description = $(id + "ImageText").value;                                                               
    }
    else if(uploadType == "video")
    {        
        message = "Just uploaded a video about the " + ObjectName + "." ;
        name = "";
        description = $(id + "VideoDescription").value;                                                               
    }
    
    var url = 'process.aspx';
    var params = 'type=posttofacebook&title=&message='+escape(message)+'&name='+escape(name)+'&description='+escape(description)+'&picture='+escape(picture)+'&link='+escape(link)+'&caption='+escape(caption);
    var myAjax = new Ajax.Request( url, { method: 'post', parameters: params, onComplete: window.location.replace(linkToPost)});       
}

function showSignUp() { $('loginPanel').hide(); $('signupPanel').show(); }
function showLogin() { $('signupPanel').hide(); $('loginPanel').show(); }

//id is the id of the panel containing the login
//panel is the panel to be validated
function WallLogin(id,panel,email,password,rememberMe)
{
    waitcursor(); 
    if(ValidateFields(panel))
    {
        LoginSiteUser(email,password,rememberMe,
            function(response)
            {
                if(response != "error")
                {
                    $("popupLoginError").hide();
                    var result = response.parseJSON();  
                    displayName = result.DisplayName;
                    loggedIn = true;
                    //hide all the login panels
                    $$('div[id $= WallLoginPanel]').each(function(element) {element.hide();});
                    //if the preview is showing, update the names shows
                    if($(id + "PreviewPanel").visible())
                    {
                        //ShowPreview(id);
                        //now we actually do post YH 6/7/10
                        $(id + "PreviewPostButton").onclick();
                    }
                    else
                    {
                        //show the welcome box
                        $(id + "LoggedInDisplayName").update(displayName);
                        $(id + "LoggedIn").show();
                        SetPostButtons(id,postType,true);
                    }
                    ajaxwin.close()
                }
                else
                {
                    $("popupLoginError").show();
                }
            }                        
        );
    }
    clearcursor(); 
}

//id is the id of the panel containing the login
//panel is the panel to be validated
function WallCreateAccount(id,panel,signupDisplayName,email,password,rememberMe)
{
    waitcursor(); 
    if(ValidateFields(panel))
    {
        CreateWallUser(signupDisplayName,email,password,rememberMe,
            function(response)
            {
                if(response != "error")
                {
                    $("popupSignupError").hide();
                    var result = response.parseJSON();  
                    displayName = result.DisplayName;
                    loggedIn = true;
                   //hide all the login panels
                    $$('div[id $= WallLoginPanel]').each(function(element) {element.hide();});
                    //if the preview is showing, update the names shows
                    if($(id + "PreviewPanel").visible())
                    {
                        //ShowPreview(id);
                        //now we actually do the post YH 6/7/10
                        $(id + "PreviewPostButton").onclick();
                    }
                    else
                    {
                        SetPostButtons(id,postType,true);
                    }
                    ajaxwin.close()
                }
                else
                {
                    $("popupSignupError").show();
                }
            }                        
        );
    }
    clearcursor(); 
}               

//end /sites/scripts/wall.js
