/*
	pickleSetup plug in for jQuery
	by: Chris Engle
	last modified: 09.11.08
	
	jQuery( [matched_elements] ).pickleSetup( options );
	Sets up pickle functions to multiple elements on a page contained inside wrapping element of [matched_elements]
*/

/* This is just a little fix for IE6 with background images.  Prevents from flickering. */
if ( document.all ) { try { document.execCommand("BackgroundImageCache", false, true); } catch(err) {} }

/*
	simulatePickle( isLoggedIn );
		Simulates the needed functionality from universal registration for pickle applications.
		params:
			isLoggedIn: (true:false) - Is the user logged in?
		notes:
			This function needs to go before any code that requires it's properties and methods
*/
function simulatePickle( isLoggedIn ) {
	urUser = {};
	urUser.getEmail = function() { return 'email@domain.com'; }
	urUser.getUserName = function() { return 'John'; }
	urUser.getUserId = function() { return '123456'; }
	if ( isLoggedIn ) urUser.isLoggedIn = true;
}

/*
	findPickleWidget( list )
		Checks the parameter "cat" in the url against [list] and sets vw_widget_name equal to the proper widget
		and sets vw_sort_order according to the parameter "sortby" (can be either: recent, rating or views).
		Also set the order (vw_arrange_order) to DESC (descending)
		params:
			list: (string/object) - If a single string value is passed in, that widget_name will be returned.
									To create a list of multiple channels/categories do something like the following:
									var myList = { channel1: 'hgtv.1000000852.1070', channel2: 'hgtv.1000000852.1071' }
									NOTE: in the case above, the URL will look something like http://.../gallery.html?cat=channel2&sortby=recent
*/
function findPickleWidget( list ) {
	var sortby = jQuery.PickleSetup.getURLParam('sortby');
	var category = jQuery.PickleSetup.getURLParam('cat');
	if ( typeof list == 'string' ) vw_widget_name = list;
	else {
		/* get sortby & cat params */
		/* if category (?cat=) has a value then see if it matches against [list] */
		if ( category != '' ) {
			for (x in list )
				if ( x == category )
					vw_widget_name = list[x];
		}
	}
	/* have the gallery default to most recent */
	switch ( sortby ) {
		case 'recent': { vw_sort_order = 'MOST_RECENT'; vw_arrange_order = 'DESC'; break; }
		case 'rating': { vw_sort_order = 'BY_RATING'; vw_arrange_order = 'DESC'; break; }
		case 'views': { vw_sort_order = 'MOST_POPULAR'; vw_arrange_order = 'DESC'; break; }
		default: { vw_sort_order = 'MOST_RECENT'; vw_arrange_order = 'DESC'; break; }
	}
	return vw_widget_name;
}

/*
	pickleSetup( options )
		Sets up pickle functions to multiple elements on a page contained inside wrapping element of [matched_elements]
		in jQuery( [matched_elements] ).pickleSetup();
		options:
			urUser					[object] The universal registration object
			site					[string] The site or brand name (hgtv, food, hrpo, etc.)
			userNameWrap			[string:object] Reference to the element that will display the user name
			signInWrap				[string:object] Reference to the element that will house the sign in tools
			signOutWrap				[string:object] Reference to the element that will house the sign out tools
			channelNavWrap			[string:object] Reference to the element that will house the channel/category navigation
			sortbyNavWrap			[string:object] Reference to the element that will house the "Sort By" navigation
			channelNavToggleClass	[string] The alternate class name for channel/category navigation
			onChannelChange			[function] A callback function that fires when the channel/category has changed
			categoryAttr			[string] The name of the attribute to be used to specify the category
			sortbyAttr				[string] The name of the attribute to be used to specify the sort order
			defaultNav				[string:object] Reference to the element that will serve as default navigation
			navClassName			[string] The name of the selected class for navigation
			btnUpload				[string:object] Reference to the element that will serve as the "Upload" button
			btnSignIn				[string:object] Reference to the element that will serve as the "Sign In" button
			btnSignOut				[string:object] Reference to the element that will serve as the "Sign Out" button
			btnBackToGallery		[string:object] Reference to the element that will serve as the "Back To Gallery" button
			uploadURL				[string] URL for the upload page
			galleryURL				[string] URL for the gallery page
*/
(function($) {
	$.fn.pickleSetup = function( options ) {
		var pSetup = new jQuery.PickleSetup(options);
		pSetup.init(this);
	};
})(jQuery);

jQuery.PickleSetup = function( options ) {
	/* set default values for the options */
	var defaults = {
		urUser						: null,
		site						: '',
		userNameWrap				: null,
		signInWrap					: null,
		signOutWrap					: null,
		channelNavWrap				: null,
		sortbyNavWrap				: null,
		channelNavToggleClass		: 'selected',
		onChannelChange				: function() {},
		categoryAttr				: 'cat',
		sortbyAttr					: 'sortby',
		defaultNav					: 'recent',
		navClassName				: 'selected',
		btnUpload					: null,
		btnSignIn					: null,
		btnSignOut					: null,
		btnBackToGallery			: null,
		uploadURL					: '',
		galleryURL					: ''
	};
	/* did any of the options get overriden? */
	this.options = jQuery.extend(defaults, options);
};

/* The heart of the program */
jQuery.extend(jQuery.PickleSetup, {
	prototype: {
		init: function(obj) {
			var pickleSetup = this;
			var sortby = jQuery.PickleSetup.getURLParam('sortby');
			var category = jQuery.PickleSetup.getURLParam('cat');
			var foundCategoryMatch = false;
			
			return obj.each(function(i) {
				/*
					set the href value for every anchor inside sortbyNavWrap to
					galleryURL + '?cat=' + category + '&sortby=' + jQuery(this).attr(pickleSetup.options.sortbyAttr)
				*/
				if ( pickleSetup.options.sortbyNavWrap != null ) {
					jQuery.each(jQuery(pickleSetup.options.sortbyNavWrap).find('a'), function() {
						/* if one of the anchors sortbyAttr matches [sortby] then set it's class to navClassName */
						if ( jQuery(this).attr(pickleSetup.options.sortbyAttr) == sortby )
							jQuery(this).addClass(pickleSetup.options.navClassName);
						jQuery(this).attr('href', pickleSetup.options.galleryURL + '?cat=' + category + '&sortby=' + jQuery(this).attr(pickleSetup.options.sortbyAttr));
					});
				}
				
				/* if the parameter "sortby" is nothing, try and match an element either by id=[sortby] or sortbyAttr=[sortby] */
				if ( sortby == '' ) {
					if ( pickleSetup.options.sortbyAttr != 'id' ) {
						jQuery.each(jQuery('*'), function() {
							if ( jQuery(this).attr(pickleSetup.options.sortbyAttr) == pickleSetup.options.defaultNav )
								jQuery(this).addClass(pickleSetup.options.navClassName);
						});
					} else
						jQuery('#' + pickleSetup.options.defaultNav).addClass(pickleSetup.options.navClassName);
				}
				
				/* if [category] has something then send it's value to callback(onChannelChange) */
				if ( category != '' )
					pickleSetup.options.onChannelChange.call(this, category);
				
				/* handle channel/category navigation */
				/* see if channelNavWrap is in use */
				if ( pickleSetup.options.channelNavWrap != null ) {
					
					/* get all children of channelNavWrap */
					var children = jQuery(pickleSetup.options.channelNavWrap).children();
					
					/* get all anchors of channelNavWrap */
					var all = jQuery(pickleSetup.options.channelNavWrap).find('a');
					
					/*
						go through each child of channelNavWrap and see if categoryAttr=[category]
						and if so, change it's class to channelNavToggleClass
					*/
					jQuery.each(children, function() {
						if ( jQuery(this.childNodes[0]).attr(pickleSetup.options.categoryAttr) == category ) {
							jQuery(this).addClass(pickleSetup.options.channelNavToggleClass);
							foundCategoryMatch = true;
						}
					});
					
					/* if foundCategoryMatch=false, set the first child of channelNavWrap's class to channelNavToggleClass */
					if ( !foundCategoryMatch )
						jQuery(children[0]).addClass(pickleSetup.options.channelNavToggleClass);
						
					/*
						set the href value for each anchor in channelNavWrap to
						galleryURL + '?cat=' + jQuery(this).attr(pickleSetup.options.categoryAttr) + '&sortby=' + sortby
					*/
					jQuery.each(all, function() {
						jQuery(this).attr('href', pickleSetup.options.galleryURL + '?cat=' + jQuery(this).attr(pickleSetup.options.categoryAttr) + '&sortby=' + sortby);
					});
				}
				
				/* setup btnBackToGallery if it's in use */
				if ( pickleSetup.options.btnBackToGallery != null )
					if ( pickleSetup.options.galleryURL != '' )
						jQuery(pickleSetup.options.btnBackToGallery)
							.attr('href', pickleSetup.options.galleryURL + '?sortby=' + pickleSetup.options.defaultNav)
							
				/* setup btnUpload if it's in use */
				if ( pickleSetup.options.btnUpload != null )
					jQuery(pickleSetup.options.btnUpload).attr('href', pickleSetup.options.uploadURL);
					
				/*******************************/
				/* FOLLOWING SECTION IS FOR UR */
				/*******************************/
				
				/* check to see if urUser is being used */
				if ( pickleSetup.options.urUser != null ) {
					
					/* make ursign default to HGTV */
					var ursign = 'http://my.hgtv.com/registration/login.esi?DEST_URL=' + pickleSetup.options.uploadURL;
					
					if ( pickleSetup.options.site != '' ) {
						if ( pickleSetup.options.btnSignIn != '' ) {
							
							/* set ursign based on site */
							switch ( pickleSetup.options.site ) {
								case 'hgtv': { var ursign = 'http://my.hgtv.com/registration/login.esi?DEST_URL=' + pickleSetup.options.uploadURL; break; }
							}
						}
					}
					
					/* setup btnSignIn if it's in use based on which site we're at (defaulting to HGTV) */
					if ( pickleSetup.options.btnSignIn != null )
						jQuery(pickleSetup.options.btnSignIn).attr('href', ursign);
					
					/* user is logged in */
					if ( pickleSetup.options.urUser.isLoggedIn ) {
						
						/* set the innerHTML for userNameWrap if it's in use */
						if ( pickleSetup.options.userNameWrap != null )
							jQuery(pickleSetup.options.userNameWrap).html('Hi, ' + urUser.getEmail());
							
						/* show the signoutWrap if it's being used */
						if ( pickleSetup.options.signOutWrap != null )
							jQuery(pickleSetup.options.signOutWrap).show();
							
						/* setup btnSignOut if it's being used */
						if ( pickleSetup.options.btnSignOut != null ) {
							
							/*
								set the onclick event for btnSignOut to:
								- logout();
								- hide signOutWrap if it's in use
								- show signInWrap if it's in use
							*/
							jQuery(pickleSetup.options.btnSignOut).bind('click', function() {
								urUser.logout();
								if ( pickleSetup.options.signOutWrap != null )
									jQuery(pickleSetup.options.signOutWrap).hide();
								if ( pickleSetup.options.signInWrap != null )
									jQuery(pickleSetup.options.signInWrap).show();
							});
						}
					/* user is NOT logged in */
					} else {
						/* if we're on the upload page, redirect the user to galleryURL */
						if ( jQuery.PickleSetup.checkUploadPage(pickleSetup) )
							window.location.href = pickleSetup.options.galleryURL;
						/* for all other pages other than the upload page, show signInWrap if it's in use */
						if ( pickleSetup.options.signInWrap != null )
							jQuery(pickleSetup.options.signInWrap).show();
					}
				}
			});
		}
	},
	/*
		checkLoginPage()
			Returns true if the current url is the same as the uploadURL option, otherwise returns false
			usage:
				if ( jQuery.PickleSetup.checkUploadPage() ) // do something
	*/
	checkUploadPage: function( self ) {
		if ( self.options.uploadURL != '' )
			if ( window.location.href.indexOf(self.options.uploadURL) != -1 )
				return true;
		return false;
	},
	/*
		getURLParam( param )
			Returns the value associated with [param] in a url.
			usage:
				var sortby = jQuery.PickleSetup.getURLParam('sortby');
	*/
	getURLParam: function( param ) {
		var q = document.location.search || document.location.hash;
		if ( param == null )
			return q;
		if ( q ) {
			var pairs = q.substring(1).split('&');
			for ( var i=0; i<pairs.length; i++ )
				if ( pairs[i].substring(0, pairs[i].indexOf('=')) == param )
					return pairs[i].substring((pairs[i].indexOf('=') + 1));
		}
		return '';
	}
});
