(function($j){
	
	Code.registerNamespace('Website');
	
	Website.Core = Code.Class.extend({
		
		init: function(){
		},
		
		setCookie: function(name,value,expiredays){
			var exdate=new Date();
			exdate.setDate(exdate.getDate() + expiredays);
			document.cookie = name + "=" + escape(value) + ((expiredays==null) ? "" : ";expires=" + exdate.toGMTString());
		},
		
		getCookie: function(name){
			if (document.cookie.length>0)
				{
				c_start=document.cookie.indexOf(name + "=");
				if (c_start!=-1)
					{ 
					c_start = c_start + name.length+1; 
					c_end = document.cookie.indexOf(";",c_start);
					if (c_end==-1) c_end=document.cookie.length;
					return unescape(document.cookie.substring(c_start,c_end));
					} 
				}
			return "";		
		}
		
	});
	Website.Core = new Website.Core();
	
})(jQuery);

(function($j){

	Code.registerNamespace('Website.Pages');

	/*
	 * Class: Website.Pages
	 */
	Website.Pages.Index = Code.Class.extend({

		init: function( dataXMLUrl, resultUrl ){
			var _self = this;
			_self._dataXMLUrl = dataXMLUrl;
			_self._resultsUrl = resultUrl;	
		},

		onReady: function(){
			var _self = this;
			
			//Populate drop downs from XML
			$j.get( _self._dataXMLUrl ,function(html){
				//Store XML for later
				_self._dataXML = html;
				_self.initFromXML(html);
			});
			
			// Fix for IE
			$j('.frow-giftfinder-search-type .frow-radio').click(function() {
				$j('input', this).attr( "checked" , "checked" )
				Website.Pages.Index.loadWhoDropDown();
				Website.Pages.Index.loadInterestsDropDown();
			});

			$j('#giftfinder-form').submit( function(){
				_self.onSearchSubmit();
				return false;
			});

		},

		onSearchSubmit: function(){
			var _self = this;
			var inpCategory;
			var inpCost;
			var inpWho;
			var inpInterest;
			
			inpWho = $j('#GiftFinderWho').val();
			inpCost = $j('#GiftFinderCost').val();
			inpInterest = $j('#GiftFinderInterests').val();
			inpCategory = $j('input[name=GiftFinderType]:checked').val();	
			
			//alert("type = " + inpCategory + ", who = " + inpWho + ", interest = " + inpInterest + ", cost = " + inpCost);
			
			var header = $j('.giftfinder-results-header');
			
			if ( (inpWho == 0) || (inpCost == 0) || (inpInterest == 0) || (inpCategory == 0) ) {

				header.html('');

				if ( inpWho == 0 ) {
					header.append('<strong>You need to select who the gift is for.</strong><br />');
				}

				if ( inpCost == 0 ) {
					header.append('<strong>You need to select how much you would like to spend.</strong><br />');
				}

				if ( inpInterest == 0 ) {
					header.append('<strong>You need to select their interests.</strong><br />');
				}
				
				if ($j(".frow-giftfinder-search-type input:checked").length <= 0) {
					header.append('<strong>You need to select the type of present they would like.</strong><br />');	
				}

				return false;
			}

			//store values
			Website.Core.setCookie("giftfinder-who",inpWho, 1 );
			Website.Core.setCookie("giftfinder-cost",inpCost, 1 );
			Website.Core.setCookie("giftfinder-interest",inpInterest, 1 );
			Website.Core.setCookie("giftfinder-type",inpCategory, 1 );
			
			//Using the values selected, look up the component id's in the XML.
			// Use the component Id's in the url rather than the values selected. There are 3 componentids required.
			if( _self._dataXML != null )
			{
				var cr = $j("selection > cr[ct='" + inpCategory + "'][in='" + inpInterest + "'][rp='" + inpWho + "'][bg='" + inpCost + "']",_self._dataXML);
				var len = $j(cr).length;
				if(  len <= 0 ){
					header.html('');
					header.append( "<strong>No results could be found. Please select another criteria.</strong>" );
					return false;
				} 
				
				var rs = $j("rs",cr);

				var comp1 = rs.attr("c1");
				var comp2 = rs.attr("c2");
				var comp3 = rs.attr("c3");
				
				//alert("c1 = " + comp1 + ", c2 = " + comp2 + ", c3 = " + comp3);

				// Build .giftfinder-results-header content
				header.html('<img alt="" src="graphics/giftfinder/ajax-loader.gif" /> Loading results for your <strong>' + $j('#GiftFinderWho option:selected').html() + '</strong> from <strong>' + $j('#GiftFinderCost option:selected').html() + '</strong>.');

				if (!$j.browser.safari) {
					$j('div.giftfinder-results-container').html('').hide();
				}
				
				//Parameter names defined here
				$j.get(_self._resultsUrl ,{ c1: comp1, c2: comp2, c3: comp3 }, function(html){
					_self.loadResults(html);
				});

			}
			else
			{
					header.append( "<strong>The page encountered a problem returning your results. Please refresh the page and try again.</strong>" );
					return false;			
			};
			

			return false;
		},
		
		loadResults: function(html){
			$j('div.giftfinder-results-container').hide().html(html);
			// Add class to carousel container on load so jCarousel can be initialised
			$j('.giftfinder-results-carousel').addClass('js-giftfinder-results-carousel');

			$j('.giftfinder-results-header').animate({opacity: 1.0}, 1000,function(){
				// Build .giftfinder-results-header content
				$j('div.giftfinder-results-container').show();
	    		$j('.giftfinder-results-header').animate({opacity: 1.0}, 1000,function(){
					$j('.giftfinder-results-header').html('This is what we found for your <strong>' + $j('#GiftFinderWho option:selected').html() + '</strong> from <strong>' + $j('#GiftFinderCost option:selected').html() + '</strong>.');
					if ($j.browser.safari) {
						// if Safari we need to do a walk around due to webkit viewpoint
						var safari_initCallback = function(carousel) {
							carousel.setup();
							carousel.prev();
						};
						$j('.js-giftfinder-results-carousel').jcarousel({scroll: 1,initCallback: safari_initCallback});
					} else {
						$j('.js-giftfinder-results-carousel').jcarousel({scroll: 1});
					}
				});
		    });
		},
		
		initFromXML: function(xml){
			var _self = this;		
			_self.loadCategory( xml,"GiftFinderType1", 0 );
			_self.loadCategory( xml,"GiftFinderType2", 1 );
			_self.loadCategory( xml,"GiftFinderType3", 2 );
			
			var ctype = Website.Core.getCookie( "giftfinder-type" );				
			if( ctype == "" ) {
				$j('#GiftFinderType1').attr( "checked" , "checked" )
				ctype = "1";
			}
			
			if( ctype == 1 ){ $j('#GiftFinderType1').attr( "checked" , "checked" ) };
			if( ctype == 2 ){ $j('#GiftFinderType2').attr( "checked" , "checked" ) };
			if( ctype == 3 ){ $j('#GiftFinderType3').attr( "checked" , "checked" ) };

			_self.loadWhoDropDown();	
			_self.loadInterestsDropDown();
			_self.loadBudgetDropDown();
						
			//alert("cwho = " + cwho + ", cinterest = " + cinterest + ", ccost = " + ccost);
			
			$j('input[name=GiftFinderType]').each(function() {
				$j(this).bind("click", function(){
					Website.Pages.Index.loadWhoDropDown();
					Website.Pages.Index.loadInterestsDropDown();
				})
			});	
			$j('#GiftFinderWho').bind("change", function(){Website.Pages.Index.loadInterestsDropDown();});
	
			var cwho = Website.Core.getCookie( "giftfinder-who" );
			var cinterest = Website.Core.getCookie( "giftfinder-interest" );
			var ccost = Website.Core.getCookie( "giftfinder-cost" );
			if ( (cwho != "") && (cinterest != "") && (ccost != "") ) {
				//alert("cwho = " + cwho + ", cinterest = " + cinterest + ", ccost = " + ccost);
				_self.onSearchSubmit();
			}
		},
		
		loadWhoDropDown: function(){
			var _self = this;
			var ctype = $j('input[name=GiftFinderType]:checked').val();
			
			var cwho = Website.Core.getCookie( "giftfinder-who" );
			//alert("load who, type = " + ctype);
			
			$j("#GiftFinderWho").empty();	
			var items = $j("categories > ct[vl='" + ctype + "'] > recipients > *", _self._dataXML);

			var options = '';
			for(var i = 0; i < items.length; i++){
				var name = $j(items[i]).attr("nm");
				var val =  $j(items[i]).attr("vl");
				options += '<option value="' + val + '"';
				if (val == cwho) options += ' selected="selected"';
				options += '>' + name + '</option>';
			}
			$j("#GiftFinderWho").append( options );	
			//alert(options);	
		},
		
		loadInterestsDropDown: function(){
			var _self = this;
			
			var ctype = $j('input[name=GiftFinderType]:checked').val();
			var cwho = $j('#GiftFinderWho').val();
			var cinterest = Website.Core.getCookie( "giftfinder-interest" );
			
			//alert("load interest, type = " + ctype + ", who = " + cwho);
			
			var showInterests = $j("categories > ct[vl='" + ctype + "'] > recipients > rp[vl='" + cwho + "']", _self._dataXML);
			
			$j("#GiftFinderInterests").empty();	
			
			var options = '';
			if($j('input[name=GiftFinderType]:checked').val() == 3){
				options += '<option value="1" selected="selected">Not applicable</option>';
			}else {
				if(showInterests.length > 0 && showInterests.attr("in") == 1) {
					var items = $j("interests > *",_self._dataXML)
					for(var i = 0; i < items.length; i++){
						var name = $j(items[i]).attr("nm");
						var val =  $j(items[i]).attr("vl");
						options += '<option value="' + val + '"';
						if (val == cinterest) options += ' selected="selected"';
						options += '>' + name + '</option>';
					}
				} else {
					options += '<option value="1" selected="selected">Not applicable</option>';
				}
			}
			$j("#GiftFinderInterests").append( options );		
		},
		
		loadBudgetDropDown: function(){
			var _self = this;
			
			var ccost = Website.Core.getCookie( "giftfinder-cost" );
						
			var items = $j("budgets > *",_self._dataXML);
			var options = '';
			for(var i = 0; i < items.length; i++){
				var name = $j(items[i]).attr("nm");
				var val =  $j(items[i]).attr("vl");
				options += '<option value="' + val + '"';
				if (val == ccost) options += ' selected="selected"';
				options += '>' + name + '</option>';
			}
			$j("#GiftFinderCost").append( options );	
			//alert(options);	
		},
		
		loadCategory: function(xml,elementId,idx){
			var cat = $j( "categories > ct:eq(" + idx + ")",xml);
			$j("#" + elementId).attr( "value" , cat.attr("vl") );		
		},
		
		// Private
		_dataXMLUrl:null,
		_dataXML: null,
		_resultsUrl: null
	
		
		// Public

		
		

	});
	// Make Website.Pages.Index a singleton
	Website.Pages.Index = new Website.Pages.Index('giftfinder.xml','giftFinderResults.do' );

	$j().ready(function(){
		Website.Pages.Index.onReady();
	});

})(jQuery);