


function urlencode (str) {
    str = (str + '').toString();
    return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
}


// FUNCTION TO BOOKMARK A PAGE
function bookmarkpage(title, url){
	
	if (window.sidebar) { // firefox
		window.sidebar.addPanel(title, url, "");
		
	}
	else if(window.opera && window.print){ // opera
		var elem = document.createElement('a');
		elem.setAttribute('href',url);
		elem.setAttribute('title',title);
		elem.setAttribute('rel','sidebar');
		elem.click();
	} 
	else if(document.all) { // ie
		window.external.AddFavorite(url, title);
	}
	else if(window.chrome){
		alert('Press ctrl+D to bookmark (Command+D for macs) after you click Ok');
	}


}



// FUNCTION TO RETRIEVE NEW STATUS VIA AJAX AND INSERT IT AT THE BOTTOM
function voteFOAT(type_id, item_id, owner_id, rating, relocate, group_by_album){
	
	// DISABLE FORM TABLE
	disableField('tVote');
	Dom.setStyle('tVote','opacity', 1);
	
	// BEGIN URL TO FETCH COMMENT
	var poststr = 'sg=main.ajax_add_item_rating&type_id='+ type_id +'&item_id='+ item_id +'&owner_id='+ owner_id +'&rating='+ rating;
	var callback = {
		success: function(o) {
			if(o.responseText == ''){
				waitingPanel.hide();
				//alert('Delete Failed!');
			}else{
				// MUST BE JSON RESPONSE
				try {
					var resp = YAHOO.lang.JSON.parse(o.responseText);  
				}
				catch(e) {				
					waitingPanel.hide();
					return false;
				}
				// If server said failure
				if(resp.success == 0){
					waitingPanel.hide();
					//alertVar(resp.errors, true);
					return false;
				}else{	
					waitingPanel.hide();
					// IF TOLD TO RELOCATE, DO SO
					if(relocate == true){	
						if(type_id == 1){
							document.location.href="/fa/rides/v_id-" + resp.customObj.item_id;
						}else if(type_id == 2){
							document.location.href="/fa/videos/v_id-" + resp.customObj.item_id;
						}else if(type_id == 3){
							document.location.href="/fa/photos/v_id-" + resp.customObj.item_id + "/group_by_album-" + intVal(group_by_album);
						}
					}		
					

				}
			}
			
		},
		
		failure: function(o) {			
			waitingPanel.hide();
		}
		
	};
	// initiate a new waiting panel (use "window.xxx" so we can hide it from outside of this function);
	window.waitingPanel = new panelLoading('Voting.  Please wait...<br />[<a href="javascript:void(0);" onClick="stopIt();waitingPanel.hide()">Stop</a>]');
	// Show the Panel
	waitingPanel.show();
	// start ajax request
	YAHOO.util.Connect.asyncRequest('POST', 'index.php', callback, poststr );
	
}




// GET CREW SUGGESTIONS POPUP
function getMutualCrew(login,member_id){
	popupAjaxContent('MUTUAL CREW MEMBERS WITH ' + login,590,300,'/fa/user-ajax_mutual_crew/member_id-'+member_id);
}

// PAD A STRING ON THE LEFT
function lpad(string_to_pad, length, pad_with_string) {
    var str = '' + string_to_pad;
    while (str.length < length)
        str = pad_with_string + str;
    return str;
}


// IS THIS A VALID EMAIL ADDRESS
var is_valid_email =  function (val) {
	//var filter = /^([\w]+(?:\.[\w]+)*)@((?:[\w]+\.)*\w[\w]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	if(typeof(val)== 'undefined' || YAHOO.lang.trim(val) == ""){
		return false;	
	}
	var filter = /^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/i;
	if (filter.test(val) === false) {
		return false;
	}
	
	return true;
}


// GENERATE A RANDOM ID
function uniqid(){
	var newDate = new Date;
	return newDate.getTime(); 
} 
/// CLEAR OUT OLD SESSION BEFORE ATTEMPTING TO LOG IN
function topLogin(id){
	var poststr = "sg=main.ajax_logout";
	var callback = {
		success: function(o) {
			if(o.responseText == ''){
				alert('Login Failed!');
			}else{
				// MUST BE JSON RESPONSE
				try {
					var resp = YAHOO.lang.JSON.parse(o.responseText);  
				}
				catch(e) {				
					waitingPanel.hide();
					alert('Invalid Response from Server');
					return false;
				}
				// If server said failure
				if(resp.success == 0){
					waitingPanel.hide();
					alert('Connection Failed');
					return false;
					
				}else{			
					//waitingPanel.hide();
					waitingPanel.setHeader('Connection established. Logging in...');
					var f = YAHOO.util.Dom.get('fTopLogin');
					if(YAHOO.lang.isObject(f)){
						f.submit();	
					}
				}
			}
			
		},
		
		failure: function(o) {
			var f = YAHOO.util.Dom.get('fTopLogin');
			if(YAHOO.lang.isObject(f)){
				f.submit();	
			}
		}
		
	};
	// initiate a new waiting panel (use "window.xxx" so we can hide it from outside of this function);
	window.waitingPanel = new panelLoading('Connecting to server.  Please wait...<br />[<a href="#" onClick="stopIt();waitingPanel.hide()">Stop</a>]');
	// Show the Panel
	waitingPanel.show();
	// start ajax request
	YAHOO.util.Connect.asyncRequest('POST', 'index.php', callback, poststr );
}
// DISAPPEARING/REAPPEARING TEXT INPUT 
function disappearingInputText(htmlID, textToMatch){
	var el = YAHOO.util.Dom.get(htmlID);
	if(!el){ return false; }
	if(el.value == '' || el.value == textToMatch){
		el.value = '';
		YAHOO.util.Dom.setStyle(htmlID,'color','#242424');
	}
}
function reappearingInputText(htmlID, textToMatch){
	var el = YAHOO.util.Dom.get(htmlID);
	if(!el){ return false; }
	if(YAHOO.lang.trim(el.value) == ''){
		el.value = textToMatch;
		YAHOO.util.Dom.setStyle(htmlID,'color','#999');
	}
}


// FUNCTION TO SWITCH TAB CONTENT
/*-- requires object similar to 
	sgNav = {
				"label1":"tab1",
				"label2":"tab2",
				"label3":"tab3"
			}
*/
var sgTabSwitch = function(tabId, tabsObj){
	var activeTab = YAHOO.util.Dom.get(tabId);
	// IF OBJECTS DON'T EXIST RETURN FALSE
	if(!activeTab || !YAHOO.lang.isObject(tabsObj)){
		return false;
	}
	// DECLARE ACTION METHODS
	this.hide = function(el){
		YAHOO.util.Dom.addClass(el,'hidden'); 
	}
	this.show = function(el){
		YAHOO.util.Dom.removeClass(el,'hidden'); 
	}
	this.activate = function(el){
		YAHOO.util.Dom.addClass(el,'active'); 
	}
	this.inactivate = function(el){
		YAHOO.util.Dom.removeClass(el,'active'); 
	}
	//LOOP THROUGH tabsObj AND ACTIVATE/INACTIVATE AS APPROPRIATE
	for(i in tabsObj){
		if(i==tabId){
			this.activate(i);
			this.show(tabsObj[i]);
		}else{
			this.inactivate(i);
			this.hide(tabsObj[i]);
		}
	}
}

// THIS FUNCTION WILL GET ALL IMG, OBJECT, EMBED ELEMENTS WITHIN htmlID AND SHRINK WIDHTS DOWN TO SPECIFIED HEIGHT/WIDTH
function shrink_objects(htmlID, max_width, max_height, iterator){
	if(typeof(iterator) == 'undefined'){
		iterator = 0;	
	}
	//alert(parseInt(window.shrink_i));
	if(iterator > 10){
		return false;	
	}
	var new_size = new Object;
	var resized = new Object;
	new_size.width = intVal(max_width);
	new_size.height= intVal(max_height);
	var el = YAHOO.util.Dom.get(htmlID);
	if(!el){
		return false;
	}
	function isAnObj(myObj){
		if( (typeof(myObj) == 'object' || typeof(myObj) == 'function') && myObj.length > 0){
			return true;
		}
		return false;
	}
	var imgs 	= YAHOO.util.Dom.getElementsBy(function(el){return true;},'img',htmlID);
	var embds	= YAHOO.util.Dom.getElementsBy(function(el){return true;},'embed',htmlID); 
	var objs	= YAHOO.util.Dom.getElementsBy(function(el){return true;},'object',htmlID); 
	if(isAnObj(imgs) ){
		for(i in imgs){ ;
			var thisEl = imgs[i]; 
			if((thisEl.width == 0)){
				iterator++; 
				if( (thisEl != undefined && thisEl != null) && (thisEl.width == undefined || thisEl.width == 0)){ 
					setTimeout(function(){ shrink_objects(htmlID, max_width, max_height, iterator); }, 1000);
				}
				return;
			}
			
			//alertVar(thisEl.width,true);
			if((thisEl.width > max_width || thisEl.height > max_height)){
				resized = shrink_width(imgs[i], new_size);
				imgs[i].width = resized.width;
				imgs[i].height= resized.height; 
				YAHOO.util.Dom.setStyle(imgs[i], 'width', resized.width+'px');
				YAHOO.util.Dom.setStyle(imgs[i], 'height', resized.height+'px');
			}
			
		}
	}
	if(isAnObj(objs)){
		for(i in objs){ //continue;
			var thisEl = objs[i];
			if(thisEl != null && (thisEl.width == undefined || thisEl.width == 0)){
				continue;
			}
			if(thisEl != null && thisEl.width > max_width || thisEl.height > max_height){
				resized = shrink_width(thisEl, new_size);
				thisEl.width = resized.width;
				thisEl.height= resized.height;
				YAHOO.util.Dom.setStyle(thisEl, 'width', resized.width+'px');
				YAHOO.util.Dom.setStyle(thisEl, 'height', resized.height+'px');
			}
		}
	}
	if(isAnObj(embds)){
		for(i in embds){ //continue;
			var thisEl = embds[i];
			if(thisEl != null && thisEl.width == undefined || thisEl.width == 0){
				continue;
			}
			
			if(thisEl != null && thisEl.width > max_width || thisEl.height > max_height){
				resized = shrink_width(thisEl, new_size);
				thisEl.width = resized.width;
				thisEl.height= resized.height;
				YAHOO.util.Dom.setStyle(thisEl, 'width', resized.width+'px');
				YAHOO.util.Dom.setStyle(thisEl, 'height', resized.height+'px');
			}
		}
	}
	
}

// get new dimensions so it fits within the maximum
// o = original dimensions / image, m = maximum dimensions
function shrink_width(o, m)
{
    // r = resized
    var r = {width: o.width, height: o.height};
    // if an image, rather than an object, resize it
    //if(o.nodeName && o.nodeName.toLowerCase() == "img") r = o;
    if(r.width > m.width)
    {
        r.height = r.height * (m.width / r.width);
        r.width = m.width;
        if(r.height > m.height)
        {
            r.width = r.width * (m.height / r.height);
            r.height = m.height;
        }
    }
    else if(r.height > m.height)
    {
        r.width = r.width * (m.height / r.height);
        r.height = m.height;
    }
	r.width = parseInt(r.width);
	r.height= parseInt(r.height);
    return r;
}



function get_html_translation_table (table, quote_style) {
    // Returns the internal translation table used by htmlspecialchars and htmlentities  
    
    // %          note: It has been decided that we're not going to add global
    // %          note: real constants, but strings instead. Integers are also supported if someone
    // %          note: chooses to create the constants themselves.
    // *     example 1: get_html_translation_table('HTML_SPECIALCHARS');
    // *     returns 1: {'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}
    
    var entities = {}, hash_map = {}, decimal = 0, symbol = '';
    var constMappingTable = {}, constMappingQuoteStyle = {};
    var useTable = {}, useQuoteStyle = {};
    
    // Translate arguments
    constMappingTable[0]      = 'HTML_SPECIALCHARS';
    constMappingTable[1]      = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';

    useTable       = !isNaN(table) ? constMappingTable[table] : table ? table.toUpperCase() : 'HTML_SPECIALCHARS';
    useQuoteStyle = !isNaN(quote_style) ? constMappingQuoteStyle[quote_style] : quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT';

    if (useTable !== 'HTML_SPECIALCHARS' && useTable !== 'HTML_ENTITIES') {
        throw new Error("Table: "+useTable+' not supported');
        // return false;
    }

    entities['38'] = '&amp;';
    if (useTable === 'HTML_ENTITIES') {
        entities['160'] = '&nbsp;';
        entities['161'] = '&iexcl;';
        entities['162'] = '&cent;';
        entities['163'] = '&pound;';
        entities['164'] = '&curren;';
        entities['165'] = '&yen;';
        entities['166'] = '&brvbar;';
        entities['167'] = '&sect;';
        entities['168'] = '&uml;';
        entities['169'] = '&copy;';
        entities['170'] = '&ordf;';
        entities['171'] = '&laquo;';
        entities['172'] = '&not;';
        entities['173'] = '&shy;';
        entities['174'] = '&reg;';
        entities['175'] = '&macr;';
        entities['176'] = '&deg;';
        entities['177'] = '&plusmn;';
        entities['178'] = '&sup2;';
        entities['179'] = '&sup3;';
        entities['180'] = '&acute;';
        entities['181'] = '&micro;';
        entities['182'] = '&para;';
        entities['183'] = '&middot;';
        entities['184'] = '&cedil;';
        entities['185'] = '&sup1;';
        entities['186'] = '&ordm;';
        entities['187'] = '&raquo;';
        entities['188'] = '&frac14;';
        entities['189'] = '&frac12;';
        entities['190'] = '&frac34;';
        entities['191'] = '&iquest;';
        entities['192'] = '&Agrave;';
        entities['193'] = '&Aacute;';
        entities['194'] = '&Acirc;';
        entities['195'] = '&Atilde;';
        entities['196'] = '&Auml;';
        entities['197'] = '&Aring;';
        entities['198'] = '&AElig;';
        entities['199'] = '&Ccedil;';
        entities['200'] = '&Egrave;';
        entities['201'] = '&Eacute;';
        entities['202'] = '&Ecirc;';
        entities['203'] = '&Euml;';
        entities['204'] = '&Igrave;';
        entities['205'] = '&Iacute;';
        entities['206'] = '&Icirc;';
        entities['207'] = '&Iuml;';
        entities['208'] = '&ETH;';
        entities['209'] = '&Ntilde;';
        entities['210'] = '&Ograve;';
        entities['211'] = '&Oacute;';
        entities['212'] = '&Ocirc;';
        entities['213'] = '&Otilde;';
        entities['214'] = '&Ouml;';
        entities['215'] = '&times;';
        entities['216'] = '&Oslash;';
        entities['217'] = '&Ugrave;';
        entities['218'] = '&Uacute;';
        entities['219'] = '&Ucirc;';
        entities['220'] = '&Uuml;';
        entities['221'] = '&Yacute;';
        entities['222'] = '&THORN;';
        entities['223'] = '&szlig;';
        entities['224'] = '&agrave;';
        entities['225'] = '&aacute;';
        entities['226'] = '&acirc;';
        entities['227'] = '&atilde;';
        entities['228'] = '&auml;';
        entities['229'] = '&aring;';
        entities['230'] = '&aelig;';
        entities['231'] = '&ccedil;';
        entities['232'] = '&egrave;';
        entities['233'] = '&eacute;';
        entities['234'] = '&ecirc;';
        entities['235'] = '&euml;';
        entities['236'] = '&igrave;';
        entities['237'] = '&iacute;';
        entities['238'] = '&icirc;';
        entities['239'] = '&iuml;';
        entities['240'] = '&eth;';
        entities['241'] = '&ntilde;';
        entities['242'] = '&ograve;';
        entities['243'] = '&oacute;';
        entities['244'] = '&ocirc;';
        entities['245'] = '&otilde;';
        entities['246'] = '&ouml;';
        entities['247'] = '&divide;';
        entities['248'] = '&oslash;';
        entities['249'] = '&ugrave;';
        entities['250'] = '&uacute;';
        entities['251'] = '&ucirc;';
        entities['252'] = '&uuml;';
        entities['253'] = '&yacute;';
        entities['254'] = '&thorn;';
        entities['255'] = '&yuml;';
    }

    if (useQuoteStyle !== 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';
    }
    if (useQuoteStyle === 'ENT_QUOTES') {
        entities['39'] = '&#39;';
    }
    entities['60'] = '&lt;';
    entities['62'] = '&gt;';


    // ascii decimals to real symbols
    for (decimal in entities) {
        symbol = String.fromCharCode(decimal);
        hash_map[symbol] = entities[decimal];
    }
    
    return hash_map;
}

// Convert all applicable characters to HTML entities  
function htmlentities (string, quote_style) {
    // -    depends on: get_html_translation_table
    // *     example 1: htmlentities('Kevin & van Zonneveld');
    // *     returns 1: 'Kevin &amp; van Zonneveld'
    // *     example 2: htmlentities("foo'bar","ENT_QUOTES");
    // *     returns 2: 'foo&#039;bar'
    var hash_map = {}, symbol = '', tmp_str = '', entity = '';
    tmp_str = string.toString();
    
    if (false === (hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style))) {
        return false;
    }
    hash_map["'"] = '&#039;';
    for (symbol in hash_map) {
        entity = hash_map[symbol];
        tmp_str = tmp_str.split(symbol).join(entity);
    }
    
    return tmp_str;
}

// HILIGHT CONTENTS OF A FIELD
function hilightField(field_id){
	var myid = getID(field_id);
	if(!myid){
		return false;
	}
	myid.focus();
	myid.select();
}

// UPDATE CAPTCHA IMAGE
function renewCaptcha(){
	var fieldID 	= getID('captcha-id');
	var imgID		= getID('captcha-img');
	var poststr 	= "sg=main.ajax_renew_captcha&captcha_id=" + fieldID.value;
	var callback	= {
		success: function(o) {
			if(o.responseText == ''){
				alert('Delete Failed!');
			}else{
				// MUST BE JSON RESPONSE
				try {
					var resp = YAHOO.lang.JSON.parse(o.responseText);  
				}
				catch(e) {				
					waitingPanel.hide();
					alert('Invalid Response from Server');
					return false;
				}
				// If server said failure
				if(resp.success == 0){
					waitingPanel.hide();
					//alertVar(resp.errors);
					alert(resp.message);
					return false;					
				}else{					
					waitingPanel.hide();
					imgID.src		= '/captcha.php?captcha_id='+resp.customObj.captcha_id;
					fieldID.value	= resp.customObj.captcha_id;
					
				}
			}
			
		},		
		failure: function(o) {
			alert('CAPTCHA update failed');
		}		
	};
	// initiate a new waiting panel (use "window.xxx" so we can hide it from outside of this function);
	window.waitingPanel = new panelLoading('Updating CAPTCHA Image.  Please wait...<br />[<a href="#" onClick="stopIt();waitingPanel.hide()">Stop Update</a>]');
	// Show the Panel
	waitingPanel.show();
	// start ajax request
	YAHOO.util.Connect.asyncRequest('POST', window.location.protocol+'//'+window.location.hostname+'/index.php', callback, poststr );
}




// FUNCTION TO ADDSLASHES
function addslashes( str ) {
	return (str+'').replace(/([\\"'])/g, "\\$1").replace(/\0/g, "\\0");
}

// FUNCTION TO STRIPSLASHES
function stripslashes( str ) {
	return (str+'').replace(/\0/g, '0').replace(/\\([\\'"])/g, '$1');

}


// function to hilight submit button
function animate_glowing(myID){
    // Create a new ColorAnim instance
    var oButtonAnim = new YAHOO.util.ColorAnim(myID, { backgroundColor: { to: "#FFCC66" } });

    /*
        Restart the color animation each time the target color has 
        been applied.
    */ 

    oButtonAnim.onComplete.subscribe(function () {
	
        this.attributes.backgroundColor.to = (this.attributes.backgroundColor.to == "#283648") ? "#FFCC66" : "#283648";
    
        this.animate();
    
    });
    
    oButtonAnim.animate();
	// remove "submit" class from buttons so the colors can come through
	YAHOO.util.Dom.removeClass(myID,'submit');
	return;
}
// function to hilight submit button
function animate_glowing_errors(myID){
    // Create a new ColorAnim instance
    var oButtonAnim = new YAHOO.util.ColorAnim(myID, { backgroundColor: { to: "#FF0000" } });


    /*
        Restart the color animation each time the target color has 
        been applied.
    */ 

    oButtonAnim.onComplete.subscribe(function () {

        this.attributes.backgroundColor.to = (this.attributes.backgroundColor.to == "#FF0000") ? "#FFCC66" : "#FF0000";
    
        this.animate();
    
    });
    
    oButtonAnim.animate();
	return;
}
// Display errors in a div
function display_errors(divID, errors){
	// first, we need to remove all instances of errorform class
	var elements = YAHOO.util.Dom.getElementsByClassName('errorform');
	for(i in elements){
		var j = elements[i].id;
		j = j.replace(/_/,'-');// replace underscores with dashes
		YAHOO.util.Dom.removeClass(j,'errorform');	
	}
	// set vars
	var tmpDiv;
	var myDiv = getID(divID);
	var varType = typeof(errors);
	// if invalid vars sent, exit
	if(!myDiv || varType != 'object' && varType != 'string'){
		if(myDiv != null && (errors == false || errors == null) ){
			myDiv.innerHTML = "";	
		}
		return false;
	}
	
	// clear out old error div
	myDiv.innerHTML = "";
	
	var stringStart = '<div class="sectionTitle5"><h3>Error</h3></div><div class="section"><div class="sectionContent">';	
	var stringMiddle = '';
	var stringEnd = '</div></div>';
	if(varType == 'string'){
		stringMiddle = '<ul class="msg-error"><li>'+errors+'</li></ul>';
	}else if(varType == 'object'){
		stringMiddle += '<ul class="msg-error">';
		for(i in errors){
			j = i.replace(/_/,'-');
			// if i is a div id, add the error look to it
			tmpDiv = getID(j);
			if(tmpDiv){
				YAHOO.util.Dom.addClass(j,'errorform');	
			}
			stringMiddle += '<li>'+errors[i]+'</li>';
		}
		stringMiddle += '</ul>';
	}
	// insert new string into error div
	myDiv.innerHTML = stringStart+stringMiddle+stringEnd;	
}


// save on file popup
function saveOnFilePopup(){
	winWallet = window.open('https://www.thefoat.com/?sg=user_wallet.add_on_file&is_pop=1','winWallet','width=750,height=600,resizable=no,scrollbars=yes,location=no,status=yes,menubar=no,copyhistory=no');
	if (window.focus) {winWallet.focus();}
}

// add money to wallet popup
function addToWalletPopup(amtOther,is_called_pay,is_recurring){
	var is_pay;
	var amtOther2;
	amtOther2 = floatVal(amtOther);
	if(typeof(is_called_pay) != 'undefined' && is_called_pay == true){
		is_pay = 1;
	}
	if(amtOther2 > 0){
		amt='other';	
	}else{
		amt=amtOther2;	
	}

	winWallet = window.open('https://www.thefoat.com/?sg=user_wallet.add1&is_pop=1&is_pay='+is_pay+'&is_recurring='+is_recurring+'&amt='+amt+'&amtOther='+amtOther2,'winWallet','width=750,height=600,resizable=no,scrollbars=yes,location=no,status=yes,menubar=no,copyhistory=no');
	if (window.focus) {winWallet.focus();}
}
// update the wallet amt on top of the screen
function updateWalletDisplay(amt){
	var mySpan = getID('walletAmt');
	if(mySpan){
		mySpan.innerHTML = '$'+amt;	
	}
}

// TOP BAR LOGIN FORM BACKGROUND REPLACEMENTS
function topBarLoginFormBG(){
	var email 	= YAHOO.util.Dom.get('top-u-email');
	var passwd	= YAHOO.util.Dom.get('top-u-password');
	if(email && passwd){
		if( email.value == ""){
			YAHOO.util.Dom.setStyle('top-u-email', 'background', '#FFFFFF url(/images/lay1/inputBgEmail.png) no-repeat');	
		}else{
			YAHOO.util.Dom.setStyle('top-u-email', 'background', 'transparent');	
		}
		if( passwd.value == ""){
			YAHOO.util.Dom.setStyle('top-u-password', 'background', '#FFFFFF url(/images/lay1/inputBgPassword.png) no-repeat');	
		}else{
			YAHOO.util.Dom.setStyle('top-u-password', 'background', 'transparent');	
		}
		
	}
	listeners = YAHOO.util.Event.getListeners ( 'top-u-email' , 'click' );
	if(listeners == null){
		YAHOO.util.Event.on('top-u-email', 'keypress', topBarLoginFormBG);
		YAHOO.util.Event.on("top-u-email", "mouseleave", topBarLoginFormBG);	
		YAHOO.util.Event.on("top-u-email", "click", topBarLoginFormBG);
		YAHOO.util.Event.on('top-u-password', 'keypress', topBarLoginFormBG);
		YAHOO.util.Event.on("top-u-password", "mouseleave", topBarLoginFormBG);	
		YAHOO.util.Event.on("top-u-password", "click", topBarLoginFormBG);
	}
	
}
// KEEP ON TOP OF WHEN THE LOGIN FORM BACKGROUND NEEDS TO CHANGE, ON LOAD, ON CHANGE, ON MOUSEOUT
//UNCOMMENT WHEN NEEDING TO USE topBarLoginFormBG();//YAHOO.util.Event.onAvailable('top-u-password',topBarLoginFormBG);

// top bar quick search
function chooseSearch(){
	var divSelect = getID('bannerSearchSelect');
	var divCurrent= getID('bannerSearchSelectCurrent');
	YAHOO.util.Dom.setStyle(divSelect.id, 'top', '5px');			
	YAHOO.util.Dom.setStyle(divCurrent.id, 'top', '-2000px');
	//YAHOO.util.Event.on(document,'onmousemove',closeChooseSearch);
	setTimeout(closeChooseSearch,4000);
	
}
function chooseSearchChosen(chosen){
	var fmsSG				= getID('fmsSG');
	var bannerSearchTerm	= getID('bannerSearchTerm');
	var divSelect = getID('bannerSearchSelect');
	var divCurrent= getID('bannerSearchSelectCurrent');
	divCurrent.innerHTML = chosen.substr(0, 1).toUpperCase() + chosen.substr(1);
	if(chosen=='parts'){
		fmsSG.value = 'mm_p.search';
	}else if(chosen=='vehicles'){
		fmsSG.value = 'mm_v.search';
	}else if(chosen=='members'){
		fmsSG.value = 'user.search_users';
	}else{
		fmsSG.value = chosen+'.home';
	}	
	closeChooseSearch();
}
function closeChooseSearch(e){
	//fmsSG = getID('fmsSG').value;
	//fmSG = 'aah';//YAHOO.util.Event.getXY(e); 
	var divSelect = getID('bannerSearchSelect');
	var divCurrent= getID('bannerSearchSelectCurrent');				
	YAHOO.util.Dom.setStyle(divSelect.id, 'top', '-2000px');			
	YAHOO.util.Dom.setStyle(divCurrent.id, 'top', '0px');
}



// grey screen with "loading" message
function panelLoading(header){
	YAHOO.namespace("example.container");

	// Initialize the temporary Panel to display while waiting for external content to load
	YAHOO.example.container.wait = 
			new YAHOO.widget.Panel("wait",  
				{ width:"240px", 
				  fixedcenter:true, 
				  close:false, 
				  iframe: true,
				  draggable:false, 
				  zindex:999,
				  modal:true,
				  visible:false
				} 
			);
	
	YAHOO.example.container.wait.setHeader(header);
	YAHOO.example.container.wait.setBody('<img src="/images/loading.gif" />');
	YAHOO.example.container.wait.render(document.body);
	
	this.show = function(){YAHOO.example.container.wait.show();}
	this.hide = function(){YAHOO.example.container.wait.hide();}
	this.setHeader = function(var1){YAHOO.example.container.wait.setHeader(var1)};

}

// grey screen with "loading" message
function panelLoading2(header){
	YAHOO.namespace("container");

	// Initialize the temporary Panel to display while waiting for external content to load
	YAHOO.container.wait = 
			new YAHOO.widget.Panel("wait",  
				{ width:"240px", 
				  fixedcenter:true, 
				  close:false, 
				  iframe: true,
				  draggable:false, 
				  zindex:999,
				  modal:true,
				  visible:false
				} 
			);
	
	YAHOO.container.wait.setHeader(header);
	YAHOO.container.wait.setBody('<img src="/images/loading.gif" />');
	YAHOO.container.wait.render(document.body);
	
	this.show = function(){YAHOO.container.wait.show();}
	this.hide = function(){YAHOO.container.wait.hide();}
	
	return YAHOO.container.wait;

}


// get float value of a variable
function floatVal(x){
	x = String(x);
	if(x.length < 1){
		return 0;	
	}
	var str = x.replace(/[^0-9\-\.]/g,'');
	if(str.length < 1){
		return 0;	
	}
	negativeStr = '';
	if(str.substring(0,1) == '-'){
		negativeStr = '-';	
	}
	str2 = x.replace(/[^0-9\.]/g,'');
	return parseFloat((negativeStr+str2)*1);	
}
// get integer value of a variable
function intVal(x){
	x = String(x);
	if(x.length < 1){
		return 0;	
	}
	var str = x.replace(/[^0-9\-\.]/g,'');
	if(str.length < 1){
		return 0;	
	}
	negativeStr = '';
	if(str.substring(0,1) == '-'){
		negativeStr = '-';	
	}
	str2 = x.replace(/[^0-9\.]/g,'');
	return parseInt((negativeStr+str2)*1);	
}

function toggleLayer(whichLayer){
	var style2 = getID(whichLayer);
	var toggleBtn = getID(whichLayer+'Btn');
	if(style2.style.display != 'none' && !Dom.hasClass(whichLayer,'hidden')){
		style2.style.display = 'none';	
		Dom.addClass(whichLayer,'hidden');
		toggleBtn.src = '/images/max.gif';
	}else{
		style2.style.display = 'block';
		toggleBtn.src = '/images/min.gif';
		
		Dom.removeClass(whichLayer,'hidden');
	}
}
function showLayer(whichLayer,timeout){
	var style2 = getID(whichLayer).style;
	style2.display = 'block';
	if(typeof(timeout) != 'undefined' && style2 != null){
		setTimeout('hideLayer(\''+whichLayer+'\')',3000);	
	}
}
function hideLayer(whichLayer){
	var style2 = getID(whichLayer).style;
	if(style2 != null){
		style2.display = 'none';
	}
}
function visibleLayer(whichLayer,timeout){
	var style2 = getID(whichLayer).style;
	YAHOO.util.Dom.removeClass(whichLayer,'invisible');
	if(typeof(timeout) != 'undefined' && style2 != null){
		setTimeout('invisibleLayer(\''+whichLayer+'\')',3000);	
	}
}
function invisibleLayer(whichLayer){
	var style2 = getID(whichLayer).style;
	if(style2 != null){
		YAHOO.util.Dom.addClass(whichLayer,'invisible');
	}
}

function minLayer(whichLayer){
	var myArray = new Array();
	if(whichLayer == 'TabPropertyProfile'){
		var myArray = new Array('POI','PLI','PC','PA','SI','PTAI','NAI','PProfile');
	}else if(whichLayer == 'TabSaleHistory'){
		var myArray = new Array('SLH','Trans1','Trans2');
	}
	for ( var i=0, len=myArray.length; i<len; ++i ){
		hideLayer(myArray[i]);
	}
}
function maxLayer(whichLayer){
	var myArray = new Array();
	if(whichLayer == 'TabPropertyProfile'){
		var myArray = new Array('PProfile','POI','PLI','PC','PA','SI','PTAI','NAI');
	}else if(whichLayer == 'TabSaleHistory'){
		var myArray = new Array('SLH','Trans1','Trans2');
	}
	for ( var i=0, len=myArray.length; i<len; ++i ){
		showLayer(myArray[i]);
	}
}

function showAllfields(formName){
	var allfields = document.getElementById(formName).elements;
	document.write('<table>');
	// loop through all input tags and add events
    for (var i=0; i<allfields.length; i++){
		if(i%2 == 0){sclass = 'alt1';}else{sclass = 'alt2';}
        var field = allfields[i];
		document.write('\n<tr><td class="'+sclass+'">'+field['name']+'</td><td class="'+sclass+'">'+field['value']+'</td></tr>');
	}
	document.write('</table>');
}
function print_r(input, _indent){
    if(typeof(_indent) == 'string') {
        var indent = _indent + '    ';
        var paren_indent = _indent + '  ';
    } else {
        var indent = '    ';
        var paren_indent = '';
    }
    switch(typeof(input)) {
        case 'boolean':
            var output = (input ? 'true' : 'false') + "\n";
            break;
        case 'object':
            if ( input===null ) {
                var output = "null\n";
                break;
            }
            var output = ((input.reverse) ? 'Array' : 'Object') + " (\n";
            for(var i in input) {
                output += indent + "[" + i + "] => " + print_r(input[i], indent);
            }
            output += paren_indent + ")\n";
            break;
        case 'number':
        case 'string':
        default:
            var output = "" + input  + "\n";
    }
    return output;
}

// ODOMETER COUNTER CLASS
YAHOO.namespace("odometer");
YAHOO.odometer.SGOdometer = function(args){

	// SIMPLE VARIABLE ISSET CHECKER
	var isset = function(prop) {
				return (typeof prop !== 'undefined');
			};
			
	// MODIFY THE STRING OBJECT TO ADD A REVERSE FUNCTION
	String.prototype.reverse = function(){
		splitext = this.split("");
		revertext = splitext.reverse();
		reversed = revertext.join("");
		return reversed;
	}

        

	// SET INITIAL VALUES
	if( !isset(args) || !YAHOO.util.Lang.isObject(args) ){
		var args = 	{
					'last_num' 		: '0',
					'container_id'	: 'sgodometer',
					'prefix'		: 'odo',
					'places'		: 11,
					'digit_srcs'	: 	{
											'_'		: '/images/lay1/odo_.gif',
											'0'		: '/images/lay1/odo0.gif',
											'1'		: '/images/lay1/odo1.gif',
											'2'		: '/images/lay1/odo2.gif',
											'3'		: '/images/lay1/odo3.gif',
											'4'		: '/images/lay1/odo4.gif',
											'5'		: '/images/lay1/odo5.gif',
											'6'		: '/images/lay1/odo6.gif',
											'7'		: '/images/lay1/odo7.gif',
											'8'		: '/images/lay1/odo8.gif',
											'9'		: '/images/lay1/odo9.gif',
											'10'	: '/images/lay1/odo10.gif',
											'blur'	: '/images/lay1/odoBlur.gif'
										}
					}
				
	}
	this.last_num		= intVal(args.last_num);
	this.container_id	= args.container_id;
	this.prefix			= args.prefix;
	this.places			= intVal(args.places);
	this.digit_srcs		= args.digit_srcs;
	this.polling_secs	= 60;
	this.polling_handle	= "";
	this.ajax_handle	= "";
	this.ajax_timeout	= 5;
		
	
	
	// CREATE A HTML ID FROM A PLACE NUMBER (right to left, where 1 = ones, 2 = tens, 3 = hundreds, etc);
	this.create_html_id = function(place_num){
		return this.prefix + place_num;
	}
	
	// EXTRACT AN INTEGER VALUE FROM AN HTML ID (RIGHT TO LEFT) FROM AN HTML ID
	this.extract_digit = function(html_id){
		var digit = html_id.replace(this.prefix, '');
		return intVal(digit);
	}
	
	// ANIMATE AN HTML ID DIGIT 
	this.animate_one = function(html_id, digit){

		
		// MAKE SURE THE IMAGE HTML ID EXISTS
		var my_id = Dom.get(html_id);
		if(!my_id){
			return false;
		}
		
		
		
		var blur_src = this.digit_srcs['blur'];
		var digit_src= this.digit_srcs[digit];
		
		//alert(digit_src);
		
		// IF THIS HTML ID ALREADY HAS THIS SRC, SKIP IT
		if( my_id.src == digit_src ){
			return true;
		}
		
		
		// CHANGE TO BLUR BRIEFLY
		my_id.src = blur_src;
		
		// WAIT BRIEFLY AND CHANGE IT TO ITS NEW IMAGE     
		setTimeout(function(){my_id.src = digit_src}, 300);
		
		return true;
	}
	
	// UPDATE THE ODOMETER TO DISPLAY THE NEW NUMBER
	this.update_num = function(new_num){
		
		
		
		// SLOW IT DOWN A BIT
		if(this.last_num > 80000 && new_num > (this.last_num + 3)){
			new_num = intVal(this.last_num) + 3;	
		}
		
		var new_num = new_num + "";// convert to string if it is a number
		
		new_rev = new_num.reverse();
		new_rev = new_rev.split("");

		
		old_rev = this.last_num + "";
		old_rev = old_rev.reverse();
		old_rev = old_rev.split("");
		
		var tmpVar = '';
		var tmpImg = '';
		//console.log(new_rev);
		
		for(i = 0; i < this.places; i++){
			var digit = new_rev[i];
			
			// IF OLD AND NEW PLACE IS SAME, DON'T CHANGE
			//alert(digit + " " + old_rev[i]);
			if( digit === old_rev[i] && this.last_num != 0 ){
				continue;
			}
			
			
			
			// GET HTML ID OF THIS PLACE
			tmpVar = this.create_html_id(i);
			tmpImg = Dom.get(tmpVar);
			
			
			if( digit == undefined){
				digit = '_';
			}
			//alert(digit);
			this.animate_one(tmpImg, digit);
			
			// RESET LAST NUMBER VARIABLE
			this.last_num = new_num;			
			
		} 
		
	}
	
	// GET NEWER STREAM ELEMENTS                              
	this.get_num = function(){
		
		
		
		
		// IF WE ALREADY HAVE AN OPEN AJAX REQUEST, DO NOT SEND ANOTHER
		if( YAHOO.util.Connect.isCallInProgress(this.ajax_handle) ){
			return false;
		}		
		
					
		// UNIQUE NAME
		var uniqueID = uniqid();	
		
		// get older html via ajax
		var post_vars	 = "sg=main.ajax_crew_connections&cachebust=" + uniqueID;

		// start ajax request	
		this.startRequest = function() {
		   		this.ajax_handle = YAHOO.util.Connect.asyncRequest('GET', window.location.protocol+'//'+window.location.hostname+'/?'+post_vars, callback, post_vars );
		}			
		
				
		var callback =	{
			success: function(o) {
				if(o.responseText == ''){
					// DO NOTHING
					return false;
				}else{
					// MUST BE JSON RESPONSE
					try {
						var resp = YAHOO.lang.JSON.parse(o.responseText);  
					}
					catch(e) {	
						return false;
					}
					// If server said failure
					if(resp.success == 0){		
						// do nothing					
						return false;
						
					}else{			
					
					
						//waitingPanel.hide();
						if(YAHOO.lang.isObject(resp.customObj)){						
							
							this.update_num(resp.customObj.num_connections);
							
						}				
					}
				}
				
			},
			
			failure: function(o) {
			},
			timeout: 5000,
			scope: this

			
		};
		this.startRequest();
		
	}
	
	// START POLLING FOR NEWER STREAM ELEMENTS
	this.start_polling = function(){
		
			
		//alert(this.newer_polling_secs);
		this.polling_handle = YAHOO.lang.later(this.polling_secs*1000, this, this.get_num, null, true );
	}
	
	// STOP POLLING FOR NEWER STREAM ELEMENTS
	this.stop_polling = function(){
		if(YAHOO.lang.isObject(this.polling_handle)){
			this.polling_handle.cancel();
		}
	}
	
}


//########################################################################################################
////############# lib_ajax.js ########################################################################////

// DISPLAY AJAX PAGE CONTENT IN A MODAL POPUP
function popupAjaxContentDark(title,width,height,url,hide_close, is_modal){
	YAHOO.namespace("container");
	// SHORTCUT 
	Y 	= YAHOO.container;
	Dom	= YAHOO.util.Dom;
	D 	= YAHOO.util.Dom;
	P 	= YAHOO.widget.Panel;
	
	// DEFAULT WIDTH
	width = intVal(width);
	if(width < 20){
		width = 600;
	}
	// DEFAULT HEIGHT
	if(height != 'auto'){		
		height = intVal(height);
		if(height < 20){
			height = 100+'px';
		}else{
			height = height+'px';
		}
	}
	
	// close button?
	closebtn = (typeof(hide_close) != 'undefined' && hide_close == true) ? false : true;
	
	// modal?
	ismodal = (typeof(is_modal) != 'undefined' && is_modal == true) ? true : false;
	
	// UNIQUE NAME
	var uniqueID = uniqid();
	
	// CREATE A CONTAINER IN WHICH TO RENDER POPUP
	var el = document.createElement('div');
	el.id = 'popup-dark-'+uniqueID;
	document.body.appendChild(el);
	yui_el = Dom.get(el.id);
	
	// Instantiate a Panel from script
	Y[uniqueID] = new P("ajaxPanel"+uniqueID, { 
						width:width+"px",
						visible:false, 
						draggable:true, 
						close:closebtn, 
						iframe:true, 
						modal:ismodal,
						dragOnly:true, // improves cpu performance
						fixedcenter: "contained",
						autofillheight: "body"
						} );
	// shortcut
	Y[uniqueID].setHeader('<img src="/images/lay1/hd_dark_tracks.png" class="vmiddle"> '+title);
	Y[uniqueID].setBody('<div id="ajaxPanelBody'+uniqueID+'"><img src="/images/ajax-loader.gif">Loading...</div>');
	//Y.ajaxPanel.setFooter("End of Panel #2");
	Y[uniqueID].render(el.id);
	
	
	// SET STYLES
	D.setStyle('ajaxPanelBody'+uniqueID+'', 'height', height);  
	D.setStyle('ajaxPanelBody'+uniqueID+'', 'overflow', 'auto'); 
	D.addClass(el.id, 'bd-dark');
	
	
	
	 
	Y[uniqueID].show();
	
	var callback = {
		success: function(o) {
			if(o.responseText == ''){
				Y[uniqueID].setBody('<div id="ajaxPanelBody'+uniqueID+'">An error was encountered while retrieving this information.</div>');
			}else{				
				Y[uniqueID].setBody('<div id="ajaxPanelBody'+uniqueID+'">'+o.responseText+'</div>');
				YAHOO.util.Dom.setStyle('ajaxPanelBody'+uniqueID+'', 'height', height);  
				YAHOO.util.Dom.setStyle('ajaxPanelBody'+uniqueID+'', 'overflow', 'auto');  
			}
			
		},
		
		failure: function(o) {
			Y[uniqueID].setBody('<div id="ajaxPanelBody'+uniqueID+'">An error was encountered while contacting theFOAT.com.</div>');
		}
		
	};
	
	// FILL BODY WITH CONTENT
	YAHOO.util.Connect.asyncRequest('POST', url, callback );
	
	// return handl on panel element
	return Y[uniqueID];
}

// FUNCTION TO ALTERNATE VISIBILITY OF TABS/DIVS
function tabChange(active_tab_id,all_tab_ids){
	// naming convention: button for a tab will have the same ID name with -btn added.  e.g. mytab1, mytab1-btn
	var all_array		= all_tab_ids.split(",");
	var tmpName		= "";
	var tmpBtnName	= "";
	if(typeof(all_array) == 'object'){
		var len	= all_array.length;
		var i 	= 0;
		for ( i=0; i<len; ++i ){
		  tmpName		= all_array[i];
		  tmpBtnName	= all_array[i]+'-btn';
		  if(all_array[i] == active_tab_id){
		  	YAHOO.util.Dom.addClass(tmpBtnName, 'submit');
			YAHOO.util.Dom.addClass(tmpName, 'block');
			YAHOO.util.Dom.removeClass(tmpBtnName, 'button');
			YAHOO.util.Dom.removeClass(tmpName, 'hidden');
		  }else{
		  	YAHOO.util.Dom.addClass(tmpBtnName, 'button');
			YAHOO.util.Dom.addClass(tmpName, 'hidden');
			YAHOO.util.Dom.removeClass(tmpBtnName, 'submit');
			YAHOO.util.Dom.removeClass(tmpName, 'block');
		  }
		}
	}
}
// FUNCTION TO AUTO-ROTATE TABS UNTIL ONE IS CLICKED
function tabRotate(all_tab_ids, max_rotations){
	if(max_rotations == 'undefined' || typeof(window.thisTabRotation) != 'number'){
		max_rations = 3;
		window.thisTabRotation = 0;
	}
	// if told to stop, stop;
	if(window.stopTabRotate != 'undefined' && window.stopTabRotate == true || window.thisTabRotation > max_rotations){
		clearInterval(window.tabRotateInterval);
		return false;	
	}
	// if next tab is not set, set it
	if(window.nextTabID == 'undefined' || typeof(window.nextTabID) != 'number'){
		window.nextTabID = 1;
	}
	// if is already set, increase it by 1
	else{
		window.nextTabID = window.nextTabID + 1;	
	}
	// split up the all_tab_ids into an array
	var all_array = all_tab_ids.split(",");
	if(typeof(all_array) == 'object'){
		var len	= all_array.length;
		// if this is an array
		if(len > 0){
			// if the nextTabID is larger than the array, reset to 0
			if(window.nextTabID >= len){
				window.nextTabID = 0;
				window.thisTabRotation = window.thisTabRotation + 1;
			}	
			var next = all_array[window.nextTabID];
			tabChange(next,all_tab_ids);
			return true;
		}
	}
}



// REPORT A PAGE AS INAPPROPRIATE - THIS WILL GO ON EVERY PAGE
YAHOO.namespace("reportPageContainer");
function initReportPage() {	
	// MAKE SURE THE CONTAINER DIV IS THERE
	var reportContainerObj = getID('reportPageContainer');
	if(typeof(reportContainerObj) != 'object'){
		return false;	
	}
	var handleYesReportPage = function() {
		reportPage();
		this.hide();
	};
	var handleNoReportPage = function() {
		this.hide();
	};
	YAHOO.reportPageContainer.reportPageDialog = new YAHOO.widget.SimpleDialog("reportPageDialog", 
	{ 
		width: "350px",
		fixedcenter: true,
		visible: false,
		draggable: true,
		text: "Do you want to report this page as inappropriate?",
		close: true,
		icon: YAHOO.widget.SimpleDialog.ICON_HELP,
		constraintoviewport: true,
		buttons: [ { text:"Yes", handler:handleYesReportPage, isDefault:true },
				  { text:"No",  handler:handleNoReportPage } ]
	} );
	YAHOO.reportPageContainer.reportPageDialog.setHeader("Are you sure?");
	YAHOO.reportPageContainer.reportPageDialog.render("reportPageContainer");
}
YAHOO.util.Event.addListener(window, "load", initReportPage);

function reportPage(){
	var poststr = "sg=main.ajax_report_page";
	var callback = {
		success: function(o) {
			if(o.responseText == ''){
				alert('Report Failed!');
			}else{
				// MUST BE JSON RESPONSE
				try {
					var resp = YAHOO.lang.JSON.parse(o.responseText);  
				}
				catch(e) {				
					waitingPanel.hide();
					alert('Invalid Response from Server');
					return false;
				}
				// If server said failure
				if(resp.success == 0){
					waitingPanel.hide();
					alert(resp.message);
					return false;
					
				}else{					
					waitingPanel.hide();
					alert("Report successful");
				}
			}
			
		},
		
		failure: function(o) {
			alert('EMBED failed');
		}
		
	};
	// initiate a new waiting panel (use "window.xxx" so we can hide it from outside of this function);
	window.waitingPanel = new panelLoading('Reporting page.  Please wait...<br />[<a href="#" onClick="stopIt();waitingPanel.hide()">Stop</a>]');
	// Show the Panel
	waitingPanel.show();
	// start ajax request
	YAHOO.util.Connect.asyncRequest('POST', 'index.php', callback, poststr );
}

// function to retrieve the value of a radio button
function get_radio_value(fieldRef){
	if(!fieldRef || fieldRef.length == 'undefined'){
		return false;	
	}
	my_field = fieldRef;
	for (var i=0; i < my_field.length; i++){
		if (my_field[i].checked){
			var rad_val = my_field[i].value;
		}
	}
	return rad_val;
}

// COPY TO CLIPBOARD
function copyToClipboard(text2copy) {
  if (window.clipboardData) {
    window.clipboardData.setData("Text",text2copy);
  } else {
    var flashcopyvar = 'flashcopier';
    if(!document.getElementById(flashcopyvar)) {
      var divholder = document.createElement('div');
      divholder.id = flashcopyvar;
      document.body.appendChild(divholder);
    }
    document.getElementById(flashcopyvar).innerHTML = '';
    var divinfo = '<embed src="/_clipboard.swf" FlashVars="clipboard='+encodeURIComponent(text2copy)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
    document.getElementById(flashcopyvar).innerHTML = divinfo;
  }
}

// parse a number into money format
function formatAsMoney(mnt) {
    mnt -= 0;
    mnt = (Math.round(mnt*100))/100;
    return (mnt == Math.floor(mnt)) ? mnt + '.00' 
              : ( (mnt*10 == Math.floor(mnt*10)) ? 
                       mnt + '0' : mnt);
}


// FUNCTION TO DETERMINE IF A global VARIABLE ISSET
function isset(varname){
  return(typeof(window[varname])!='undefined');
}

// FUNCTION TO ADD FAVORITE VIA AJAX
function favoriteAdd(type_id,encrypted_profile_id,var_id){
	var poststr = "sg=main.ajax_favorite_add&type_id=" + intVal(type_id) + "&member_id=" + encrypted_profile_id + "&var_id=" + var_id;
	var callback = {
		success: function(o) {
			if(o.responseText == ''){
				alert('Favorite Add Failed!');
			}else{
				// MUST BE JSON RESPONSE
				try {
					var resp = YAHOO.lang.JSON.parse(o.responseText);  
				} catch(e) {				
					waitingPanel.hide();
					//alert('Invalid Response from Server');
					alert(o.responseText);
					return false;
				}
				// If server said failure
				if(resp.success == 0){
					waitingPanel.hide();
					alertVar(resp.errors);
					return false;					
				}else{			
					waitingPanel.hide();
					alert("Favorite added");
				}
			}			
		},		
		failure: function(o) {
			alert('Add favorite failed');
		}		
	};
	// initiate a new waiting panel (use "window.xxx" so we can hide it from outside of this function);
	window.waitingPanel = new panelLoading('Adding Favorite.  Please wait...<br />[<a href="#" onClick="stopIt();waitingPanel.hide()">Stop</a>]');
	// Show the Panel
	waitingPanel.show();
	// start ajax request
	YAHOO.util.Connect.asyncRequest('POST', 'index.php', callback, poststr );
}
// FUNCTION TO DELETE FAVORITE VIA AJAX
function favoriteDelete(favorite_id){
	var poststr = "sg=main.ajax_favorite_delete&favorite_id=" + intVal(favorite_id);
	var callback = {
		success: function(o) {
			if(o.responseText == ''){
				alert('Favorite Delete Failed!');
			}else{
				// MUST BE JSON RESPONSE
				try {
					var resp = YAHOO.lang.JSON.parse(o.responseText);  
				} catch(e) {				
					waitingPanel.hide();
					alert(o.responseText);
					return false;
				}
				// If server said failure
				if(resp.success == 0){
					waitingPanel.hide();
					return false;					
				}else{			
					waitingPanel.hide();
					alert("Favorite Deleted");
				}
			}			
		},		
		failure: function(o) {
			alert('Delete favorite failed');
		}		
	};
	// initiate a new waiting panel (use "window.xxx" so we can hide it from outside of this function);
	window.waitingPanel = new panelLoading('Deleting Favorite.  Please wait...<br />[<a href="#" onClick="stopIt();waitingPanel.hide()">Stop</a>]');
	// Show the Panel
	waitingPanel.show();
	// start ajax request
	YAHOO.util.Connect.asyncRequest('POST', 'index.php', callback, poststr );
}






// FUNCTION TO EMBED STYLES PULLED FROM AJAX *************** CAUSES ERROR IN IE7!!!!! ***************************
function applyStyles(rawHTML) {
	if (YAHOO.env.ua.gecko > 0) return;
	var headEl = null; // lazy-load
	
	// find all styles in the string
	var styleFragRegex = '<style[^>]*>([\u0001-\uFFFF]*?)</style>';
	var matchAll = new RegExp(styleFragRegex, 'img');
	var matchOne = new RegExp(styleFragRegex, 'im');
	
	var styles = (rawHTML.match(matchAll) || []).map(function(tagMatch) {  
		return (tagMatch.match(matchOne) || ['', ''])[1];
	});

	// add all found style blocks to the HEAD element.
	for (i = 0; i < styles.length; i++) {
		if (!headEl) {
			headEl = document.getElementsByTagName('head')[0];
			if (!headEl){
				return;
			}
		}
		var newStyleEl = document.createElement('style');
		newStyleEl.type = 'text/css';
		if (YAHOO.env.ua.ie > 0){
			newStyleEl.styleSheet.cssText = styles[i];
		} else {
			var cssDefinitionsEl = document.createTextNode(styles[i]);
			newStyleEl.appendChild(cssDefinitionsEl);
		}
		headEl.appendChild(newStyleEl);
	}
}




// FUNCTION TO COPY AN OBJECT, AS OPPOSED TO CREATING A REFERENCE TO IT
function CloneObject(inObj) {
	for (i in inObj){
		this[i] = inObj[i];
	}
} // Usage:x = new CloneObject(obj);


// FUNCTION TO DETERMINE IF AN IMAGE DIMENSIONS HAVE LOADED
function imageLoaded(img){
	if(typeof(img.width) == 'undefined'){
		return false;	
	}
	if(img.width > 0){
		return true;
	}
	return false;
	
}

// FUNCTION TO ZOOM IN AN IMAGE OR AN IMAGE ROOTED TO AN OBJECT
function zoomin(myObj,mySrc,closeOnMouseOut, rounded_corners, title){
	if(typeof(window.zoomCounter) == 'undefined'){
		window.zoomCounter = 0;	
	}
	if(typeof(zoomin_img) == 'undefined'){
		window.zoomin_img 	= new Image();
	}
	if(typeof(mySrc) != 'undefined' && mySrc != ''){
		zoomin_img.src = mySrc;
	}else{
		zoomin_img.src = myObj.src;
	}
	this.doit = function(){
		zoomin(myObj,mySrc,closeOnMouseOut, rounded_corners, title);
	}
	//alertVar(img);
	// if we don't have the width yet, error out
	if(zoomin_img.height == 0){
		if(window.zoomCounter > 10){
			return;	
		}
		window.zoomCounter=window.zoomCounter+1;
		
		setTimeout(this.doit,500);
		
		
		return;
	}
	zoomin2(myObj,mySrc,zoomin_img,closeOnMouseOut, rounded_corners, title);
}

function zoomin2(myObj,mySrc,img,closeOnMouseOut, rounded_corners, title){	
		YAHOO.namespace("container");
		var width2	= img.width + 20;
		var height2	= img.height + 41;
		var xy2 = YAHOO.util.Dom.getXY(myObj);   
		var omo = "";
		ttl = "&nbsp;";
		if (YAHOO.lang.isValue(title) && YAHOO.lang.trim(title) != "") {
			ttl = title;
		}
		if(typeof(closeOnMouseOut) != 'undefined'){
				omo = ' onMouseOut="YAHOO.container.panel100.hide()" ';
		}
		xy2[0] -= 2;
		xy2[1] -= 2;
		// if it already exists, set it to small dimensions so it will always expand
		if(YAHOO.lang.isObject(YAHOO.container.panel100)){
			YAHOO.container.panel100.cfg.setProperty('width','20px');
			YAHOO.container.panel100.cfg.setProperty('xy',xy2);
			YAHOO.container.panel100.cfg.setProperty('zIndex',1000);
		}else{
			// Instantiate a Panel from script 
			YAHOO.container.panel100 = new YAHOO.widget.Panel("panel100", { 
											  xy:xy2, 
											  zIndex:1000, 
											  width:30, 
											  iframe:true, 
											  visible:false, 
											  draggable:true, 
											  constraintoviewport:false, 
											  close:true 
											  } 
										);
		}
		YAHOO.container.panel100.setHeader(ttl);
		if (YAHOO.lang.isValue(rounded_corners)) {
			YAHOO.container.panel100.setHeader('<div class="tl"></div><span>'+ttl+'</span><div class="tr"></div>');
		}
		//YAHOO.example.container.panel100.setHeader("Panel #2 from Script");
		YAHOO.container.panel100.setBody('<img id="panel100Img" src="'+ img.src +'" style="width:20px; height:20px"  onClick="YAHOO.container.panel100.hide()" '+omo+' />');
		//YAHOO.example.container.panel100.setFooter("End of Panel #2");
		YAHOO.container.panel100.render("container");
		YAHOO.container.panel100.show();
		var expandPanel = new YAHOO.util.Anim('panel100', {   
			width: { to: width2 },
			height: { to: height2 }
		}, 0.5, YAHOO.util.Easing.easeOut);   
		var expandPanelImg = new YAHOO.util.Anim('panel100Img', {   
			width: { to: img.width },
			height: { to: img.height }
		}, 0.5, YAHOO.util.Easing.easeOut);   
		expandPanel.animate();
		expandPanelImg.animate();
		
		// clear out global variable set in zoomin() so we don't get stuck with first image's dimension
		window.zoomin_img.width = 0;// hack for IE.
		//window.zoomin_img.height = 0;// hack for IE.
		
		// we have to delete the zoomin_img for firefox, but IE won't allow a window property to be deleted, so we surround it in a try/catch to hide the error thrown by ie
		try{
			delete(window.zoomin_img);
		}catch(err) {
			
		}
		
		
	
}
// FUNCTION TO ZOOM IN AN IMAGE OR AN IMAGE ROOTED TO AN OBJECT
function zoominCornered(myObj,mySrc,closeOnMouseOut){
	if(typeof(window.zoomCounter) == 'undefined'){
		window.zoomCounter = 0;	
	}
	if(typeof(zoomin_img) == 'undefined'){
		window.zoomin_img 	= new Image();
	}
	if(typeof(mySrc) != 'undefined' && mySrc != ''){
		zoomin_img.src = mySrc;
	}else{
		zoomin_img.src = myObj.src;
	}
	this.doit = function(){
		zoomin(myObj,mySrc,closeOnMouseOut);
	}
	//alertVar(img);
	// if we don't have the width yet, error out
	if(zoomin_img.height == 0){
		if(window.zoomCounter > 10){
			return;	
		}
		window.zoomCounter=window.zoomCounter+1;
		
		setTimeout(this.doit,500);
		
		
		return;
	}
	zoomin3(myObj,mySrc,zoomin_img,closeOnMouseOut);
}


function zoomin3(myObj,mySrc,img,closeOnMouseOut){	
		YAHOO.namespace("container");
		var width2	= img.width + 20;
		var height2	= img.height + 41;
		var xy2 = YAHOO.util.Dom.getXY(myObj);   
		var omo = "";
		if(typeof(closeOnMouseOut) != 'undefined'){
				omo = ' onMouseOut="YAHOO.container.panel100.hide()" ';
		}
		xy2[0] -= 2;
		xy2[1] -= 2;
		// if it already exists, set it to small dimensions so it will always expand
		if(YAHOO.lang.isObject(YAHOO.container.panel200)){
			YAHOO.container.panel200.cfg.setProperty('width','20px');
			YAHOO.container.panel200.cfg.setProperty('xy',xy2);
			YAHOO.container.panel200.cfg.setProperty('zIndex',1000);
		}else{
			// Instantiate a Panel from script 
			YAHOO.container.panel200 = new YAHOO.widget.Panel("panel200", { 
											  xy:xy2, 
											  zIndex:1000, 
											  width:30, 
											  iframe:true, 
											  visible:false, 
											  draggable:true, 
											  constraintoviewport:false, 
											  close:true 
											  } 
										);
		}
		
		//YAHOO.example.container.panel100.setHeader("Panel #2 from Script");
		YAHOO.container.panel200.setBody('<img id="panel100Img" src="'+ img.src +'" style="width:20px; height:20px"  onClick="YAHOO.container.panel100.hide()" '+omo+' />');
		//YAHOO.example.container.panel100.setFooter("End of Panel #2");
		YAHOO.container.panel200.render("container");
		YAHOO.container.panel200.setHeader('<div class="tl"></div><span>&nbsp;</span><div class="tr"></div>');
		
		
		// SINCE WE WANT ROUNDED CORNERS, WE HAVE TO SET THEM UP AFTER IT'S RENDERED, OR THE BUTTONS WILL OVERWRITE THE FOOTER
		var divBL = document.createElement("div");
		var divBR = document.createElement("div");
		divBL.className = "bl";
		divBR.className = "br"
		YAHOO.container.panel200.appendToFooter(divBL);
		YAHOO.container.panel200appendToFooter(divBR);
		YAHOO.container.panel200.show();
		var expandPanel = new YAHOO.util.Anim('panel200', {   
			width: { to: width2 },
			height: { to: height2 }
		}, 0.5, YAHOO.util.Easing.easeOut);   
		var expandPanelImg = new YAHOO.util.Anim('panel200Img', {   
			width: { to: img.width },
			height: { to: img.height }
		}, 0.5, YAHOO.util.Easing.easeOut);   
		expandPanel.animate();
		expandPanelImg.animate();
		
		// clear out global variable set in zoomin() so we don't get stuck with first image's dimension
		window.zoomin_img.width = 0;// hack for IE.
		//window.zoomin_img.height = 0;// hack for IE.
		
		// we have to delete the zoomin_img for firefox, but IE won't allow a window property to be deleted, so we surround it in a try/catch to hide the error thrown by ie
		try{
			delete(window.zoomin_img);
		}catch(err) {
			
		}
		
		
	
}
// Simple get ajax and put it in a DHTML popup
var modalPopupFromWeb = function( width, height, ajax_url, post_vars, resize  ){
	
	
	// REQUIRE YAHOO YUI CONNECTION MANAGER
	var Connector = YAHOO.util.Connect;
	if( typeof(Connector) != 'object'){
		alert('The connection manager failed to load. Please reload the page.');
		return false;
	}
	
	// Declare the div replace function
	var handleSuccess = function(o){
		if(o.responseText !== undefined){			
			// PUT THE RESPONSE IN A POPUP DIV
			modalPopup(width,height,o.responseText, resize);			
		}
	}
	// AJAX QUERY FAILURE FUNCTION
	var handleFailure = function(o){
		if(o.responseText !== undefined){
			myDiv.innerHTML = "<li>Transaction id: " + o.tId + "</li>";
			myDiv.innerHTML += "<li>HTTP status: " + o.status + "</li>";
			myDiv.innerHTML += "<li>Status code message: " + o.statusText + "</li>";
		}
	}
	
	var callback ={
	  cache:false ,
	  success:handleSuccess,
	  failure: handleFailure,
	  argument: { /*field:arrFields[i], loopId:i*/ }
	};
	
	var request = Connector.asyncRequest('POST', ajax_url, callback, post_vars);
	return;	
}
function modalPopup(width,minHeight,txtBody,txtUrl,resize_it){	
		YAHOO.namespace("example.container");
		var width2	= width ;
		var height2	= minHeight + 30;
		var xy2 = new Array;
		xy2[0] = Math.floor(width/2);
		xy2[1] = 100;
		// if it already exists, set it to small dimensions so it will always expand
		if(typeof(YAHOO.example.container.panel100) == 'object'){
			YAHOO.example.container.panel100.cfg.setProperty('width',width);
			//YAHOO.example.container.panel100.cfg.setProperty('height',height2);
			//YAHOO.example.container.panel100.cfg.setProperty('xy',xy2);
			YAHOO.example.container.panel100.cfg.setProperty('fixedcenter',true);  
		}else{
			// Instantiate a Panel from script 
			YAHOO.example.container.panel100 = new YAHOO.widget.Panel("panel100", { 
													width:width2, 
													autofillheight:body, 
													visible:false, 
													draggable:true, 
													constraintoviewport:false, 
													close:true, 
													fixedcenter:false 
													} 
												);
		}
		//YAHOO.example.container.panel100.setHeader("Panel #2 from Script");
		YAHOO.example.container.panel100.setBody(txtBody);
		//YAHOO.example.container.panel100.hide()
		//YAHOO.example.container.panel100.setFooter("End of Panel #2");
		YAHOO.example.container.panel100.render("container");
		YAHOO.example.container.panel100.show();
		if(resize_it==true){
			var expandPanel = new YAHOO.util.Anim('panel100', {   
				width: { from:30, to: getID('panel100').clientWidth },
				height: { from:30, to: getID('panel100').clientHeight } // readjust hight to whatever is set in the body dynamically
			}, 0.5, YAHOO.util.Easing.easeOut);   
		}else{
			var expandPanel = new YAHOO.util.Anim('panel100', {   
				width: { from:30, to: width }
			}, 0.5, YAHOO.util.Easing.easeOut);
		}
		expandPanel.animate();
		YAHOO.example.container.panel100.cfg.setProperty('height',getID('panel100').clientHeight);
}



// FUNCTION TO STOP UPLOAD
function stopIt(){
	if(YAHOO.util.Connect.isCallInProgress(oConnect)) {
		YAHOO.util.Connect.abort(oConnect);
	}
}
// CLASS FOR RATINGS
function ratingClass(wrapperID, formID, ratingVarID, FID_arr, messages_arr, messageID, initialRating, display_only){
	var i = 0;
	// FUNCTION TO CHECK INITIAL VALUES
	this.init = function(){
		// preload images
		this.picFull		= new Image(14,16); 
  		this.picFull.src	= "/images/f-16.gif";
		this.picHalf		= new Image(14,16); 
  		this.picHalf.src	= "/images/f-16-half.gif";
		this.picEmpty		= new Image(14,16); 
  		this.picEmpty.src	= "/images/f-16-faded.gif";
		
		// if no message div id, error out
		this.messageHandle = getID(messageID);
		if(this.messageHandle == null && display_only != 1){
			this.is_ok = false;
			return false;
		}
		// if no wrapper div id, error out
		this.wrapperHandle = getID(wrapperID);
		if(this.wrapperHandle == false){
			this.messageHandle.innerHTML = 'No wrapper id';			
			this.is_ok = false;
			return false;
		}
		// if no form id, error out
		this.formHandle	= getID(formID);
		if(this.formHandle == false && display_only != 1){
			this.messageHandle.innerHTML = 'No Form';
			this.is_ok = false;
			return false;
		}
		// if no rating form variable id, error out
		this.ratingVarID = getID(ratingVarID);
		if(this.ratingVarID == false && display_only != 1){
			this.messageHandle.innerHTML = 'No Form Rating Variable';
			this.is_ok = false;
			return false;
		}
		// if f-image id's are not set, error out
		if(typeof(FID_arr) != 'object'){
			this.messageHandle.innerHTML = 'No Image IDs';
			this.is_ok = false;
			return false;
		}else{
			this.fs = new Array(5);
			for(i=0; i<5; i++){
				this.fs[i] = getID(FID_arr[i]);
				if(this.fs[i] == false){
					this.is_ok = false;
					return false;
				}
			}
		}
		// if no messages are specified for each f-level, set them to blank
		if(typeof(messages_arr) != 'object'){
			this.messages = ['','','','',''];
		}else{
			this.messages = messages_arr;
		}
		// set initial rating
		this.initialRating = floatVal(initialRating);
		
		// use this variable to run/not run other functions when called// is there an easier way??
		this.is_ok = true; 
		
		// set it to initial value
		this.clear();
		
	}
	
	// function to use the display div to show a message
	this.showMsg = function(msg){
		if(this.is_ok != true || typeof(msg) == 'undefined'){
			return false;
		}
		this.messageHandle.innerHTML = msg;
	}
	
	// Function  to show the "f's"
	this.showFs = function(num_fs, show_messages){
		// if init didn't work well, exit		
		if(this.is_ok != true){
			return;// TODO: isn't there a more elegant way to do this???
		}
		if(typeof(show_messages) == 'undefined'){
			var show_messages = false;
		}
		// set all to empty
		num_fs = floatVal(num_fs);
		this.fs[0].src = this.fs[1].src = this.fs[2].src = this.fs[3].src = this.fs[4].src = this.picEmpty.src;
		for(i=1; i<=5; i++){
			if(num_fs >= i-0.75){
				this.fs[i-1].src = this.picHalf.src;
				if(show_messages == true){
					this.showMsg(this.messages[i-1]);
				}else{
					this.showMsg('');
				}
			}
			if(num_fs >= i-0.25 ){
				this.fs[i-1].src = this.picFull.src;
				if(show_messages == true){
					this.showMsg(this.messages[i-1]);
				}else{
					this.showMsg('');
				}
			}
		}		
	}
	
	// Function to disable this until the next page load
	this.disable = function(){this.is_ok=false;return true;}
	
	// Function to set it to default value
	this.clear = function() {this.showFs(this.initialRating);return true;}
	
	// Function to make vote via Ajax
	this.vote = function(num_fs){
		// if init didn't work well, exit		
		if(this.is_ok != true){
			return;// TODO: isn't there a more elegant way to do this???
		}
		var p = this; // get a handle on the parent class
		// set the form element value to the rating integer
		this.ratingVarID.value = intVal(num_fs);
		// (the "true" tells Connection Manager this is a file upload form
		YAHOO.util.Connect.setForm(formID, true);	
		this.callback = {		  
			upload: function(o) {
				if(o.responseText == ''){
					alert('Rating Failed!');
				}else{
					// MUST BE JSON RESPONSE
					try {
						var resp = YAHOO.lang.JSON.parse(o.responseText);  
					}catch(e) {
						waitingPanel.hide();
						//alert('Invalid Response from Server');
						alert(o.responseText);
						return false;
					}
					// If failure, show error.
					if(resp.success == 0){
						waitingPanel.hide();
						alertVar(resp.errors);
						return false;
					}else{
						o.argument.showFs();
						o.argument.disable();
						waitingPanel.hide();
					}	
				}
			},
			failure: function(o){
				alert('Rating Failed');
			},
			argument: {
				disable:function(){
					p.disable();
				},
				showFs:function(){
					p.showFs(num_fs,false);
				}
			}
		};		
		// initiate a new waiting panel (use "window.xxx" so we can hide it from outside of this function);
		window.waitingPanel = new panelLoading('Adding your rating.  Please wait...<br />[<a href="#" onClick="stopIt();waitingPanel.hide()">Stop</a>]');
		// Show the Panel
		waitingPanel.show();		
		// Perform Upload Call
		window.oConnect = YAHOO.util.Connect.asyncRequest('POST', 'index.php', this.callback);
	}
}

// function to trim off white space from front and back of a string
function trim (str) {
	if(typeof(str) == 'undefined'){
		return '';	
	}
	var	str = str.replace(/^\s\s*/, ''),
		ws = /\s/,
		i = str.length;
	while (ws.test(str.charAt(--i)));
	return str.slice(0, i + 1);
}


// FUNCTION TO EXECUTE SCRIPTS IN MIXED HTML AJAX RESPONSES (BETWEEN < SCRIPT></ SCRIPT>)
var evaluateJs = function(obj)
{
	
	window.jsCode = new Array();
	var scriptTags = obj.getElementsByTagName('SCRIPT');
	var head = document.getElementsByTagName('HEAD')[0];
	for(var no=0;no<scriptTags.length;no++){                  
		if (scriptTags[no].src){
			var head = document.getElementsByTagName("head")[0];
			var scriptObj = document.createElement("script");            
			scriptObj.setAttribute("type", "text/javascript");
			scriptObj.setAttribute("src", scriptTags[no].src);             
			head.appendChild(scriptObj);
	
		}else{                      
				var code = scriptTags[no].innerHTML;                        
				window.jsCode[no] = code;
				setTimeout('eval(window.jsCode[' + no + '])',200);      // Has to wait because we want to make all objects part of the window object(global variables) instead of locale
		}            
	}      
}
var evaluateJsDiv = function(divID)
{
	var obj = YAHOO.util.Dom.get(divID);

	
	window.jsCode = new Array();
	var scriptTags = obj.getElementsByTagName('SCRIPT');
	var head = document.getElementsByTagName('HEAD')[0];
	for(var no=0;no<scriptTags.length;no++){                  
		if (scriptTags[no].src){
			var head = document.getElementsByTagName("head")[0];
			var scriptObj = document.createElement("script");            
			scriptObj.setAttribute("type", "text/javascript");
			scriptObj.setAttribute("src", scriptTags[no].src);             
			head.appendChild(scriptObj);
	
		}else{                      
				var code = scriptTags[no].innerHTML;                        
				window.jsCode[no] = code;
				setTimeout('eval(window.jsCode[' + no + '])',200);      // Has to wait because we want to make all objects part of the window object(global variables) instead of locale
		}            
	}      
}



// FUNCTION TO CHECK OR UNCHECK A CHECKBOX BY ID
function check_box(box_id,is_checked){
	if(is_checked != null && is_checked == true){
		var check_it = true;	
	}else{
		var check_it = false;	
	}
	YAHOO.util.Dom.id(box_id).checked = check_it;
}

// FUNCTION TO ALERT ERRORS, STRING OR ARRAY/OBJECT
function alertVar(my_var,show_keys){
	if(my_var == null){
		return false;	
	}	
	if(typeof(my_var) == 'string' || typeof(my_var) == 'number'){
		alert(my_var);	
	}else if(typeof(my_var) == 'object'){
		my_str = '';
		for(i in my_var){
			if(typeof(i) == 'string' || typeof(my_var) == 'number'){
				//
				if(typeof(show_keys) != 'undefined' && show_keys == true){
					my_str += "\n["+i+"] = "+my_var[i] + "(" + typeof(my_var[i]) + ")<br>";
				}
				//my_str += "\n"+ i +'->'+my_var[i] + "<br>"; // shows key and arrow to value
				my_str += "\n"+my_var[i] ; // shows just value
			}else if(typeof(i) == 'object'){
				for(j in my_var){
					if(typeof(show_keys) != 'undefined' && show_keys == true){
						my_str += "\n["+i+"]["+j+"] = "+my_var[i][j] + "(" + typeof(my_var[i][j]) + ")<br>";
					}
					my_str += "\n"+my_var[i][j] + "<br>";
				}
			}
		}
		alert(my_str);
	}
}

// FUNCTION TO REPLACE ALERT WITH YUI DIALOG BOX
/*(function() {
    YAHOO.namespace('widget.alert');

    alert_old = window.alert;
    window.alert = function(str) {
        YAHOO.widget.alert.dlg.setBody(str);
        YAHOO.widget.alert.dlg.cfg.queueProperty('icon', YAHOO.widget.SimpleDialog.ICON_WARN);
        YAHOO.widget.alert.dlg.cfg.queueProperty('zIndex', 9999);
        YAHOO.widget.alert.dlg.render(document.body);
        if (YAHOO.widget.alert.dlg.bringToTop) {
            YAHOO.widget.alert.dlg.bringToTop();
        }
        YAHOO.widget.alert.dlg.show();
    };


    YAHOO.util.Event.on(window, 'load', function() {

        var handleOK = function() {
            this.hide();
        };

        YAHOO.widget.alert.dlg = new YAHOO.widget.SimpleDialog('widget_alert', {
            visible:false,
            width: '800px',
            zIndex: 9999,
            close: false,
            fixedcenter: true,
            modal: false,
			iframe: true,
            draggable: true,
            constraintoviewport: true, 
            icon: YAHOO.widget.SimpleDialog.ICON_WARN,
            buttons: [
                { text: 'OK', handler: handleOK, isDefault: true }
                ]
        });
        YAHOO.widget.alert.dlg.setHeader("Alert!");
        YAHOO.widget.alert.dlg.setBody('Alert body passed to window.alert'); // Bug in panel, must have a body when rendered
        YAHOO.widget.alert.dlg.render(document.body);
    });
})();*/



// CROSS BROWSER GET ID
function getID(id){
	myID = YAHOO.util.Dom.get(id);
	/*if (document.getElementById){
		// this is the way the standards work
		var myID = document.getElementById(id);
	}else if (document.all)	{
		// this is the way old msie versions work
		var myID = document.all[id];
	}else if (document.layers)	{
		// this is the way nn4 works
		var myID = document.layers[id];
	}*/
	if(!myID){
		return false;
	}else{
		return myID;	
	}
}

// GENERAL AJAX-GENERATED SELECT FIELD
function getSelectOptions(field_name, selected_value, ajax_url, post_vars, no_any, just_values){

	/*
		VARIABLES DESCRIPTION
		field_name			= The id="xx" && name="xx" in the <select> tag
		selected_value	= the value to check the options against; a match will make an option selected
		ajax_url		= the html url which we will post to to get the options object
		post_vars		= the variables we will pass to ajax_url (whatever that server script needs)
		no_any			= if not false, then print the "Any" option
		just_values		= if not false, then return the return object and don't modify any fields
		
	*/
	var x = '';
	
	// REQUIRE YAHOO YUI CONNECTION MANAGER
	var Connector = YAHOO.util.Connect;
	if( typeof(Connector) != 'object'){
		alert('The connection manager failed to load. Please reload the page.');
		return false;
	}
	
	
	
	// NEXT, MAKE SURE ALL REQUIRED VARIABLES WERE PASSED
	if(	typeof(field_name) 			!= 'string') { x += "html_id\n"; }
	if(	typeof(selected_value)	 	!= 'string') { x += "selected_value\n"; }
	if(	typeof(ajax_url)	 		!= 'string') { x += "ajax_url\n"; }
	if(	typeof(post_vars) 			!= 'string') { x += "post_vars\n"; }
	if( x.length != 0 ){
		var strAlert = "getSelectOptions Error: \n\nThe following object variables must be created: ";
		strAlert 	+= "\n\n" +x;
		alert(strAlert);
		return false;
	}
	x = '';
	
	
	// NEXT, MAKE SURE select_div_id exists
	var myField = YAHOO.util.Dom.get(field_name);
	if(!myField){
		alert("Field ID '"+field_name+"' does not exist.");
		return false;	
	}
	// set values back to only 1 by default
	if(just_values === undefined || just_values == false){
		if(no_any !== undefined && no_any != false){
			myField.options.length = 0;
		}else{
			myField.options.length = 0;	
		}
	}
	
	// SET OPTIONS TO TEMPORARILY SAY ... LOADING...
	myField.options[0] = new Option('...LOADING...', '', false, false);
	
	
	// AJAX QUERY SUCCESS FUNCTION
	var handleSuccess = function(o){
		if(o.responseText !== undefined){
			// set values back to only 1 by default
			if(just_values === undefined || just_values == false){
				if(no_any !== undefined && no_any != false){
					myField.options.length = 0;
				}else{
					myField.options.length = 1;	
				}
			}
			if(no_any === undefined || no_any == false){
				m = 1;
				// put in a default "any" option
				myField.options[0] = new Option("Any", '', false, false);
			}else{
				m = 0;	
			}
			// evaluate response text into an array object
			//var resp = eval('(' + o.responseText + ')');
			var resp = YAHOO.lang.JSON.parse(o.responseText);
			
			// make sure response is actually an object
			if(resp == null){
				return false;
			}
			
			if(just_values !== undefined && just_values != false){
				return resp;
			}
			var rLength = resp.length;
			
				
			// loop through results
			var sel = '';
			for(j=0; j<rLength; j++){
				if(resp[j].value == selected_value && resp[j].value != null){
					sel 		= true;
				}else{
					sel			= false;
				}
				myField.options[j+m] = new Option(resp[j].description, resp[j].value, false, sel);
				
			}
			enableField(field_name);
		}
	}
	
	// AJAX QUERY FAILURE FUNCTION
	var handleFailure = function(o){
		if(o.responseText !== undefined){
			div.innerHTML = "<li>Transaction id: " + o.tId + "</li>";
			div.innerHTML += "<li>HTTP status: " + o.status + "</li>";
			div.innerHTML += "<li>Status code message: " + o.statusText + "</li>";
		}
	}
	
	// AJAX CALLBACK FUNCTION
	var callback =
		{
		  success:handleSuccess,
		  failure: handleFailure,
		  argument: { /*field:arrFields[i], loopId:i*/ }
		};
		
	// this really needs a "synchronous, not asynchronous" connection
	request = Connector.asyncRequest('POST', ajax_url, callback, post_vars);
	return;
	
	
}

// Simple get ajax and replace the div innherHTML function
var simpleAjaxContent = function( div_name, ajax_url, post_vars, call_back_function, request_method  ){
	//alert(div_name);
	// First, check for div existence
	var myDiv = getID(div_name);
	if(!myDiv){
		return false;	
	}
	// SET TERMPORARY "LOADING" MESSAGE
	//myDiv.innerHTML = '<span><img src="/images/loading.gif"></span>';
	
	// REQUIRE YAHOO YUI CONNECTION MANAGER
	var Connector = YAHOO.util.Connect;
	if( typeof(Connector) != 'object'){
		alert('The connection manager failed to load. Please reload the page.');
		return false;
	}
	
	//if( typeof(request_method) != 'string' || request_method.toLowerCase != "get" ){
	//	request_method = 'POST';	
	//}
	
	request_method = 'POST';
	
	// Declare the div replace function
	var handleSuccess = function(o){
		if(o.responseText !== undefined){
			
			// replace innerHTML
			myDiv.innerHTML = o.responseText;
			//setTimeout('evaluateJsDiv(\'' +div_name+ '\');',200);
			//setTimeout('evaluateJsDiv(\''+ div_name +'\');',2000);
			if(typeof(call_back_function) != 'undefined'){
				if(YAHOO.lang.isFunction(call_back_function)){
					call_back_function();
				}
				//YAHOO.lang.JSON.parse(call_back_function);
				//YAHOO.util.Dom.get('response2').innerHTML = call_back_function;
				//alert(call_back_function);
			}
		}
	}
	// AJAX QUERY FAILURE FUNCTION
	var handleFailure = function(o){
		if(o.responseText !== undefined){
			myDiv.innerHTML = "<li>Transaction id: " + o.tId + "</li>";
			myDiv.innerHTML += "<li>HTTP status: " + o.status + "</li>";
			myDiv.innerHTML += "<li>Status code message: " + o.statusText + "</li>";
		}
	}
	
	var callback ={
	  cache:false ,
	  success:handleSuccess,
	  failure: handleFailure,
	  argument: { /*field:arrFields[i], loopId:i*/ }
	};
	
	var request = Connector.asyncRequest(request_method, ajax_url, callback, post_vars);
	return;	
}




// FUNCTION TO CLEAR A SELECT BY IT'S ID
function clearSelect(field_name, num_options_to_leave){
	if(	typeof(field_name)!= 'string') { return false; }
	if(	typeof(num_options_to_leave)!= 'string' && typeof(num_options_to_leave)!= 'number') { return false; }
	var myField = YAHOO.util.Dom.get(field_name);
	//var myField = getID(field_name);
	if(!myField){
		return false;
	}
	myField.value = null;
	myField.options.length = num_options_to_leave;
	return true;	
}
// FUNCTION TO CLEAR MULTIPLE SELECTS AND ALSO DISABLE THEM OPTIONALLY
function clearSelects(field_names, num_options_to_leave, disable_them){
	var names_array	= field_names.split(",");
	if(typeof(names_array) == 'object'){
		var len	= names_array.length;
		var i 	= 0;
		for ( i=0; i<len; ++i ){
		  clearSelect(names_array[i], num_options_to_leave);
		  if(disable_them == true){
			  disableField(names_array[i]);
		  }
		}
	}else{
		alert('names_array is: ' + typeof(names_array));	
	}
}
// FUNCTION TO DISABLE A Field
function disableField(fieldName,opacity){
	if(!opacity){
		opacity = .3;	
	}
	var myField = YAHOO.util.Dom.get(fieldName);
	if(myField == false){
		return true;	
	}
	var subFields = [];
	subFields = YAHOO.util.Dom.getChildren(myField);
	if(myField){
		myField.disabled = true;
		YAHOO.util.Dom.setStyle(fieldName, 'opacity', opacity);
		for (var i = 0; i < subFields.length; i++)
		{
			subFields[i].disabled = true;
			var href = subFields[i].getAttribute("href");
			if(href && href != "" && href != null){
				href = 'return';
			}
			//YAHOO.util.Dom.setStyle(subFields[i], 'opacity', .3);
			disableField(subFields[i],.5);
		}

		return true;
	}
	return false;
	/*var myField = getID(fieldName);
	if(myField == null){
		return false;
	}
	myField.disabled = true;
	changeOpac(30, fieldName);
	return true;*/
}
// FUNCTION TO DISABLE MULTIPLE FIELDS
function disableFields(field_names,opacity){
	var names_array	= field_names.split(",");
	if(typeof(names_array) == 'object'){
		var len	= names_array.length;
		var i 	= 0;
		for ( i=0; i<len; ++i ){
			 disableField(names_array[i],opacity);
		}
	}else{
		alert('names_array is: ' + typeof(names_array));	
	}
}
// FUNCTION TO ENABLE A Field
function enableField(fieldName,opacity){
	if(!opacity){
		opacity = 1;	
	}
	var myField = YAHOO.util.Dom.get(fieldName);
	if(myField == false){
		return true;	
	}
	var subFields = [];
	subFields = YAHOO.util.Dom.getChildren(myField);
	if(myField){
		myField.disabled = false;
		YAHOO.util.Dom.setStyle(fieldName, 'opacity', opacity);
		for (var i = 0; i < subFields.length; i++)
		{
			subFields[i].disabled = true;
			var href = subFields[i].getAttribute("href");
			if(href && href != "" && href != null){
				href = 'return';
			}
			//YAHOO.util.Dom.setStyle(subFields[i], 'opacity', .3);
			enableField(subFields[i],1);
		}

		return true;
	}
	return false;
}
// FUNCTION TO ENABLE MULTIPLE FIELDS
function enableFields(field_names){
	var names_array	= field_names.split(",");
	if(typeof(names_array) == 'object'){
		var len	= names_array.length;
		var i 	= 0;
		for ( i=0; i<len; ++i ){
			 enableField(names_array[i]);
		}
	}else{
		alert('names_array is: ' + typeof(names_array));	
	}
}

//change the opacity for different browsers 
function changeOpac(opacity, id) { 
	if(opacity > 1){
		opacity = opacity / 100;
	}
    return YAHOO.util.Dom.setStyle(id, 'opacity', opacity);
	//return true;
	/*var myField = getID(id);
	if(myField == null){
		return false;
	}
	object = myField.style;	
    object.opacity = (opacity / 100); 
    object.MozOpacity = (opacity / 100); 
    object.KhtmlOpacity = (opacity / 100); 
    object.filter = "alpha(opacity=" + opacity + ")"; */
} 
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 || 5;  
	var opacity = options.opacity || 50;  
	var opaque = (opacity / 100);  
	var bgcolor = options.bgcolor || '#000000';  
	var dark=getID('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  
		tnode.style.zIndex = zindex;
		  
		tbody.appendChild(tnode);                        // Add it to the web page    
		dark=getID('darkenScreenObject');  // Get the object. 
	}  
	if (vis) {    
		var scrollHeight = getScrollXY();  
		// Calculate the page width and height     
		if( document.body && ( document.body.scrollWidth || document.body.scrollHeight ) ) {
			var pageWidth = document.body.scrollWidth + scrollHeight[0]+'px';        
			var pageHeight = document.body.scrollHeight + scrollHeight[1]+'px';
		} else if( document.body.offsetWidth ) {
			var pageWidth = document.body.offsetWidth + scrollHeight[0]+'px';      
			var pageHeight = document.body.offsetHeight + scrollHeight[1]+'px';  
		} else {
			var pageWidth='100%';       
			var pageHeight='100%';    
		}       
		//set the shader to cover the entire page and make it visible.
		  
		dark.style.top = '0px'; //scrollHeight[1]+'px';
		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;    
		dark.style.height= '10000px';    
		dark.style.display='block';                            
	} else {     
		dark.style.display='none';  
	}
}
function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}
function getPageDimensions(){
	if(document.all){
      availW = document.body.clientWidth;
      availH = document.body.clientHeight;
   }else{
      availW = innerWidth;
      availH = innerHeight;
   }
   return [availW,availH];	
}
function add_item_of_week(type_id, item_id){
	var poststr = "sg=main.ajax_add_item_of_week&type_id=" + intVal(type_id) + "&item_id=" + intVal(item_id);
	var callback = {
		success: function(o) {
			if(o.responseText == ''){
			}else{
				// MUST BE JSON RESPONSE
				try {
					var resp = YAHOO.lang.JSON.parse(o.responseText);  
				}
				catch(e) {				
					waitingPanel.hide();
					alert('Invalid Response from Server');
					return false;
				}
				// If server said failure
				if(resp.success == 0){
					waitingPanel.hide();
					alertVar(resp.errors);
					return false;
					
				}else{					
					waitingPanel.hide();
					alert("Add successful");
				}
			}
			
		},
		
		failure: function(o) {
			
		}
		
	};
	// initiate a new waiting panel (use "window.xxx" so we can hide it from outside of this function);
	window.waitingPanel = new panelLoading('Adding to items of week.  Please wait...<br />[<a href="javascript:void(0)" onClick="stopIt();waitingPanel.hide()">Stop</a>]');
	// Show the Panel
	waitingPanel.show();
	// start ajax request
	YAHOO.util.Connect.asyncRequest('POST', 'index.php', callback, poststr );
}


// FUNCTION TO CHANGE THE BIGPIC ON MOTOR MALL DETAILS PAGE
function bigPic(src){
	if(document.getElementById('bigpic')){
		document.getElementById('bigpic').src = src;
		return true;
	}
	//alert('didnt work');
	return false;
}



//########################################################################################################
////############# lib_flv_player.js ##################################################################////
/*---- FLV PLAYER JAVASCRIPT ----*/
var WIDE_SCREEN = false;
function doWideScreen(){
	
	//YAHOO.namespace("container");

	if(WIDE_SCREEN){
		YAHOO.util.Dom.setStyle('channel-left', 'margin-top', '0px');
		//document.getElementById('flashContainer').style.width = 640+'px';
		//document.getElementById('flashContainer').style.height = 430+'px';
		YAHOO.util.Dom.setStyle('flashContainer', 'width', 640+'px');
		YAHOO.util.Dom.setStyle('flashContainer', 'height', 430+'px');
		YAHOO.util.Dom.setStyle('videoContainer', 'width', 640+'px');
		//YAHOO.util.Dom.setStyle('videoContainer', 'height', 430+'px');	
		WIDE_SCREEN = false;
		//YAHOO.container.flashContainerIframe.hide();
		
		
		//YAHOO.util.Dom.setStyle('videoContainer', 'float', 'right');
	}
	else{
		YAHOO.util.Dom.setStyle('channel-left', 'margin-top', '10px');
		//document.getElementById('flashContainer').style.width = 941+'px';
		//document.getElementById('flashContainer').style.height = 550+'px';
		YAHOO.util.Dom.setStyle('videoContainer', 'width', 950+'px');
		//YAHOO.util.Dom.setStyle('videoContainer', 'height', 890+'px');
		//YAHOO.util.Dom.setStyle('videoContainer', 'float', 'none');
		YAHOO.util.Dom.setStyle('flashContainer', 'width', 950+'px');
		YAHOO.util.Dom.setStyle('flashContainer', 'height', 610+'px');	
		
		WIDE_SCREEN = true;		
		
		// Instantiate a frame panel underlay to prevent flash ads from bleeding through.
		/*YAHOO.container.flashContainerIframe = new YAHOO.widget.Panel("flashContainerIframe", 
										{ 
											width:"300px",
											height:"530px",
											visible:false, 
											draggable:false, 
											close:false,
											iframe:true,
											zIndex:999,
											underlay:"none",
											xy: YAHOO.util.Dom.getXY( YAHOO.util.Dom.get('flashContainer') )
										} 
									);
		YAHOO.container.flashContainerIframe.setBody("This Iframe underlay prevents flash ads from bleeding through.");
		YAHOO.container.flashContainerIframe.render("container");
		YAHOO.container.flashContainerIframe.show();*/
		
		

	}
	
}


//v1.7
// Flash Player Version Detection
// Detect Client Browser type
// Copyright 2005-2008 Adobe Systems Incorporated.  All rights reserved.
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
function ControlVersion()
{
	var version;
	var axo;
	var e;
	// NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry
	try {
		// version will be set for 7.X or greater players
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) {
	}
	if (!version)
	{
		try {
			// version will be set for 6.X players only
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
			
			// installed player is some revision of 6.0
			// GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
			// so we have to be careful. 
			
			// default to the first public version
			version = "WIN 6,0,21,0";
			// throws if AllowScripAccess does not exist (introduced in 6.0r47)		
			axo.AllowScriptAccess = "always";
			// safe to call for 6.0r47 or greater
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}
	if (!version)
	{
		try {
			// version will be set for 4.X or 5.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}
	if (!version)
	{
		try {
			// version will be set for 3.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = "WIN 3,0,18,0";
		} catch (e) {
		}
	}
	if (!version)
	{
		try {
			// version will be set for 2.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			version = "WIN 2,0,0,11";
		} catch (e) {
			version = -1;
		}
	}
	
	return version;
}
// JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer(){
	// NS/Opera version >= 3 check for Flash plugin in plugin array
	var flashVer = -1;
	
	if (navigator.plugins != null && navigator.plugins.length > 0) {
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
			var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
			var descArray = flashDescription.split(" ");
			var tempArrayMajor = descArray[2].split(".");			
			var versionMajor = tempArrayMajor[0];
			var versionMinor = tempArrayMajor[1];
			var versionRevision = descArray[3];
			if (versionRevision == "") {
				versionRevision = descArray[4];
			}
			if (versionRevision[0] == "d") {
				versionRevision = versionRevision.substring(1);
			} else if (versionRevision[0] == "r") {
				versionRevision = versionRevision.substring(1);
				if (versionRevision.indexOf("d") > 0) {
					versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
				}
			}
			var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
		}
	}
	// MSN/WebTV 2.6 supports Flash 4
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
	// WebTV 2.5 supports Flash 3
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
	// older WebTV supports Flash 2
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
	else if ( isIE && isWin && !isOpera ) {
		flashVer = ControlVersion();
	}	
	return flashVer;
}
// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
	versionStr = GetSwfVer();
	if (versionStr == -1 ) {
		return false;
	} else if (versionStr != 0) {
		if(isIE && isWin && !isOpera) {
			// Given "WIN 2,0,0,11"
			tempArray         = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
			tempString        = tempArray[1];			// "2,0,0,11"
			versionArray      = tempString.split(",");	// ['2', '0', '0', '11']
		} else {
			versionArray      = versionStr.split(".");
		}
		var versionMajor      = versionArray[0];
		var versionMinor      = versionArray[1];
		var versionRevision   = versionArray[2];
        	// is the major.revision >= requested major.revision AND the minor version >= requested minor
		if (versionMajor > parseFloat(reqMajorVer)) {
			return true;
		} else if (versionMajor == parseFloat(reqMajorVer)) {
			if (versionMinor > parseFloat(reqMinorVer))
				return true;
			else if (versionMinor == parseFloat(reqMinorVer)) {
				if (versionRevision >= parseFloat(reqRevision))
					return true;
			}
		}
		return false;
	}
}
function AC_AddExtension(src, ext)
{
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?'); 
  else
    return src + ext;
}
function AC_Generateobj(objAttrs, params, embedAttrs) 
{ 
  var str = '';
  if (isIE && isWin && !isOpera)
  {
    str += '<object ';
    for (var i in objAttrs)
    {
      str += i + '="' + objAttrs[i] + '" ';
    }
    str += '>';
    for (var i in params)
    {
      str += '<param name="' + i + '" value="' + params[i] + '" /> ';
    }
    str += '</object>';
  }
  else
  {
    str += '<embed ';
    for (var i in embedAttrs)
    {
      str += i + '="' + embedAttrs[i] + '" ';
    }
    str += '> </embed>';
  }
  document.write(str);
}
function AC_FL_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}
function AC_SW_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
     , null
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}
function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();    
    switch (currArg){	
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":	
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblclick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
      case "id":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace": 
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}

// -----------------------------------------------------------------------------
// Globals
// Major version of Flash required
var requiredMajorVersion = 9;
// Minor version of Flash required
var requiredMinorVersion = 0;
// Revision of Flash required
var requiredRevision = 45;
// -----------------------------------------------------------------------------



//########################################################################################################
////############# lib_comments.js ####################################################################////

// MAKE TEXTAREA AUTO GROW
var autoHeightTextarea = function(textareaID, minHeight) {
	// GET THE TEXTAREA
	var textArea = getID(textareaID);
	if(!textArea){
		return false;	
	}
	Dom.setStyle(textArea, 'overflow', 'hidden');
	
	var hiddenID = textareaID+'-hidden';
	var hiddenTextarea=getID(hiddenID);  
	if (!hiddenTextarea) {    
		// 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('textarea');       // Create the layer.        
		tnode.style.position='absolute';                 // Position absolutely        
		tnode.style.top='-10000px';                           // In the top        
		tnode.style.left='-10000px';                          // Left corner of the page        
		tnode.style.height = minHeight;
		tnode.style.overflow='auto';                   // Try to avoid making scroll bars                    

		//tnode.style.display='none';                      // Start out Hidden        
		tnode.id=hiddenID; 						// Name it so we can find it later  
		//tnode.style.zIndex = 0;
		  
		Dom.insertAfter(tnode,textArea);                        // Add it to the web page    
		hiddenTextarea=getID(hiddenID);  // Get the object. 
		
		// GIVE THE HIDDEN TEXTAREA THE SAME STYLES AS THE REAL TEXTAREA SO WE CAN GET THE SAME WRAP POINT
		Dom.addClass(hiddenTextarea, 'comment-input');
		Dom.setStyle(hiddenTextarea, 'font-size', Dom.getStyle(textArea,'font-size')); 
		Dom.setStyle(hiddenTextarea, 'font-family', Dom.getStyle(textArea,'font-family')); 		
		Dom.setStyle(hiddenTextarea, 'line-height', Dom.getStyle(textArea,'line-height')); 
		
			
		Dom.setStyle(hiddenTextarea, 'width',   (parseInt(Dom.getStyle(textArea,'width'),10) + 15)  + 'px');
	}  
	
	
	
	// SET THE HIDDEN TEXTAREA CONTENT TO MATCH
	hiddenTextarea.value = textArea.value;
	
	
	// GET THE HIDDEN TEXTAREA'S SCROLL HEIGHT
	hiddenHeight = parseInt(hiddenTextarea.scrollHeight, 10);
	
	// GET OLD TEXTAREA HEIGHT
	var height = parseInt(Dom.getStyle(textArea, 'height'), 10);
	
	var newHeight = hiddenHeight + 12;
	if (newHeight < parseInt(minHeight, 10)) {
		newHeight = parseInt(minHeight, 10);
	}
	if ((height != newHeight)) {   
		Dom.setStyle(textArea, 'height', newHeight + 'px');
		if (YAHOO.env.ua.ie > 0) {
			//Internet Explorer needs this
			//Dom.setStyle(textArea,'height', '99%');
			//Dom.setStyle(textArea,'zoom', '1');
			
			//window.setTimeout(function() {
			//	Dom.setStyle(textArea,'height', '100%');
			//}, 1);
		}
	}
}
var autoHeightListener = function(textareaID, minHeight){
	// shortcut to autoHeightTextarea function
	var handleAutoHeight = function(){autoHeightTextarea(textareaID, minHeight)}
	
	// auto resize as soon as it is available in the DOM
	YAHOO.util.Event.onContentReady(textareaID, handleAutoHeight , this, true);
	
	// get click listeners (if there are any)
	listeners = YAHOO.util.Event.getListeners ( textareaID , 'click' );
	if(listeners == null){	
		YAHOO.util.Event.on(textareaID, "keyup", handleAutoHeight, true);
		//YAHOO.util.Event.on(textareaID, 'keypress', handleAutoHeight, true);
		//YAHOO.util.Event.on(textareaID, "mouseleave", handleAutoHeight, true);
	}
}

// FUNCTION TO SUBMIT THE "ADD COMMENT FORM" VIA AJAX
function sgCommentAdd(id_suffix){
	// BUILD THE HTML IDS FROM THE SUFFIX
	var formID 				= 'comment-add-' + id_suffix;
	var textareaID			= 'comment-details-' + id_suffix;
	var newCommentAnchorID	= 'comment-new-anchor-' + id_suffix;
	
	// IF THE FORM DOESN'T EXIST, JUST RETURN FALSE
	var myForm		= getID(formID);
	var textarea	= getID(textareaID);
	if(!myForm || !textarea){
		return false;	
	}
	
	// CHECK TO MAKE SURE THE FORM DOESN'T JUST HAVE THE DEFAULT TEXT
	var comment = YAHOO.lang.trim(textarea.value);
	if(comment == 'write a comment...' || comment == 'write a reply...' || comment == ''){
		return false;	
	}
	
	YAHOO.util.Connect.setForm(formID, true);			
	var callback = {		  
		upload: function(o) {
			if(o.responseText == ''){
				alert('Connection to server failed. Please try again.');
				return false;
			}else{
				// MUST BE JSON RESPONSE
				try {
					var resp = YAHOO.lang.JSON.parse(o.responseText);  
				}
				catch(e) {
					waitingPanel.hide();
					alert('Invalid Response from Server');
					return false;
				}
				// If failure, show error, otherwise, redirect.
				if(resp.success == 0){
					waitingPanel.hide();
					return false;
				}else{
					waitingPanel.setHeader('Add Successful.  Updating Current Page...');
					textarea.value = "";
					sgInsertNewComment(resp.customObj.comment_id, id_suffix);					
					waitingPanel.hide();
				}

			}
		},
		failure: function(o){
			alert('Connection to server interrupted. Please try again.');
			return false;
		}
	};
	
	// initiate a new waiting panel (use "window.xxx" so we can hide it from outside of this function);
	window.waitingPanel = new panelLoading('Adding...  Please wait...<br />[<a href="javascript:void(0);" onClick="stopIt();waitingPanel.hide()">Stop Submit</a>]');
	
	// Show the Panel
	waitingPanel.show();
	
	// Perform Upload Call
	window.oConnect = YAHOO.util.Connect.asyncRequest('POST', window.location.protocol + '//' + window.location.hostname + '/index.php', callback);
}


// FUNCTION TO RETRIEVE NEW STATUS VIA AJAX AND INSERT IT AT THE BOTTOM
function sgInsertNewComment(newCommentID, id_suffix){
	
	// BUILD THE HTML IDS FROM THE SUFFIX
	var newCommentAnchorID	= 'comment-new-anchor-' + id_suffix;
	
	// IF THE FORM DOESN'T EXIST, JUST RETURN FALSE
	var newCommentAnchor	= getID(newCommentAnchorID);
	if(!newCommentAnchor){
		return false;	
	}
	
	// EXTRACT TYPE AND ITEM (BEING COMMENTED ON) ID FROM THE SUFFIX
	var suffix_parts	= id_suffix.split('-');
	var type_id			= parseInt(suffix_parts[0], 10);
	var item_id			= parseInt(suffix_parts[1], 10);
	
	// SAY 'LOADING'
	newCommentAnchor.innerHTML = '<img src="/images/ajax-loader.gif">Loading...';
	
	// CREATE DIV ABOVE NEW COMMENT ANCHOR TO PLACE THE NEW HTML
	var el = document.createElement('div');
	el.id = 'new-comment-' + id_suffix + uniqid();		
	yui_el = Dom.get(el.id);
	Dom.insertBefore(el, newCommentAnchor);
	this.el = el;
	
	// GET NEW DIMENSIONS
	var dimensions = Dom.getRegion(el.id);
	
	Dom.setStyle(el.id, 'height', 0);
	Dom.setStyle(el.id, 'overflow', 'hidden');
	
	// BEGIN URL TO FETCH COMMENT
	var getCommentURL = window.location.protocol + '//' + window.location.hostname +'/fa/main-ajax_comment_dsp/type_id-'+ type_id +'/id-'+ item_id +'/comment_id-'+ newCommentID;
	
	// BUILD VARIABLES TO GET A COMMENT THAT MATCHES OUR CURRENT CONFIG
	config_name = type_id+'-'+item_id;
	if(YAHOO.lang.isObject(YAHOO[config_name])){
		for(i in YAHOO[config_name]){
			getCommentURL += '/'+ i +'-'+ YAHOO[config_name][i];
		}
	}
	
	
	
	
	// FUNCTION TO ADD FINAL ATTRIBUTES TO NEW DIV
	this.finish = function(){
		Dom.setStyle(this.getEl(), 'overflow', 'visible');
		Dom.setStyle(this.getEl(), 'height', 'auto');
	}
	this.animate_me = function(){
		this.newel = this.el;
		// HIDE 'LOADING'
		newCommentAnchor.innerHTML = '';	
		if(this.el.innerHTML == ''){
			return false;	
		}
		var attributes = {   
			height: { from: 0, to: 30 } 
		}; 
		var anim = new YAHOO.util.Anim(this.el, attributes, .75, YAHOO.util.Easing.easeOut);
		anim.onComplete.subscribe( this.finish );
		anim.animate(); 
	}
	//setTimeout(animate_me, 2000);
	
	// GET STATUS ENTRY AND LOAD IT INTO NEW DIV
	new simpleAjaxContent( el.id, getCommentURL, false, this.animate_me );
	
	
}

// FUNCTION TO RETRIEVE NEW STATUS VIA AJAX AND INSERT IT AT THE BOTTOM
function sgCommentDelete(commentID, id_suffix){
	
	// BUILD THE HTML IDS FROM THE SUFFIX
	var container_id	= "comment-" + id_suffix;
	
	// IF THE FORM DOESN'T EXIST, JUST RETURN FALSE
	var commentContainer	= getID(container_id);
	if(!commentContainer){
		return false;	
	}
	
	// EXTRACT TYPE AND ITEM (BEING COMMENTED ON) ID FROM THE SUFFIX
	var suffix_parts	= id_suffix.split('-');
	var type_id			= parseInt(suffix_parts[0], 10);
	var item_id			= parseInt(suffix_parts[1], 10);
	var comment_id		= parseInt(suffix_parts[2], 10);// not used in this function, but good to know
	
	
	
	// BEGIN URL TO FETCH COMMENT
	var poststr = 'sg=main.ajax_comment_delete&type_id='+ type_id +'&id='+ item_id +'&comment_id='+ commentID;
	var callback = {
		success: function(o) {
			if(o.responseText == ''){
				alert('Delete Failed!');
			}else{
				// MUST BE JSON RESPONSE
				try {
					var resp = YAHOO.lang.JSON.parse(o.responseText);  
				}
				catch(e) {				
					waitingPanel.hide();
					alert('Invalid Response from Server');
					return false;
				}
				// If server said failure
				if(resp.success == 0){
					waitingPanel.hide();
					alert(resp.message);
					return false;
					
				}else{					
					waitingPanel.hide();
					var obj =Dom.get(container_id);
					obj.parentNode.removeChild(obj);

				}
			}
			
		},
		
		failure: function(o) {
			alert('DELETE failed');
		}
		
	};
	// initiate a new waiting panel (use "window.xxx" so we can hide it from outside of this function);
	window.waitingPanel = new panelLoading('Deleting Reply.  Please wait...<br />[<a href="javascript:void(0);" onClick="stopIt();waitingPanel.hide()">Stop</a>]');
	// Show the Panel
	waitingPanel.show();
	// start ajax request
	YAHOO.util.Connect.asyncRequest('POST', window.location.protocol + '//' + window.location.hostname + '/index.php', callback, poststr );
	
}

// FUNCTION TO RETRIEVE NEW STATUS VIA AJAX AND INSERT IT AT THE BOTTOM
function sgInsertOlderComments(datetime, id_suffix){
	
	// BUILD THE HTML IDS FROM THE SUFFIX
	var oldCommentAnchorID	= 'comment-old-anchor-' + id_suffix;
	this.oldCommentLinkID	= 'comment-old-link-' + id_suffix;
	
	// IF THE ANCHOR DIV DOESN'T EXIST, JUST RETURN FALSE
	var oldCommentAnchor	= getID(oldCommentAnchorID);
	if(!oldCommentAnchor){ 
		return false;	
	}
	
	
	
	// EXTRACT TYPE AND ITEM (BEING COMMENTED ON) ID FROM THE SUFFIX
	var suffix_parts	= id_suffix.split('-');
	var type_id			= parseInt(suffix_parts[0], 10);
	var item_id			= parseInt(suffix_parts[1], 10);
	
	// SAY 'LOADING'
	oldCommentAnchor.innerHTML = '<img src="/images/ajax-loader.gif">Loading...';
	
	// CREATE DIV ABOVE NEW COMMENT ANCHOR TO PLACE THE NEW HTML
	var el = document.createElement('div');
	el.id = 'new-comment-' + id_suffix;// + uniqid();		
	yui_el = Dom.get(el.id);
	Dom.insertAfter(el, oldCommentAnchor);
	this.el = el;
	el.oldCommentLinkID = this.oldCommentLinkID;// attach it to the dom element so we can use it below in animate_me
	
	// SET IT TO 0 HIEGHT, SO WE CAN SLIDE IT OPEN AND LOOK COOL	
	Dom.setStyle(el.id, 'height', 0);
	Dom.setStyle(el.id, 'overflow', 'hidden');
	
	// BEGIN URL TO FETCH COMMENT
	var getCommentURL = window.location.protocol + '//' + window.location.hostname + '/fa/main-ajax_comments_older_dsp/type_id-'+ type_id + '/id-'+ item_id +'/datetime-' + encodeURI(datetime);
	
	// BUILD VARIABLES TO GET A COMMENT THAT MATCHES OUR CURRENT CONFIG
	config_name = type_id+'-'+item_id;
	if(YAHOO.lang.isObject(YAHOO[config_name])){
		for(i in YAHOO[config_name]){
			getCommentURL += '/'+ i +'-'+ YAHOO[config_name][i];
		}
	}
	
	
	
	
	// FUNCTION TO ADD FINAL ATTRIBUTES TO NEW DIV
	this.finish = function(){
		Dom.setStyle(this.getEl(), 'overflow', 'visible');
		Dom.setStyle(this.getEl(), 'height', 'auto');
		// remove 'get older' link
		var obj =Dom.get(this.getEl().oldCommentLinkID);
		obj.parentNode.removeChild(obj);
	}
	this.animate_me = function(){
		this.newel = this.el;
		// HIDE 'LOADING'
		oldCommentAnchor.innerHTML = '';	
		if(this.el.innerHTML == ''){
			return false;	
		}
		var attributes = {   
			height: { from: 0, to: 30 } 
		}; 
		var anim = new YAHOO.util.Anim(this.el, attributes, .75, YAHOO.util.Easing.easeOut);
		anim.onComplete.subscribe( this.finish );
		anim.animate(); 
		
		
	}
	//setTimeout(animate_me, 2000);
	
	// GET STATUS ENTRY AND LOAD IT INTO NEW DIV
	new simpleAjaxContent( el.id, getCommentURL, false, this.animate_me );
	
	
}
