// JavaScript Document
function jqToggleLayer( elementID, speed, toggleMenu, showHide ) {
	/*
	* showHide = optional, must be 'show' or 'hide'. 
	*/
	//alert( showHide );
	if ( showHide == null ) {
		var elementDisplay = $("#" + elementID).css("display");
		if ( elementDisplay == "none" ) {
			$("#" + elementID).show(speed);
		} else {
			$("#" + elementID).hide();
		}
		if ( toggleMenu ) {
			jqToggleLayer ( "leftcontent", "", 0 );
		}
	} else {
		if ( showHide == "show" ) {
			$("#" + elementID).show(speed);
		} else {
			$("#" + elementID).hide();
		}
	}
}

function jqSlideLayer( elementID, speed, toggleMenu, showHide ) {
	//using jquery, but this should have been toggle (it didn't allow item to be hidden)
	//$("#" + elementID).show( "clip", speed );
	//using jqueryui to toggle
	// this was set to just toggle and then toggleMenu
	// changed to use showHide 2009-07-21
	
	if ( showHide == null ) {
		$("#" + elementID).toggle( "blind", speed );
	} else {
		if ( showHide == "show" ) {
			$("#" + elementID).show( "blind", speed );
		} else {
			$("#" + elementID).hide();
		}
	}
	
	if ( toggleMenu ) {
		jqToggleLayer ( "leftcontent", "", 0 );
	}
}

function jqSetSelection ( elementID, valueText, checkID, windowID, transfer ) {
	/*
	* elementID = the ID of the element (as opposed to numeric location)
	* valueText = the ID of the option (as opposed to numeric)
	* checkID = the ID of the green check
	* windowID = if supplied, this is the ID to close
	*
	* actually, checkID and elementID should ALWAYS be the same
	* this function is similar to the function used for personalized tags
	* set dropdown menu (using the element number OR id) to the value given
	* close the window if required
	* make the green check visible after changing the selection
	*/
	transfer = transfer === 0 ? 0 : 1;
	
	var greenCheck = "greenCheck" + checkID;
	elementID = "select" + elementID;
	//document.getElementById(elementID).value = valueText;
	/* turns out it is better to loop through the menu
	* and choose the item with the appropriate value..
	* also, check if the menu is disabled. If so,
	* enable it and then disable it later
	*/
	if ( $("#" + elementID).data("disabled") == "1" ) {
		$("#" + elementID).prop("disabled", false);
	}
	$("#" + elementID + " option").each(function(i){
		if ( $(this).attr("id") == valueText ) {
			$("#" + elementID).change(); // fire the change event manually
			jQuery(this).parent().val( jQuery(this).val() );
		} else {
			if ( jQuery(this).parent().val() == jQuery(this).val() ) {
				jQuery(this).parent().val("");
			}
		}
	});
	if ( $("#" + elementID).data("disabled") == "1" ) {
		$("#" + elementID).prop("disabled", true);
	}
	//alert("about to show");
	$("#" + greenCheck).show( "slide", "fast" );
	//jqSlideLayer ( greenCheck, 'fast', 0, 'show' );	
	//alert("done showing");
	if ( windowID ) {
		if ( windowID == "JQUIDialog" || windowID == "JQUIDialog2" || windowID == "JQUIDialogv2" || windowID == "attInfo" ) {
			if ( transfer ) {
				transferTo = elementID;
				var transferOptions = new Array();
				transferOptions["className"] = "ui-effects-transfer";
				if ( transferTo != "" && $("#" + transferTo).length ) {
					transferOptions["to"] = "#" + transferTo;
				}
				$("#" + windowID).effect( "transfer", transferOptions, 500 );
			}
			$("#" + windowID).dialog( "close" );
		} else {
			jqToggleLayer( windowID, '', 1 );
		}
	}
} // function jqSetSelection ( elementID, valueText, checkID, windowID ) {

function jqSetSelectionOLD ( elementID, valueText, checkID, windowID ) {
	/*** STOPPED USING ON 2011-04-18 ***/
	/*
	* elementID = the ID of the element (as opposed to numeric location)
	* valueText = the ID of the option (as opposed to numeric)
	* checkID = the ID of the green check
	* windowID = if supplied, this is the ID to close
	*
	* actually, checkID and elementID should ALWAYS be the same
	* this function is similar to the function used for personalized tags
	* set dropdown menu (using the element number OR id) to the value given
	* close the window if required
	* make the green check visible after changing the selection
	*/
	//$("body").append("<br><br><br><br><br>setting selection");
	var greenCheck = "greenCheck" + checkID;
	elementID = "select" + elementID;
	//document.getElementById(elementID).value = valueText;
	// turns out it is better to loop through the menu
	// and choose the item with the appropriate value..
	
	$("#" + elementID + " option").each(function(i){
		//$("body").append("<br><br><br><br>checking if '" + $(this).attr("id") + "' = '" + valueText + "'");
		if ( $(this).attr("id") == valueText ) {
			$("#" + elementID).change(); // fire the change event manually
			jQuery(this).parent().val( jQuery(this).val() );
		} else {
			if ( jQuery(this).parent().val() == jQuery(this).val() ) {
				jQuery(this).parent().val("");
			}
		}
	});
	
	
	jqSlideLayer ( greenCheck, 'fast', 0, 'show' );	
	if ( windowID ) {		
		if ( windowID == "JQUIDialog" ) {
			$("#JQUIDialog").dialog( "close" );
		} else if ( windowID == "JQUIDialog2" ) {
			$("#JQUIDialog2").dialog( "close" );
		} else if ( windowID == "JQUIDialogv2" ) {
			$("#JQUIDialogv2").dialog( "close" );
		} else if ( windowID == "attInfo" ) {
			$("#attInfo").dialog( "close" );
		} else {
			jqToggleLayer( windowID, '', 1 );
		}
	}
}
	
function futureDate( daysAhead ) {
	var result = new Date();
	var dayOfWeek = result.getDay();
	switch ( dayOfWeek ) {
	case 6:
		// saturday
		daysAhead += 2;
		break;
	case 0:
		// sunday
		daysAhead += 1;
		break;
	}
	var futureTime = result.getTime() + (daysAhead*24*60*60*1000);
	result.setTime(futureTime);
	return result;
}

function getMonthDay ( date ) {
	/* since javascript is stupid and has no built-in way to get a spelled out month
	* we'll need this function to do it ourselves
	* mostly copied from http://www.w3schools.com/jsref/jsref_getmonth.asp
	* also added in the day
	*/
	var month=new Array(12);
	month[0]="January";
	month[1]="February";
	month[2]="March";
	month[3]="April";
	month[4]="May";
	month[5]="June";
	month[6]="July";
	month[7]="August";
	month[8]="September";
	month[9]="October";
	month[10]="November";
	month[11]="December";
	var month = month[date.getMonth()];
	var day = date.getDate();
	var result = month + " " + day;
	return result;
}

function inArray( what, where ){
	// this returns true or false ONLY
	var result = false;
	for(var i = 0; i < where.length; i++ ){
		if( what == where[i] ){
			result = true;
		}
	}
	return result;
}

function inObject( what, where ){
	console.log("checking object");
	var result = false;
	for( var key in where ) {
		console.log("checking" + String(where[key]) );
		if ( what == String(where[key]) ) {
			result = true;
		}
	}
	return result;
}

function setShoppingCookie(){
	$(document).ready(function(){
		//var allEngines = { 0:"shopzilla",1:"nextag",2:"yahooshopping",3:"pricegrabber",4:"shoppingcom",5:"become",6:"jellyfish",7:"smarter",8:"pronto"};
		var allEngines = ["shopzilla","nextag","yahooshopping","pricegrabber","shoppingcom","become","jellyfish","smarter","pronto"];
		currentEngine = $.getQueryString({id:"cid"}) ? String($.getQueryString({id:"cid"})) : String($.getQueryString({id:"utm_source"}));
		if ( currentEngine ) {
			if ( inArray( currentEngine, allEngines ) ) {
				$.cookie('shoppingsearch', currentEngine, { expires: 365, path: '/', domain: 'nicepricefavors.com', secure: false });
			}
		}
	});
} // function setShoppingCookie(){
setShoppingCookie();

function cookieTest () {
	jQuery.cookie( 'test', true );
	if ( jQuery.cookie ( 'test' ) ) {
		jQuery.cookie( 'test', null );
		var result = true;
	} else {
		var result = false;
	}
	return result;
} // function cookieTest () {

function dialogCreated( el ) {
	// returns true if the dialog was already created, false otherwise
	return el.is(":ui-dialog");
	// el = the jquery element - such as dialogCreated( $("#myID") );
	/*var result;
	// the test is different for 1.3.2 or 1.4+
	if ( $().jquery == "1.3.2" ) {
		result = el.dialog( "option", "height" ) ? true : false;
	} else {
		result = isNaN(el.dialog( "option", "height" )) ? false : true;
	}
	return result;*/
} // function dialogCreated( el ) {

function rolloverLink( el, off, over, clicked ) {
	preloadImage( over );
	preloadImage( clicked );
	/* sometimes we may wish to disable a rollover
	* we'll do this by adding class 'rolloverDisabled'
	* so if the element is of class 'rolloverDisabled', do nothing
	*/
	el.hover(function(){
		$(this).not(".rolloverDisabled").attr("src",over);
	},function(){
		$(this).not(".rolloverDisabled").attr("src",off);
	}).mousedown(function(){
		$(this).not(".rolloverDisabled").attr("src",clicked);
	}).mouseup(function(){
		$(this).not(".rolloverDisabled").attr("src",over);
	});
} // function rolloverLink( el, off, over, clicked ) {

function preloadImage( imageURL ){
	$("<img/>").attr("src", imageURL ).addClass("hideMe").appendTo("body");
} // function preloadImage( imageURL ){




function enableFormElements( form ) {
	/* sometimes we disable dropdown menus so they're greyed out
	* but we still fill them in using jquery etc
	* but they're not submitted with the form because they're disabled
	* so we have to re-enable them at the time the form is submitted
	* also, save the disabled status in a .data value so we can
	* re-disable them later if necessary (using disableFormElements( form ) )
	* for now we review the following elements:
	* select, input, textarea
	*/
	$("select,input,textarea", form).each(function(){
		if( $(this).prop("disabled") ) {
			$(this).data("wasDisabled", "1");
			$(this).prop("disabled", false);
		}
	});
} // function enableFormElements( form ) {

function disableFormElements( form ) {
	/* checks form for elements that have been enabled by enableFormElements( form )
	* and disables them again
	*/
	$("select,input,textarea", form).each(function(){
		if( $(this).data("wasDisabled") == "1" ) {
			$(this).prop("disabled", true);
		}
	});
} // function disableFormElements( form ) {
	
function uniformSizes( elements ) {
	/* get lengths / widths of largest elements in elements
	* set all to this size
	* it looks more professional
	* this seems to have a rare bug where if the images are cached, it 
	* runs before they're 'drawn' on the screen, which makes the boxes too small
	* there's a nice alternative method of determining if all images are loaded
	* at http://stackoverflow.com/questions/6488104/how-to-know-when-all-images-inside-a-specific-div-are-loaded/6488123#6488123
	* however it suffers from the same problem
	*
	* turned off as of 2011-11-09 until a fix is found
	*/
	//return 1;
	
	$(document).ready(function(){
		elements.parent().data("totalImagesLoading", elements.find("img").length );
		elements.parent().data("totalImagesLoaded", 0 );
		//$("body").append("<br><br><br><br><br><br>ready");
		//$("body").append("<br>total images = " + elements.children("img").length + "..." + elements.parent().data("totalImagesLoading") );
		
		elements.find("img").load(function(){
			//$("body").append("<br>an image has been loaded");
			elements.parent().data("totalImagesLoaded", elements.parent().data("totalImagesLoaded") + 1 );
			if ( elements.parent().data("totalImagesLoaded") == elements.parent().data("totalImagesLoading") ) {
				// all images are loaded, now we can resize the boxes
				/* lets wait an additional 200 milliseconds before we resize
				* just to give the browser time to draw everything
				*/
				setTimeout( function(){
					var widest = 0;
					var tallest = 0;
					elements.each(function(){
						//$("body").append("<br><br>width = " + $(this).width() );
						//$("body").append("<br>height = " + $(this).height() );
						
						if ( $(this).width() > widest ) {
							widest = $(this).width();
						}
						if ( $(this).height() > tallest ) {
							tallest = $(this).height();
						}
					});
					if ( widest > 0 && tallest > 0 ) {
						// just in case!
						elements.width(widest).height(tallest);
					}
					//$("body").append("<br>widest = " + widest );
					//$("body").append("<br>tallest = " + tallest );
				}, 200 );
				
			}
		});
		
	});
} // function uniformSizes( elements ) {

function isTablet(){
	/* determines if the user is on a tablet device
	* returns 1 if so
	* currently detecting ipad and droid
	*/
	var iPad = navigator.userAgent.match(/iPad/i) != null;
	var android = navigator.userAgent.match(/android/i) != null && navigator.userAgent.match(/mobile/i) == null;
	return iPad || android;
}
