// firebug degradiation
if (! ("console" in window) || !("firebug" in console)) {
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group"
                 , "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
    window.console = {};
    for (var i = 0; i <names.length; ++i) window.console[names[i]] = function() {};
}
var monthNames = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];

var resizeCol = function(){$("#content-left, #content-body").equalizeCols();};
var resetList = function(){ 
				$("#targetcruiselist, .paging, .no-results, .pagingInfo").fadeOut("normal", function(){
						$(".results-loading").fadeIn("fast");
						resizeCol();
						if(jQuery.browser.msie && parseInt(jQuery.browser.version) == 6){
							
						}
				}); 
};



var builtInteractions = function() { 
	$("#qm1").css("z-index", 100);
	//$('table.detail').each( function(){ $(this).find('>tbody>tr:odd').addClass('odd').end().find('>tbody>tr:even').addClass('even'); } );
	//$('tr>td:last-child,tr>th:last-child,ul li:last-child').addClass('last-child');
	//$('tr>td:first-child,tr>th:first-child,ul li:first-child').addClass('first-child');
	//if($(".last-child").hasClass("first-child")){
	//	$(".last-child.first-child").each( function() {
		//	$(this).removeClass("first-child").removeClass("last-child").addClass("only-child");   
		//});
  // }
   
   $(".cruise-item .title").live("mouseover", function() {
			$(this).css({"cursor": "pointer", "background-position": "left bottom"});
		}).
   	live("mouseout", function() {
			$(this).css({"cursor": "none", "background-position": "left top"});
		}							   
	).live("click", function(){
		$(this).find("a").trigger("click");
		return false;
	});
   $('a.func-toggle').live("click",function(event){
			//console.debug("hi %o  event %o", $(this), event);
			var _href = $(this).attr('href');
			var _obj = $(_href);
			//console.debug("href %s obj %o  class %b visibility %s", _href, _obj, _obj.hasClass('hidden'), _obj.css("display"));
			if(_obj.hasClass('hidden')==true){
				_obj.slideDown("slow", function(){ _obj.removeClass('hidden'); resizeCol();});
				$(this).parent().addClass('show-hide-caption').trackLink({buttonName: "Show Searchbox Feature"  });
			}else{
				_obj.slideUp("slow", function(){ _obj.addClass('hidden'); resizeCol();});
				$(this).parent().removeClass('show-hide-caption').trackLink({buttonName: "Hide Searchbox Feature"  });
			}
			resizeCol();
			event.preventDefault(); 
			event.stopPropagation();
			return false;
		});
	$('a.func-toggle-detail').live("click",function(event){
			var _obj = $(this).parents('div.cruise-item')
			if(_obj.hasClass('cruise-item-show')==true){
				_obj.find(".sailings").slideUp("fast", function(){
					_obj.removeClass('cruise-item-show').trackLink({buttonName: "Show Cruise Item"  });
					resizeCol();
				});
			}else{
				_obj.find(".sailings").slideDown("fast", function() {
					setTableSize(event, true);
					_obj.addClass('cruise-item-show').trackLink({buttonName: "Hide Cruise Item"  });
					resizeCol();	
				});
			}
			resizeCol();
			event.preventDefault(); 
			event.stopPropagation();
			return false;
		});
	
	$("a.func-toggle-more").live("click", function(event){
		
		var $cruiseItem = $(this).parents(".cruise-item");
		//alert("clicked func-toggle-more");
		if($cruiseItem.hasClass(".cruise-item-show") == false) {
			$(".title a", $cruiseItem).trigger("click");
			setTableSize(event, true);
		}
		else {
			var hidden = $("tbody tr:hidden",$cruiseItem).length;
			
			if(jQuery.browser.msie && parseInt(jQuery.browser.version) ==8){
				var count = 0;
				 $("tbody tr", $cruiseItem).each(function(){
					//alert("display attr:"+ $(this).css('display') + " truth:"+($(this).css('display')=='none'));
					if($(this).css('display') == 'none') {
						count++;
						//alert("updated count:"+count);
					}
				 });
				 hidden = count;
			}
			//alert("hidden rows:"+hidden);
			if(hidden > 0)
			setTableSize(event, false); // changed because now initinally opened
		}
		//console.debug("%d %o", $(this).length, $(this));
		/* function to figure out how many more rows to show if less than 10, show all, add in incriments of 5 */
		$(this).trackLink({buttonName: "Show More Cruise Item"  });
		resizeCol();
		return false;			
	});
	
	// initinalize as closed
	$("#area-favorites").addClass("closed");
	$('#area-favorites .btn-expand').live("click",function() {
		var $btn = $(this);
		var favCount = parseInt($('#area-favorites tbody tr').length);
		//console.debug("fav count %d newCount %d", favCount, (1+favCount) );
		if(favCount >= 0) {
			if($("#area-favorites").hasClass("closed")){
				// show the items
				$("#area-favorites .cruise-item").slideDown("normal", function(){
					$(this).removeClass("hid");	
					$("#favcount").html($('#area-favorites tbody tr').length);
					$btn.parents("#area-favorites").removeClass("closed").trackLink({buttonName: "Show Saved Favs"  });
					resizeCol();																 
				});
				/*
				if($.browser.msie && parseInt(jQuery.browser.version) < 6) {
					$("#area-favorites .cruise-item").show("fast", function(){ 
						$(this).removeClass("hid");	
						$("#favcount").html($('#area-favorites tbody tr').length);
						$btn.parents("#area-favorites").removeClass("closed").trackLink({buttonName: "Hide Saved Favs"  });
						resizeCol();																 
					});
				}
				*/
				
			}
			else {
				//hide the items
				$("#area-favorites .cruise-item").slideUp("normal", function(){
					$(this).addClass("hid");
					$("#favcount").html($('#area-favorites tbody tr').length);
					$btn.parents("#area-favorites").addClass("closed");
					$(this).buildFavs();
					resizeCol();
				});
				/*
				if($.browser.msie && parseInt(jQuery.browser.version) < 6) {
					$("#area-favorites .cruise-item").hide("fast", function(){ 
						$(this).removeClass("hid");	
						$("#favcount").html($('#area-favorites tbody tr').length);
						$btn.parents("#area-favorites").removeClass("closed");
						resizeCol();																 
					});
				}
				*/
				
				
			}
		 }
		 
		return false;											
	});
	
	var showMore = "Show <span></span> more";
	var viewMore = "View X date<span>s</span> &amp price<span>s</span> in this set";
	$(".expand").live("mouseover",function() {
		//alert("moved in");
		$(this).parent().addClass("hovered");
		
		if($(this)[0].tagName.toLowerCase() == "div") {
			var classNames = $("ul", this).attr("class");
			var firstChild = $(".first-child a", this);
			firstChild.html(viewMore.replace(/X/,classNames)).addClass((parseInt(classNames) == 1) ? "single" : "");
		}
		return false;
	})
	.live("mouseout", function() {
		//alert("moved out");
		$(this).parent().removeClass("hovered");
		
		if($(this)[0].tagName.toLowerCase() == "div") {
			//$(this).css("cursor", "none");
			var classNames = $("ul", this).attr("class");
			var firstChild = $(".first-child a", this);
			firstChild.html(showMore).removeClass("single");
		}
		return false;
	});
	$("div.expand").live("mouseover", function() {
		$(this).css("cursor", "pointer");										   
	}).
	live("mouseout", function() {
		$(this).css("cursor", "none");
	})
	.live("click", function() {
		$(this).parents(".cruise-item").find("h3 a").trigger("click");
		//$(this).parents(".cruise-item").find("
	});
	
	var helpHtml = "This sailing has been added to your favorites at the top of the page. <a href='#area-favorites' class='view-favourites anchorLink'>View favorites</a>";
	$("#cruise-list tbody .star").live("click", function(event){
		var favCount = parseInt($("#area-favorites tbody tr").length);
		var redraw = false;
		//console.debug("favCount %d  favCount+1 %d", favCount, (1+favCount) );
		//alert("favCount "+favCount+" favcount+1 "+ (1+parseInt(favCount)) );
		/*	code for 5 favs */
			if(favCount+1 < 6) { 
			var $trParent = $(this).parents("tr").addClass("help")
			var cruiseId = $trParent.attr("id");
			$(this).parent().addClass("selected");
			//console.debug("fav clicked %s %o siblings %o", cruiseId, $(this), $(this).parent().next().nextAll());
			var $nextTd = $(this).parent().next();
			$nextTd
					.nextAll()
					.remove()
				.end()
				.attr("colSpan", 6)
				.html(helpHtml);
			
			//console.debug("favs has class %s", $('#area-favorites').attr("class"));
			/*
			if(!$('#area-favorites').hasClass("closed") ){
				$('#area-favorites').data("prevOpened", true);
				$('#area-favorites .btn-expand').trigger("click");
				
				console.debug("has class closed %o", $('#area-favorites').data("prevOpened"));
				/ * temp code to trigger favorites being done * /
				//favoritesDone();
				//alert("fetching new favorites");
			
			}
			else {
				*/
				redraw = true;	
			//}
			
			// view favourites link is that the lightbox?
			//console.debug("fav id: %d calling AddFav", cruiseId);
			$(this).attr("href", "#").trackLink({buttonName: "Add Favs", evarTripId: cruiseId, favs: true  });
			//console.log("Adding a fav");
			AddFavorite(cruiseId, redraw);
			//console.log("returned from addingFav");
			//$("#favcount").text(favCount+1)
		 //code for 5 favs	
		}
		else { // have five trigger lightbox 
		//alert("over five open lightbox")
			//console.debug("count greater than 5 %d",(parseInt(favCount)+1) );
			$("#removeFavsLink").trigger("click");
		}
		
		event.preventDefault(); 
		event.stopPropagation();
		return false;
	});
	
	
	$(".favs .info").live("mouseover", function(e) {
		var locClass = ($(this).parents(".detail").parent().hasClass("sailings")) ? "add": "";
		$("#favText").css({"left": e.pageX +15, "top": e.pageY -10}).addClass(locClass).fadeIn("fast"); 
	})
	.live("mouseout", function(e) {
		$("#favText").fadeOut("fast");					   
	});
	var cruiseFrom = false;
	$("p.cruise-from").live("mouseover", function(e) {
		if(!cruiseFrom) {
			var width_window = $(window).width();
			var height_window = $(window).height();
			var offset = $("#condText").offset();
			var left = offset.left;
			var top = offset.top;
			var width = $("#condText").outerWidth();
			var height = $("#condText").outerHeight()
			var margin = (jQuery.browser.mozilla) ? 25 : height;
			
			var changeY = (jQuery.browser.mozilla) ? height*1.5 : height*1.5 ;
			
			var newLeft = (width_window < (left + width + margin)) ? e.pageX-margin : e.pageX-width-margin;
			var newTop = e.pageY-changeY;
			//newTop = (newTop < 0) ?e.pageY-top : top-height;	
			//console.debug("width_window: %d ofset 25  condit width: %d  height: %d   ofset: %o  newLeft: %o newTop: %o", 
			//width_window, width, height, $("#condText").offset(), newLeft, newTop);
			//console.debug("width_height: %d  top: %d e.pageY %d height: %d   ofset: %o newTop: %o", 
			//height_window, top, e.pageY, height, $("#condText").offset(), newTop);
			
		//	console.debug("mouse x: %d  y: %d  offset x: %d  y: %d  \nnewTop: %d  el height %d", e.pageX, e.pageY, left, top, newTop, height);
			e.preventDefault();
			e.stopPropagation();
		
			if($("#condText").css("display") == "none")
			$("#condText").css({"left": newLeft, "top": newTop}).fadeIn("fast");										 
		}
		else {
			cruiseFrom = true;
			
		}
	})
	.live("mouseout", function(e) {
		$("#condText").fadeOut("fast");						   
		cruseFrom = false;
	});
	
   if($.browser.msie){
		if(parseInt($.browser.version, 10) == 7) {
			$(".cruise-item tr.expand li").css("display", "inline");
			//alert("im ie7");
		}
	}
	$("a.anchorLink").anchorAnimate();
	var selDates = $("#ctl00_ContentPlaceHolder1_seldates");
	selDates.find("[value*=',']").addClass("optGroup").end().find("[value='']").addClass("optGroup");
	/*
	if($("#share_favorites").length == 1) {
		$("#share_favorites").shareForm();	
	}
	
	$(".prevSearchResult").live("click", function() {
		cclSailing.SearchPrev( null, null, $.cookie(PrevResult_Cookie_name));										  
	});
	*/
	$("body").one("mousemove", function() {
		resizeCol();						  
	});
	$(window).one("scroll", function() {
		resizeCol();						  								 
	});

	
};
var rowIncr = 5;
var showMore = "Show <span></span> more";
function setTableSize(event, initinal){
	//console.log("Setting the table size");
	var $targ = $(event.target);
	var $tbody = ($targ.parents(".detail").length == 1) ? $targ.parents(".detail").find("tbody") : $targ.parents(".cruise-item").find(".detail tbody");
	var totalRows = $("tr", $tbody).length;
	var rowsShowing  = ($tbody.data("rowsActive")) ?  parseInt($tbody.data("rowsActive").rowsShowing) : 
	(($(".show", $tbody).length > 0) ? $(".show", $tbody).length : 0);
	var rowsHidden = (totalRows - rowsShowing >0 ) ? totalRows - rowsShowing : totalRows;
	var rows = 0; var clickedCount = 1; 
	var dataSetError = true;
	
	//alert("is this triggering");
	if(initinal){
		//console.debug("totalRows: %d rowIncr %d rowsHidden %d", totalRows, rowIncr, rowsHidden);
		if(totalRows > rowIncr || rowsHidden == rowIncr) {
			rows = rowIncr;	
		}
		else if(rowsHidden < rowIncr) {
			rows = rowsHidden;
		}

		$("tr", $tbody).hide();
		$tbody.parent().find("tfoot li.first-child").show();
		//console.debug("rows %d %o", rows, $targ);
	}
	else {
		//alert("is this triggering now for final update")
		//console.debug("setting rows  rows: %s  rowsShowing %s  rowsHidden %s rowIncr %d" , rows, rowsShowing, rowsHidden, rowIncr);
		//console.debug("stuff %d  %d  %b", rowsShowing+rowIncr, totalRows, (rowsShowing+rowIncr > totalRows)); 
		if(rowsShowing+rowIncr <= totalRows) {
			rows = rowsShowing+rowIncr;
		}
		else if (rowsShowing+rowIncr > totalRows) {
			rows = totalRows;
			var text = $("span", $targ).text();
			//alert("why isnt it unbinding the click");
			$("span", $targ).text("");
			$targ.unbind("click"); //.css("visibility", "hidden");
		}
		
		//if(!dataSetError)
		try {
		clickedCount = 1+parseInt($tbody.data("rowsActive").clickedCount);
		}
		catch(e) {  } // use a try catch for ie alert("error "+e.message); }
	}
	$tbody.data("rowsActive", {rowsShowing: rows, rowsHidden: rowsHidden, clickedCount: Math.ceil(rows/5)});
	//console.debug("updated rows obj %o", $tbody.data("rowsActive"));
	//alert("browser msie " + jQuery.browser.msie + " version " + jQuery.browser.version + " parsedVersion " + parseInt(jQuery.browser.version));
	
	var count = 1;
	//console.debug("number of rows: %d  rowsShowing: %d", rows, rowsShowing);
	if($tbody.data("rowsActive").rowsHidden > 0) {
		if(jQuery.browser.msie && parseInt(jQuery.browser.version) ==8){
			var len = 0; var i=0;
			
			if(initinal) {
				len = (rows > rowIncr || rows == rowIncr) ? rowIncr : rows ;
			}
			else {
				var count=0;
				 $("tr", $tbody).each(function(){
					if($(this).css('display') == 'block') {
						count++;
					}
				 });
				 i = count;
				 len = ((rows-i) > rowIncr || (rows-i) == rowIncr) ? rowIncr+i : rows ;
			}
			//alert("rows: "+ rows + " rowIncr: "+ rowIncr + " len: "+len + " i: "+i+" truth: "+(i < len));
			for(; i < len; i++) {
				$("tr:eq("+i+")", $tbody).each(function() {
				//alert("count = "+i + " rows: "+rows);
					$(this).css("display", "block");
				});
				if(i+1 == len) {
					$("tr:eq("+i+")", $tbody).each(function() {
				//alert("count = "+i + " rows: "+rows);
						$(this).css("display", "block");
						resizeCol();
					});
				}
				
			}
			var $tBody = $targ.parents(".cruise-item").find(".detail tbody")
			var $moreStuff =  $targ.parents(".cruise-item").find("tfoot .func-toggle-more span");
			//alert("rows :"+ rows + " total Rows: " + totalRows + "len:"+len);
			//alert("moreText " + $moreStuff.text() + " stuff: "+ showMore + " hidden rows" + (totalRows-len) + " total rows:"+totalRows);
			if(rows < totalRows) {
					//console.debug("moreText %o stuff %s", $moreStuff.text(), showMore + $moreStuff.text());
					var extra = ((totalRows-len) > 4) ? "(5) " : ( ((totalRows-len) > 0) ? "("+ (totalRows-len) +") ":"" );
					//alert("new more string: "+extra+ " moreStuff Len:"+$moreStuff.length);
					//console.debug("new more string %s", extra);
					$moreStuff.text(extra);
					//var text = $targ.text();.paren
					//text += "("+rowsHidden+")";
			}
			else {
				$moreStuff.text("");
				$moreStuff.parent().css("display", "none");
			}
			resizeCol();
		}
		else {		
			var len = 0; var i=0;
			
			if(initinal) {
				len = (rows > rowIncr || rows == rowIncr) ? rowIncr : rows ;
			}
			else {
				var count=0;
				$("tr", $tbody).each(function(){
					//console.debug("display side %o", $(this).css('display'));
					if($(this).css('display') == 'table-row' || $(this).css('display') == 'block') {
						count++;
					}
				 });
				 //alert("ie6 test: " + count);
				 i = count;
				 len = ((rows-i) > rowIncr || (rows-i) == rowIncr) ? rowIncr+i : rows ;
				// console.debug("count: %d  new Len: %d", count, len);
			}
			//console.debug("rows: %d  rowIncr: %d  len: %d  i: %d   truth: %b", rows, rowIncr, len, i,(i < len));
			for(; i < len; i++) {
				$("tr:eq("+i+")", $tbody).fadeIn("fast");
				if(i+1 == len) {
					$("tr:eq("+i+")", $tbody).fadeIn("fast", function(){ resizeCol(); });
				}
				
			}
			var $tBody = $targ.parents(".cruise-item").find(".detail tbody")
			var $moreStuff =  $targ.parents(".cruise-item").find("tfoot .func-toggle-more span");
			//console.debug("rows: %d  total Rows: %d  len: %d", rows, totalRows,len);
			//console.debug("moreText: %s   stuff: %s  hidden rows: %d  total rows: %d", $moreStuff.text(), showMore, (totalRows-len),totalRows);
			if(rows < totalRows) {
				//	console.debug("moreText %o stuff %s", $moreStuff.text(), showMore + $moreStuff.text());
					var extra = ((totalRows-len) > 4) ? "(5) " : ( ((totalRows-len) > 0) ? "("+ (totalRows-len) +") ":"" );
					//alert("new more string: "+extra+ " moreStuff Len:"+$moreStuff.length);
//					console.debug("new more string %s", extra);
					$moreStuff.text(extra);
					//var text = $targ.text();.paren
					//text += "("+rowsHidden+")";
			}
			else {
				$moreStuff.text("");
				$moreStuff.parent().css("display", "none");
			}
			resizeCol();
		}
	}
	resizeCol();
	return false;
}


function done(context) {
	//console.debug("json obj %o", context.d);
	
	//if($("
	//context = JSON.parse(context);
	//builtInteractions();
	
		//console.debug("obj %o", context);
    var lastPage = context.d.LastPage;
		var currPage = (context.d.CurrentPage == null) ? 1: context.d.CurrentPage;
	    
		$(".paging").buildPager({
			last: lastPage,
			curr: currPage,
			range: searchOptions.itemsPerPage,
			count: context.d.TotalResultsCount,
			showingRange: context.d.CurrentResultsCount
		});
//		console.debug("area-favs cruise-item: %o cruise-list cruise-item %o",  $("#area-favorites .cruise-item"),
//																				 $("#cruise-list .cruise-item"));

		try {
			if(context.d.TotalResultsCount > 0 ) {
			}
		}
		catch(e) {console.debug("error %o", e); }

		if(context.d.TotalResultsCount > 0 ) {
		
		
		var itineraries = $('#cruise-list').mapDirective({
            '.cruise-item': 'itn <- d.Itineraries',
            'a.func-toggle-detail': 'itn.ItnDescriptionText',
            'p.cruise-from span': 'itn.FromPriceText',
            'a.departFrom': 'itn.DeparturePortText',
            'a.departFrom[href]' : '/cms/search2/lightboxes/PortsOfCall.aspx#{itn.DeparturePortHref}&KeepThis=true&TB_iframe=true&width=630&height=570',
            'a.shipName': 'itn.ShipText',
	'a.shipName[title]+': 'itn.ShipText',
            'a.shipName[href]': '/cms/search2/lightboxes/shiphighlights.aspx#{itn.ShipHref}&KeepThis=true&TB_iframe=true&width=700&height=580',
            'th.interior a[href]': '/cms/search2/lightboxes/stateroom.aspx#{itn.INHref}&KeepThis=true&TB_iframe=true&width=700&height=580',
            'th.ocean a[href]': '/cms/search2/lightboxes/stateroom.aspx#{itn.OVHref}&KeepThis=true&TB_iframe=true&width=700&height=580',
            'th.balcony a[href]': '/cms/search2/lightboxes/stateroom.aspx#{itn.OBHref}&KeepThis=true&TB_iframe=true&width=700&height=580',
            'th.suites a[href]': '/cms/search2/lightboxes/stateroom.aspx#{itn.SUHref}&KeepThis=true&TB_iframe=true&width=700&height=580',
			'div.expand .count': 'itn.HiddenSailingsCount',
			'div.expand li[class]': function(int) {
				//console.debug("added class %s  %d", ((int.item.HiddenSailingsCount < 2) ? "single" : ""), int.item.HiddenSailingsCount );
				return (int.item.HiddenSailingsCount < 2) ? "single" : "";
			},
			'tfoot .showRows[class]+': function(int) {
				return (int.item.HiddenSailingsCount < 6) ? "hid" : "";
			},
			'tfoot .func-toggle-more span': function(int) {
				return "(" + ((int.item.HiddenSailingsCount > 5) ? 5 : int.item.HiddenSailingsCount) + ") " ;
			},
			'p.btn-details a[href]': '/Itinerary.aspx#{itn.DetailsHREF}'
        });

        var sailings = $('table.detail', itineraries)
  .mapDirective({
      'tbody tr': 's <- itn.Sailings',
	  'tbody tr[class]+': function(s){
		var oddEven =  (s.pos % 2 == 0) ? 'even' : 'odd';
     	var firstLast = (s.pos == 0) ? 'first-child': (s.pos == s.items.length -1) ? 'last-child':'';
		var display = (s.item.Style != null) ? s.item.Style : "" ;
		//console.debug("s %o", s.item);
      	return oddEven + ' ' + firstLast + ' ' + s.item.Style; 
    	},
		'tbody tr[id]': 's.SailingId',
      'td.dates': 's.CalendarDaysText',
      'td.interior': 's.INPriceText',
      'td.ocean': 's.OVPriceText',
      'td.balcony': 's.BAPriceText',
      'td.suites': 's.STPriceText',
      'td.details a[href]':'/Itinerary.aspx#{s.DetailsHREF}'
  });

 var ports = $('span.ports', itineraries)
  .mapDirective({
      'a': 'p <- itn.Ports',
      'a.portName': 'p.PortText',
      'a.portName[href]': '/cms/search2/lightboxes/PortsOfCall.aspx#{p.PortHref}&KeepThis=true&TB_iframe=true&width=630&height=570'
	
  });

// paging doesnt exactly have iteration, how to handle it?
// have last page have current page

		


        $('div.sailings', itineraries).html(sailings);
        $('span.ports', itineraries).html(ports);
		if(!compiled) {
        	$p.compile(itineraries, 'itinerary');
        	compiled=true;
			searchOptions.firstLoad = false;
		}
		//console.debug("itinerary %o", itineraries); 
        var html = $p.render('itinerary', context);
		
		//console.debug("cruise list %o  targetcruiselist %o", html, $('#targetcruiselist'));
		
		//console.log("fade in poof");
		
		$('#targetcruiselist').html(html).fadeIn("fast", function(){ 
			$(".results-loading, .no-results").hide();
			$(".paging").show("normal");
			
			resizeCol();
			builtInteractions();
			//console.log("loading cruiste list");
			
			
			//$(this).find(".cruise-item .func-toggle-detail").trigger("click");
			//$(this).find(".cruise-item:first .sailings").height("100%");
			searchOptions.failCnt = 0;
			cache.push(buildNewUrl(""));
			//var query = buildNewUrl("")
			//updateCache(query, context);
		});
		//alert("browser msie " + $.browser.msie + " version: "+ jQuery.browser.version);
		
			if($.browser.msie && parseInt(jQuery.browser.version) < 8) {
			   $("#targetcruiselist .cruise-item").stackOrderIEFix();
			}
			else if($.browser.msie && parseInt(jQuery.browser.version) == 8){
				$("a.more-details").each(function(a){
					var text = $(this).text();
					var imgPath = $(this).css("backgroundImage");
					var path = new String(imgPath.match(/\(.*\)/gi));
					path = path.substring(2);
					path = path.substring(0, path.length-2);
					//alert("path:" + path);
					
				//console.debug("imgPath %o regEx %o  path %o", imgPath, imgPath.match(/\(.*\)/gi), path);
				
					$(this).css({"text-indent": 0, "background": "none"}).text("");
					$("<img>").attr("src", path).attr("title", text).appendTo($(this));
									
				});
				
				$("#targetcruiselist a.star").each(function(a, domEl){
					var text = $(domEl).text();
					var imgPath = $(domEl).css("backgroundImage");
					var path = new String(imgPath.match(/\(.*\)/gi));
					path = path.substring(2);
					path = path.substring(0, path.length-2);
					
					if($(domEl).parent().hasClass("selected")){
						path = path.replace("favourite-icn.png", "favorite-icon-on.png");
					}
					else {
						path = path.replace("favourite-icn.png", "favorite-icon-off.png");
					}
					//alert("path:" + path);
					
					//if(a > 5){
					
					//return false;
					//}
					//console.debug("imgPath %o regEx %o  path %o", imgPath, imgPath.match(/\(.*\)/gi), path);
									
					$(domEl).css({"text-indent": 0, "background": "none"}).text("");
					$("<img>").attr("src", path).attr("title", text).appendTo($(domEl));
					
					$(domEl).hover(function(){
						if(!$(this).parent().hasClass("selected")){
							var img = $(this).find("img");
							var src2 = new String(img.attr("src")).replace("-off", "-on");
					   		$(this).find("img").attr("src", src2); 
					   	}
					}, function(){
						if(!$(this).parent().hasClass("selected")){
							var img = $(this).find("img");
							var src2 = new String(img.attr("src")).replace("-on", "-off");
					   		$(this).find("img").attr("src", src2);
					   	}
					}).click(function(){
					//alert("click for star");
						var img = $(this).find("img");
						var src2 = new String(img.attr("src")).replace("-off", "-on");
					   	$(this).find("img").attr("src", src2); 
					});
				});
				
				
			}
		
		}
		else {
			//console.debug("no results %d",  context.d.TotalResultsCount);
			$(".paging, .results-loading").hide();
			$(".no-results").fadeIn("fast", function(){
				$(".paging, .results-loading").hide("fast");									 
			});
		}
		
		
		
//		console.debug("area-favs cruise-item: %o",  $("#area-favorites .cruise-item"));
		tb_init('a.thickbox, area.thickbox, input.thickbox');
		
    }

function failed(msg, status, error) {
    //alert("The response failed\n"  + msg.message); 
		//console.debug("msg %o status %o error %o", msg, status, error);
		
		// try twice if service errors
		if(searchOptions.failCnt < 2) {
		//parseSearchString(cclSailing); 
			cclSailing.SearchAsync(done, failed, searchOptions.pageSize, 1, searchOptions.sortExpression);
			SearchFilter(failedFilter, "");
			searchOptions.failCnt++;
		}
		else {
			builtInteractions();
			$(".paging, .results-loading").hide();
			$(".no-results").fadeIn();
		}
}


    function favoritesDone(context) {

        // add call to update header count
        favoritesDoneHeader(context);
	//console.debug("favourites json obj %o", context.d);
	if(context.d.Itineraries != null){
		
		//console.debug("itineraries: %o  length: %d  cruise-item: %o", context.d.Itineraries,context.d.Itineraries.length,
		//$("#area-favorites .cruise-item"));
		
		if($("#area-favorites .cruise-item").length == 0) {
			//console.debug("cruise-item not found %d", $("#area-favorites .cruise-item").length);
			$("#area-favorites").append(favsItem);
		}
		
		
       	 var itineraries = $('#area-favorites').mapDirective({
            'div.cruise-item': 'itn <- d.Itineraries',
            'h3.itnTitle': 'itn.ItnDescriptionText',
            'a.departFrom': 'itn.DeparturePortText',
            'a.departFrom[href]' : '/cms/search2/lightboxes/PortsOfCall.aspx#{itn.DeparturePortHref}&KeepThis=true&TB_iframe=true&width=630&height=570',
            'a.shipName': 'itn.ShipText',
	'a.shipName[title]+': 'itn.ShipText',
            'a.shipName[href]': '/cms/search2/lightboxes/shiphighlights.aspx#{itn.ShipHref}&KeepThis=true&TB_iframe=true&width=700&height=580',
            'th.interior a[href]': '/cms/search2/lightboxes/stateroom.aspx#{itn.INHref}&KeepThis=true&TB_iframe=true&width=700&height=580',
            'th.ocean a[href]': '/cms/search2/lightboxes/stateroom.aspx#{itn.OVHref}&KeepThis=true&TB_iframe=true&width=700&height=580',
            'th.balcony a[href]': '/cms/search2/lightboxes/stateroom.aspx#{itn.OBHref}&KeepThis=true&TB_iframe=true&width=700&height=580',
            'th.suites a[href]': '/cms/search2/lightboxes/stateroom.aspx#{itn.SUHref}&KeepThis=true&TB_iframe=true&width=700&height=580',
			'p.btn-details a[href]': '/Itinerary.aspx#{itn.DetailsHREF}'
        });

     	var sailings = $('table.detail', itineraries).mapDirective({
      'tbody tr': 's <- itn.Sailings',
	  'tbody tr[class]+': function(s){
		var oddEven =  (s.pos % 2 == 0) ? 'even' : 'odd';
     	var firstLast = (s.pos == 0) ? 'first-child': (s.pos == s.items.length -1) ? 'last-child':'';
      	return oddEven + ' ' + firstLast; 
    	},
		'tbody tr[id]': 's.SailingId',
      'td.dates': 's.CalendarDaysText',
      'td.interior': 's.INPriceText',
      'td.ocean': 's.OVPriceText',
      'td.balcony': 's.BAPriceText',
      'td.suites': 's.STPriceText',
      'td.details a[href]':'/Itinerary.aspx#{s.DetailsHREF}'
  	});

		var ports = $('span.ports', itineraries)
  .mapDirective({
      'a': 'p <- itn.Ports',
      'a.portName': 'p.PortText',
	  'a.portName[href]': '/cms/search2/lightboxes/PortsOfCall.aspx#{p.PortHref}&KeepThis=true&TB_iframe=true&width=630&height=570'
	
  });

        $('div.favsailings', itineraries).html(sailings);
        $('span.ports', itineraries).html(ports);
		if(!favcompiled){
			$p.compile(itineraries, 'f5');
			favcompiled=true;
		}
        
        var htmlFavs = $p.render('f5', context);
		//console.debug("favs html %o", htmlFavs);
		
        $('#targetarea-favorites').html(htmlFavs);
		//console.debug("area favs %o", $('#targetarea-favorites').html());
       	
	   	if(favcompiled)
        $('#targetarea-favorites').fadeIn("fast");
		
		if($.browser.msie && parseInt(jQuery.browser.version) < 8) {
   		   $("#targetarea-favorites .cruise-item").stackOrderIEFix();
    	}
		
        //console.debug("#favcount before %d itineraries length: %d", $("#favcount").text(),context.d.Itineraries.length);
	    $("#favcount").html($("#area-favorites tbody tr").length);
		//console.debug("#favcount after %d", $("#favcount").text());
		
		//console.debug("favsCount: %d tr count %d ", 
		//$("#favcount").text(), $("#area-favorites tbody tr").length);
	
		if($("#favcount").text() == 1) {
			$(".area-title .btn-expand").parent().removeClass("closed");
		}
	
	
		
		
	$("#area-favorites tbody .star").live("click",function(event) {
	    var $header = $("#area-favorites .area-title h2 span");
		var $rows = $("#area-favorites tbody tr")
		//console.debug("a star was clicked %o", $(this));
		
		var tr = $(this).parent().parent();
		var trId = tr.attr("id");
		var $item = $(this).parents(".cruise-item");
		var $areaFavs = $(this).parents("#area-favorites");
		
		tr.fadeOut("normal", function() {
			//console.debug("remove row %o", tr);
			//console.debug("cruise item %o", $item);
			
			var $tBody = tr.parent();
			
			
			tr.remove();
			
			

			//console.debug("length %d  item %o", ($("tr",$item).length == 1), $item);
			//console.debug("number of rows %d  tbody %o  item %o     areaFavs length %d", $("tr", $tBody).length, $tBody, $item, $("tbody tr",$areaFavs).length);
			
			if($("tbody tr",$areaFavs).length == 0) {
				//console.log("removing all of them");
				$item.fadeOut("normal", function() { 
				$(this).remove(); 
				resizeCol();
				//console.debug("rows showing %d",$("#area-favorites tbody tr").length);
				$header.text("0");
				$('#area-favorites').addClass("closed");
				RemoveFavorite(trId, true);
				});	
			}
			else {
				//console.debug("single removal length %b  item %o", ($("tbody tr",$item).length == 0), $item);
				if( $("tbody tr",$item).length == 0) {
					$item.fadeOut("normal", function() { 
						$item.remove(); 
						//console.debug("rows showing %d",$("#area-favorites tbody tr").length);
					});	
				}
				
				
				$header.text($("#area-favorites tbody tr").length);
				RemoveFavorite(trId, false);
				resizeCol();
				
			}
		});
		
		
		return false;
	});
	$("#area-favorites tbody .remove").click(function(){ $(this).prev().trigger("click"); });
		
		
       tb_init('a.thickbox, area.thickbox, input.thickbox'); 
      }  
    }

	function updateUrl(selectObj) {
		var $selObj = $(selectObj);
		var selected = $("option:selected", $selObj).val();
		var id = $selObj.attr("id");
		var newUrl = "";
		var updateUrl = false;
		
		if(id == 'sel-sortby'){
			var valSel = setSortExpression(selected, "string");
			cclSailing.SortExpression = valSel;
			cclSailing.PageSize = $("#sel-sortcount option:selected").val();
			//console.debug("expression %o  paging %d", cclSailing.SortExpression, cclSailing.PageNumber);
			//cclSailing.PageNumber = 1;
			//newUrl = $.query.SET("sort", valSel).toString();
			updateUrl = true;
		}
		else if(id == "sel-sortcount") {
			//cclSailing.PageNumber = 1;
			var sortBy = $("#sel-sortby option:selected").val();
			var valSel = setSortExpression(sortBy, "string");
			cclSailing.SortExpression = valSel;
			
			cclSailing.PageSize = selected;
			//console.debug("expression %o  paging %d", cclSailing.SortExpression, cclSailing.PageNumber);
			//console.debug("pageNumber %d  pageSize %d", cclSailing.PageNumber, cclSailing.PageSize);
			//newUrl = $.query.SET("pageSize", selected).toString();
			updateUrl = true;
		}
		else if(id == "ctl00_ContentPlaceHolder1_seldates") {
			//console.debug("sel state %s", $selObj.val());
			resetList();
			//selectedOpt = new String($selObj.val()).split(" ");
			
			var opt = $("option[value='"+$selObj.val()+"']", $selObj).attr("selected", true);
			console.debug("selected val %s", selected);
			if(opt.hasClass("optGroup")){
				// multiple sequential months
				/*
				var months = monthGrouping[selectedOpt[0]];
				var startMonth = new Array(3);
				var endMonth = new Array(3);
				//console.debug("months %o  grouping %o", months, monthGrouping);
				if(selectedOpt[1].indexOf("-") > -1){
					//spans years	
					var startYear = selectedOpt[1].split("-");
					startMonth[0] = (parseInt(months[0]) > 9) ? months[0] : "0"+months[0];
					startMonth[1] = 1;
					startMonth[2] = startYear[0];
					
					endMonth[0] = (parseInt(months[2]) > 9) ? months[2] : "0"+months[2];
					endMonth[1] = new Date(parseInt(startYear)+1, endMonth[0], 0).getDate();
					endMonth[2] = parseInt(startYear)+1;
					
					//console.debug("span years: startMonth %o  endMonth %o", startMonth, endMonth);

					cclSailing.FromDate = startMonth.join("/");
					cclSailing.ToDate = endMonth.join("/");
					
				}
				else {
					startMonth[0] = (parseInt(months[0]) > 9) ? months[0] : "0"+months[0];
					startMonth[1] = 1;
					startMonth[2] = selectedOpt[1];
					endMonth[0] = (parseInt(months[2]) > 9) ? months[2] : "0"+months[2];
					endMonth[1] = new Date(selectedOpt[1], months[2], 0).getDate();
					endMonth[2] = selectedOpt[1];
					
					//console.debug("startMonth %o  endMonth %o", startMonth, endMonth);
					
					cclSailing.FromDate = startMonth.join("/");
					cclSailing.ToDate = endMonth.join("/");
					
				}
				*/
				
			}
			else if(selected != ""){
				/*
				var year = selectedOpt[1];
				var month = jQuery.inArray(selectedOpt[0],monthNames)+1;
				var lastDate = new Date(year, month, 0).getDate();
				*/
				
				var startMonth = selected.substring(0,2);
				var startYear = selected.substring(2);
			
				var endMonth = selected.substring(0,2);
				var endYear = selected.substring(2);


				cclSailing.FromDate = ""+ startMonth +""+startYear;
				cclSailing.ToDate = ""+endMonth +""+endYear;
				
				//console.debug("startDate %s  endDate %s", cclSailing.FromDate, cclSailing.ToDate);
				//lastDay = new Date(2008, month + 1, 0);

			}
			else {
				cclSailing.FromDate = cclSailing.ToDate = null; 
			}
			updateUrl = false;
			$(this).trackLink({buttonName: "Modify Search Box Feature"  });
			//console.debug("startDate %s  endDate %s", cclSailing.startDate, cclSailing.endDate);
		}
		else if(id == "sel-state") {
			//console.debug("sel state %s", $selObj.val());
			cclSailing.StateCode = $selObj.val();
			updateUrl = false;
			
			$(this).trackLink({buttonName: "Modify Search Box Feature"  });

			// async update
		}

		if(updateUrl) {
			//location.search = newUrl;
			var newSearch = buildNewUrl(newUrl)
			//console.debug("newSearch url: ", newSearch);
			//alert(newSearch);
			location.search = newSearch;
		}
		else {
			//console.debug("searchAsync %o", $selObj);
			cclSailing.SearchAsync(done, failed, cclSailing.PageSize, cclSailing.PageNumber, cclSailing.SortExpression);
			SearchFilter(failed, "");
		}
	
		return updateUrl;
	}

	function buildNewUrl(newUrl) {
		// get all values for cclSearchObj
		// will need to test
		// array fields
		var dest = "";
		var serviceCall = false;
		
		//console.debug("new url :%s:  %d", newUrl, newUrl.length);
		if(newUrl.length > 0) {
		  serviceCall = true;
		}
		  
		//console.debug("DestinationCodes %o", cclSailing.DestinationCodes);
		if(cclSailing.DestinationCodes != null && cclSailing.DestinationCodes.length > 0){
			try {
				if(typeof cclSailing.DestinationCodes == "string") {
					dest = 	cclSailing.DestinationCodes;
				}
				else {
					dest = 	cclSailing.DestinationCodes.join(",");
				}
				
			}catch(e) { }
			
		}
		if(dest.length > 0){
			$.query.SET("dest" , dest);	
		}
		else {
			$.query.REMOVE("dest");	
		}
		
		var dur = "";
		if(cclSailing.DurationCodes != null && cclSailing.DurationCodes.length > 0) {
			//console.debug("DurationCodes %o", cclSailing.DurationCodes);
			try {
				if(typeof cclSailing.DurationCodes == "string") {
					dur = cclSailing.DurationCodes;
				}
				else {
					dur = cclSailing.DurationCodes.join(",");
				}
				
			} catch(e){ }
		}
		
		if(dur.length > 0){
			$.query.SET("dur" , dur);
		}
		else {
			$.query.REMOVE("dur");
		}
		
		var embkCode = "";
		if(cclSailing.PortCodes != null && cclSailing.PortCodes.length > 0){
			//console.debug("PortCodes %o", cclSailing.PortCodes);
			//alert("Ports: "+cclSailing.PortCodes.length);
			try {
				if(typeof cclSailing.PortCodes == "string"){
					embkCode = cclSailing.PortCodes;
				}
				else {
					embkCode = cclSailing.PortCodes.join(",");	
				}
				
				
			} catch(e){ /*alert("error"+e);*/ }
						
		}
		//console.debug("PortCodes %o  ebmkCode %s", cclSailing.PortCodes, embkCode);
		//alert("port length: " + embkCode.length);
		if(embkCode.length > 0){
			$.query.SET("embkCode", embkCode );	
		}
		else {
			$.query.REMOVE("embkCode");	
		}
		// single values
		
		$.query.REMOVE("startDate");
		$.query.REMOVE("endDate");
		$.query.REMOVE("cruiseMonth");
		$.query.REMOVE("minDays");
		$.query.REMOVE("maxDays");
		$.query.REMOVE("portName");
		$.query.REMOVE("src");
		$.query.REMOVE("destinationText");
		
		var dat = ""
		//console.debug("monthNum %s  monthYear %s", monthNum, monthYear);
		/*
		if(cclSailing.FromDate != null) {
			var startDate = cclSailing.FromDate;
			var monthNum = startDate.substring(0,2);
			var monthYear = startDate.substring(2);
			var datDate =  ""+monthNum : "0"+monthNum;
			
			var endDate = cclSailing.ToDate;
			var monthNumEnd = endDate.substring(0,2);
			var monthYearEnd = endDate.substring(2);
			var datDateEnd = (monthNum > 9) ? ""+monthNum : "0"+monthNum;
			
			console.debug("startDate %o  endDate %o month %d  endmonth %d  %b", startDate, endDate, monthNum, monthNumEnd, (monthNum != monthNumEnd));
			
				dat = "" + datDate +""+ monthYear;
			
		}
		*/
		var dates = $("#ctl00_ContentPlaceHolder1_seldates option:selected").val();
		if(dates != ""){
			dat = dates;
		}
		else {
			dat = "";	
		}
		
		try {
			if(dat.length > 0){
				$.query.SET("dat", dat);
			}
			else {
				$.query.REMOVE("dat");
			}
		}
		catch(e){
			$.query.REMOVE("dat");
		}
		//console.debug("monthNum %s  monthYear %s dat %s  cclSailing.fronDate %s", monthNum, monthYear, dat, startDate);
		
		var senior = (cclSailing.IsOver55) ? "Y" : "N";
		$.query.SET("Senior", senior);

		var pastGuest = (cclSailing.IsPastGuest) ? "Y" : "N" ;
		$.query.SET("PastGuest", pastGuest);

		if(cclSailing.StateCode != null){
			$.query.SET("StateCode", cclSailing.StateCode);
		}
		
		/*
		var resetPageNum = false;
		if(cclSailing.DestinationCodes.length != cclSailing.DestinationCodes_preLen){
			resetPageNum = true;	
		}
		if(cclSailing.DurationCodes.length != cclSailing.DurationCodes_preLen){
			resetPageNum = true;	
		}
		if(cclSailing.PortCodes.length != cclSailing.PortCodes_preLen){
			resetPageNum = true;	
		}
		console.debug("destCodes len %d  destCode_preLen %d\ndurCodes len %d  durCodes_preLen %d\nportCodes len %d portCode_preLen %d", cclSailing.DestinationCodes.length, cclSailing.DestinationCodes_preLen, cclSailing.DurationCodes.length, cclSailing.DurationCodes_preLen, cclSailing.PortCodes.length, cclSailing.PortCodes_preLen
		 );
		
		cclSailing.PageNumber = (resetPageNum) ? 1 : cclSailing.PageNumber;
		*/
		
		
		if(cclSailing.PageNumber > 0) {
			var num = 1;
			if(!serviceCall)
				num = cclSailing.PageNumber;
			else
				cclSailing.PageNumber = num;
					
			$.query.SET("pageNumber", cclSailing.PageNumber);
		}
		
		if(cclSailing.PageSize > 0) {
			var val = $("#sel-sortcount").val();
			//console.debug("pageSize %s", val);
			$.query.SET("pageSize", val);
		}
		if(cclSailing.SortExpression.length > 0) {
			var val = $("#sel-sortby").val();
			setSortExpression(val, "string");
			$.query.SET("sort", cclSailing.SortExpression);
		}
	//	console.debug("expression %o  paging %d   size: %o", cclSailing.SortExpression, cclSailing.PageNumber, cclSailing.PageSize);
		    	 
		//console.debug("updated query str\n %s", $.query.toString());
		return $.query.toString();
	}

		
    var cclSailing = new CCLSailingSearchRequest();
	var searchOptions	= new Object();
	var compiled = false;
	var favcompiled = false;
	var favsItem = null;
	searchOptions.lastPage = -1;
	searchOptions.itemsPerPage = 5;
	searchOptions.sortExpression = "FromPrice DESC";
	searchOptions.currPage = 1;
	searchOptions.lastPage = -1;
	searchOptions.firstLoad = true;
	searchOptions.failCnt = 0;


	$(document).ready(function() {

        var page = $.query.GET("pageNumber");
	    var querySort = $.query.GET("sort");
	    var size =  $.query.GET("pageSize");
	    $("#sel-sortby option[value='"+querySort+"']").attr("selected", true);
	     $("#sel-sortcount option[value='"+size+"']").attr("selected", true);
		 
		if(jQuery.browser.msie){
			$("body").attr("id", "ie");	
		}
	   
	    favsItem = $("#area-favorites .cruise-item").clone(true);
	    builtInteractions();
	    $("#area-favorites").buildFavs();
	    
	    if (page == "")
	        cclSailing.SearchAsync(done, failed, 5, 1, "FromPrice");
	    else
	        cclSailing.SearchAsync(done, failed, size, page, querySort);

	    //console.log("building cruises");
	    $("#content-body").buildCruises(cclSailing);
	    //console.log("built cruises");

	    resizeCol();
	});

(function($) {
$.fn.equalizeCols = function() {
   
  var height = 0;
  this.css("height","auto").each(function(){
    
    height = Math.max( height, jQuery(this).outerHeight(true) );
   // alert("height: "+height+" this outerHeight: "+jQuery(this).outerHeight(true) +"  outerheight no margin:"+
   // jQuery(this).outerHeight() );
  });
  // code to fix ie8 broken dynamic content height issue
  heightAdj = (jQuery.browser.msie && (parseInt(jQuery.browser.version) == 8)) ? height/2: height ;

  //console.debug("this %o", this);
  this.css("height", height); 
  
  if(jQuery.browser.msie && (parseInt(jQuery.browser.version) == 8)) 
  {
  	this.each(function(a, domEl)
  	{
  	  if(a==1)
  	  {
  	   $(domEl).css("height", heightAdj);
  	  }
  	});
  	
  }
  
  
   return this;
};
$.fn.shareForm = function() {
	var yourEmail = "Please enter your email address";
	var toEmail = "(add an email address)";
	return this.each(function(){ 
		var shareForm = $("#share_favorites");
		var aTag = $(".repeaterControl a", shareForm);
		var repeatSection = $(".toRepeater", shareForm).html();
		var $repeatLi = $("<li class='toRepeater'></li>").html(repeatSection);
		
			$('#from-email, input[id^="to-email"]').focus(function() {
				currText = ($(this).val() == yourEmail || $(this).val() == toEmail) ? "":currText; 
				//console.debug("focus value %s", currText);
				$(this).val(currText);
			});
			$('#from-email, input[id^="to-email"]').blur(function() {
				//console.debug("idVal = %s", $(this).attr("id"));
				currText = ($(this).val() == "") ? (($(this).attr("id") == "from-email") ?yourEmail : toEmail ):$(this).val(); 
				$(this).val(currText);
			});
		
		var count = 0
		//repeatSection.wrap("<li></li>").addClass(".toRepeater");
		aTag.live('click',function(event) {
			//console.debug("%o %o", $repeatLi, event);
			var $newLi = $repeatLi.clone(true);
			var textField = $(":text", $newLi);
			textField.blur(function() {
				//console.debug("idVal = %s", $(this).attr("id"));
				currText = ($(this).val() == "") ? (($(this).attr("id") == "from-email") ?yourEmail : toEmail ):$(this).val(); 
				$(this).val(currText);
			}).focus(function() {
				currText = ($(this).val() == yourEmail || $(this).val() == toEmail) ? "":currText; 
				//console.debug("focus value %s", currText);
				$(this).val(currText);
			});
			var oldId = textField.attr("id");
			textField.attr("id", oldId+"_"+count);
			$(this).parent().before($newLi);
			count++;
		});
		var limit = $('.word_count').parent().attr("class");
		$('.word_count').each(function(){  
    	// get current number of characters 
			
			var length = limit- $(this).val().length;  
			 // get current number of words  
			//var length = $(this).val().split(/\b[\s,\.-:;]*/).length;  
			 // update characters  
			$(this).parent().find('.counter').html( length + ' characters remaning');  
			// bind on key up event  
			 $(this).keyup(function(){  
				// get new length of characters  
				var new_length = limit - $(this).val().length;  
				 // get new length of words  
				 //var new_length = $(this).val().split(/\b[\s,\.-:;]*/).length;  
				 // update  
				var $remaining =  $(this).parent().find('.counter');
				var ouputStr = new String();
				 
				if(new_length < 0) {
				 	$remaining.addClass("error");
					outputStr = Math.abs(new_length) + ' characters over';
				}
				else {
					$remaining.removeClass("error");
					outputStr = new_length + ' characters remaining';
				}
				
				$remaining.html(outputStr);
			 });  
		 }); 
		
	});
};

$.fn.buildPager = function(options){
	// new recheck paging
	var defaults = {
		first: -1,
		last: -1,
		itemsPerPage: 5,
		curr: -1,
		block: 'paging',
		prev: $(".paging .prev"),
		next: $(".paging .next"),
		count: -1,
		showingRange: "-1 - -5"
	};
	var opts = $.extend(defaults, options);
	
	return this.each(function() {
							  
	if(opts.count == 0)	return;
	
	searchOptions.currPage = opts.curr;
	searchOptions.lastPage = opts.last;
	searchOptions.count = opts.count;
	searchOptions.showingRange = opts.showingRange;
	//console.debug("opts %o", opts);
	var startNum, endNum;
	
	startNum = (opts.curr >0) ? Math.ceil(opts.curr/opts.range) : 1;
	if(startNum != 1) {
		startNum = (startNum-1)*opts.range+1
	}
	endNum = startNum + opts.range-1
	if(endNum > opts.last) {
		endNum = opts.last;
		if(endNum - opts.range > 1)
		startNum = endNum - opts.range;
	}
	if(startNum == endNum)


	//console.debug("showing range %o searchOptions %o  itemsPerPage %d", searchOptions.showingRange, searchOptions, searchOptions.itemsPerPage);
	if(!searchOptions.showingRange) {
		var range = new Array();
		if(opts.curr == 1){
			range[0] = opts.curr;
			range[1] = parseInt(opts.curr) + parseInt(searchOptions.itemsPerPage) -1;
			//console.debug("curr page 1 %o  curr %d  itemsPerPage %d  calc %d midCalc %d", range, opts.curr, searchOptions.itemsPerPage, (opts.curr + searchOptions.itemsPerPage - 1), (opts.curr + searchOptions.itemsPerPage));
		}
		else {
			range[1] = parseInt(opts.curr)*parseInt(searchOptions.itemsPerPage);
			range[0] = parseInt(range[1])-parseInt(searchOptions.itemsPerPage)+1;
			//console.debug("curr %d  itemsPerPage %d  first calc %d last calc %d", opts.curr, searchOptions.itemsPerPage, range[0], range[1]);
		}
		 //console.debug("curr page %d range: %d   %o",opts.curr, searchOptions.range, range);
		 searchOptions.showingRange = range.join(" - ");
		 
	}
	$('#currentCount').html(searchOptions.showingRange);
	$('#totalCount').html(searchOptions.count);
	$(".pagingInfo").fadeIn("fast");
	//console.debug("opts last %s  endNum %s", opts.last, endNum);
	//console.debug("curr page %s  last page %s   start num %s   end number  %s",opts.curr, opts.last, startNum, endNum); 
	var paging = "";
	var aTag = "<a href='#' class='page'>|</a>";
	var spanTag = "<span>|</span>";
		
		
		
	for(var i=startNum; i <= endNum ; i++) {
		if(opts.curr == i){
			paging += spanTag.replace(/[|]/,i);	
		}
		else {
			paging += aTag.replace(/[|]/,i);
		}
	}
	$(".pages").html($(paging));
	$(".paging").fadeOut("normal");
	// build paging
	$(".paging .pages a").live("click", function() {
		
		//console.debug("paging page %d", newPage );
		//console.debug("newUrl %s", jQuery.query.SET("pageNumber", newPage) );
		//resetList();
		//var newUrl = jQuery.query.SET("pageNumber", $(this).text()).toString();
		var newPage = $(this).text();
		//console.debug("next page %d  query: %o", newPage, jQuery.query.get("pageNumber"));
		if(jQuery.query.get("pageNumber")){
			cclSailing.PageNumber = newPage;
			var newSearch = buildNewUrl("")
			location.search = newSearch;
		}
		else {
			location.search	+= "&pageNumber="+newPage;
		}
		//console.debug("newUrl %s", newUrl);
		
		//location.search = newUrl;
		/* update query string */
		//cclSailing.SearchAsync(done, failed, searchOptions.itemsPerPage, $(this).text() , searchOptions.sortExpression);	
		
		//return false;
		//	cclSailing.Search(done, failed, searchOptions.itemsPerPage, $(this).text() , searchOptions.sortExpression);											
	});
	if(parseInt(searchOptions.currPage)-1 <= 0) {
		opts.prev.css("visibility", "hidden");
	}
	else {
		opts.prev.css("visibility", "visible");
		opts.prev.live("click", function() {
			//console.debug("this prev page %d", parseInt(searchOptions.currPage)-1 );
			resetList();
			var newPage = parseInt(searchOptions.currPage)-1;
			if(jQuery.query.get("pageNumber")){
				cclSailing.PageNumber = newPage;
				var newSearch = buildNewUrl("")
				location.search = newSearch;
			}
			else {
				location.search	+= "&pageNumber="+newPage;
			}
			
			/* update query string */
			//cclSailing.SearchAsync(done, failed, parseInt(searchOptions.itemsPerPage), parseInt(searchOptions.currPage)-1 , searchOptions.sortExpression);
			//cclSailing.Search(done, failed, searchOptions.itemsPerPage, searchOptions.curr-1 , searchOptions.sortExpression);	
			//return false;
			//	cclSailing.Search(done, failed, searchOptions.itemsPerPage, searchOptions.curr-1 , searchOptions.sortExpression);										
		});
	}
	if(parseInt(searchOptions.currPage, 10)+1 > parseInt(searchOptions.lastPage)) {
		opts.next.css("visibility", "hidden");
	}
	else {
		opts.next.css("visibility", "visible");
		opts.next.live("click", function() {									  
			//console.debug("curr page %d  next page %d ", parseInt(searchOptions.currPage), parseInt(searchOptions.currPage, 10) +1);
			resetList();
			var newPage = parseInt(searchOptions.currPage)+1;
			if(jQuery.query.get("pageNumber")){
				cclSailing.PageNumber = newPage;
				var newSearch = buildNewUrl("")
				location.search = newSearch;
			}
			else {
				location.search	+= "&pageNumber="+newPage;
			}

			/* update query string */
			//cclSailing.SearchAsync(done, failed, parseInt(searchOptions.itemsPerPage), parseInt(searchOptions.currPage)+1 , searchOptions.sortExpression);	
			//cclSailing.Search(done, failed, searchOptions.itemsPerPage, searchOptions.curr+1 , searchOptions.sortExpression);
			
													
		});		
	}
	
	
	// call ccl obj
	// searchOptions.currPage = opts.curr;
	// cclSailing.Search(done, failed, searchOptions.itemsPerPage, page_index + 1, searchOptions.sortExpression);
	resizeCol();
	});
};
$.fn.stackOrderIEFix = function () {
   var zIndexNumber = 500;
   return this.each(function () {
      $(this).css('zIndex', zIndexNumber);
      zIndexNumber -= (zIndexNumber <= 0) ? 0 : 10;
   });
};
$.fn.buildCruises = function(cclSailing) {
	
};
$.fn.anchorAnimate = function(settings) {

		settings = jQuery.extend({
			speed : 1100
		}, settings);	
		
		return this.each(function(){
			var caller = this
			$(caller).click(function (event) {	
				event.preventDefault()
				var locationHref = window.location.href
				var elementClick = ($(caller).attr("href") != "#") ? $(caller).attr("href") : "q"+$(caller).attr("id");
				
				var destination = $(elementClick).offset().top -200;
				//console.debug("%d %d", destination, destination-200);
				$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, settings.speed, function() {
					//window.location.hash = elementClick
				});
				return false;
			})
		});
    };
$.fn.buildFavs = function() {
		GetFavorites(favoritesDone, failed);
};
})(jQuery);
jQuery.fn.fadeIn = function(speed, callback) { 
    return this.animate({opacity: 'show'}, speed, function() { 
        if (jQuery.browser.msie && parseInt(jQuery.browser.version) < 8) { 
            this.style.removeAttribute('filter');  
            }
        if (jQuery.isFunction(callback)) 
            callback();  
    }); 
}; 
 
jQuery.fn.fadeOut = function(speed, callback) { 
    return this.animate({opacity: 'hide'}, speed, function() { 
        if (jQuery.browser.msie && parseInt(jQuery.browser.version) < 8) { 
            this.style.removeAttribute('filter');  
            }
        if (jQuery.isFunction(callback)) 
            callback();  
    }); 
}; 
jQuery.fn.trackLink = function(options){
	// trackLink
	var defaults = {
		prop: "28",
		linkTrackVars: "28",
		linkTrackEvents: "None",
		trackEventName: 'Search Page Click',
		sprop: "28",
		evar:"27",
		evarTripId: "Cruise",
		favs: false,
		buttonName: 'default click'
	};
	
	if(!s_account) var s_account="carnivalprod"
	
	
	
	if ( (window.location.toString().indexOf("uatcarnival.com")>-1 ) || (window.location.toString().indexOf("syscarnival.com") >-1) || (window.location.toString().indexOf("dev.carnival.com") >-1) ){
	
		s_account="carnivaldev"
	
	}

	
	
	var opts = $.extend(defaults, options);
	var s=s_gi(s_account); 
	
	if(opts.favs){
		// add to favs
		s.linkTrackVars='prop'+opts.prop + ',eVar'+opts.evar;
		s.linkTrackEvents=opts.linkTrackEvents;
		s.prop28 = opts.buttonName;
		s.eVar27 = opts.evarTripId;
	}
	else {
		
		s.linkTrackVars='prop'+opts.prop; 
		s.linkTrackEvents=opts.linkTrackEvents;
		s.prop28 = opts.buttonName;
    	
    	}
    	s.tl(this,'o',opts.trackEventName);
	
	
};