// 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){
	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;
	}
	zoomin2(myObj,mySrc,zoomin_img,closeOnMouseOut);
}

function zoomin2(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.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.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) {
			
		}
		
		
	
}
// 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  ){
	//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;
	}
	
	
	// 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('POST', 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 );
}
