//Standard popup window
function popUp(URL) {
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=750,height=550,left = 265,top = 237');");
}

function popUpVideo(URL) {
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=580,height=560,left = 20,top = 20');");
}

function callPageTracking(url){				
		SiTrackPage(url);					
}
function callWineGuideTracking(url,tab){				
		var pageURL = url + tab;
		SiNewPageContext();
		SiTrackPage(pageURL);					
}
function removeSpecialChars(text)
{
	text = text.replace(/ /,"");
	text = text.replace("/","_");
	text = text.replace("-","_");
	text = text.replace("'","\'");
	return text;
}
function callCIDTracking()
{
	var cidValue=CIDExtractValue("cid",document.URL,"&");
	var cidValueUpper=CIDExtractValue("CID",document.URL,"&");
	
	if(cidValue == null && cidValueUpper != null) {
		cidValue = cidValueUpper;
	}
	
	if (cidValue == null) cidValue=CIDExtractValue("cid",document.cookie,";");
	if (cidValue != null) SiTrackData("cid="+cidValue);	
}

function CIDExtractValue(Name,DataSource,DataEndChar)
{
  var Prefix = Name+"=";
  var Value  = null;
  var Begin  = DataSource.indexOf(Prefix);
  if ((Begin != -1) && (Name.length > 0))
  {
    var End = DataSource.indexOf(DataEndChar,Begin);
    if (End == -1) End = DataSource.length;
    Value = DataSource.substring(Begin+Prefix.length,End);
  }
  return Value;
}

function callLinkTracking(var1,var2)
{
	var1 = removeSpecialChars(var1);
	var2 = removeSpecialChars(var2);
	SiTrackLink(var1+"_"+var2);
}
	function getTabName(tabCountFromURL)
	{
		var tabName = "";
		if (tabCountFromURL == 0)
		{
			tabName = "MIXEDWINE";
		}
		if (tabCountFromURL == 1)
		{
			tabName = "REDWINE";
		}
		if (tabCountFromURL == 2)
		{
			tabName = "WHITEWINE";
		}
		if (tabCountFromURL == 3)
		{
			tabName = "ROSEWINE";
		}
		if (tabCountFromURL == 4)
		{
			tabName = "SPARKLINGWINE";
		}   
		if (tabCountFromURL == 5)
		{
			tabName = "OTHERWINE";
		}       		   		      		      		      		
		return tabName;
   	}

function getTabCountFromURL(url)
{
	var tabCountFromURL = "";	
	var index = url.indexOf("#tab");
	if ( index != -1)
	{
		tabCountFromURL = document.URL.substring(index+4);
	}
	return tabCountFromURL;
}   	

function getDisplayTabCount(tab,tabCountFromURL, firstTab)
{
	if(tab == null || tab == "")
	{
		if (tabCountFromURL == null || tabCountFromURL == "")
		{
			tab = firstTab;
		}
		else
		{
			tab = tabCountFromURL;
		}
	}
return tab;
}

function removeComma(var1)
{
if (var1 == null)
{
var1 = "";
}
var length = var1.length;
var1 = var1.substring(0,length-1);
return var1;
}

$(document).ready(function () {		
		
		///////////////////
		//wine planner page
		///////////////////
		
		if( $('DIV.summaryBox').length > 0 ){
			
			$('DIV.plannerTabs UL LI A').click( function(e){
				var tabAction = $(this).attr('href');
				//alert(tabAction);
				//e.preventDefault();
			} );
			
			//tooltips
			//var productID = $('DIV.sortable UL LI DIV.winepod DIV.body A').attr('id');
			$('DIV.sortable UL LI DIV.winepod DIV.body A[id]').each(function () {
			
			var $link = $(this);
			$link.qtip({ 
			   show: 'mouseover',
			   hide: 'mouseout',
			   content: { url: '/DWBase/jsp/templates/youraccount/more-details-popup.jsp',data: { productId: $link.attr('id') } },
			   position: {
				  corner: {
					 target: 'topMiddle',
					 tooltip: 'bottomMiddle'
				  },
				  adjust: {
					 x: 0,
					 y: -5
				  }			  
			   },
			   hide: {
					fixed: true // Make it fixed so it can be hovered over
			   },
			   style: {
				background: '#ffffff',
				color: '#000',
				border: {
					 width: 5,
					 radius: 5,
					 color: '#990000'
				  },
				  width: 230,
				  tip: 'bottomMiddle',
				  name: 'red' // Inherit from preset style
			   }
			});
			});

				var freeBottleproductIDs = $('.wpSpan2 .selectedwines p a').attr('id');
				$('.wpSpan2 .selectedwines p a[href]').qtip({
			   show: 'mouseover',
			   hide: 'mouseout',
			   content: { url: '/LW/jsp/templates/youraccount/free-bottles-popup.jsp',data: { productIds: freeBottleproductIDs }  },
			   position: {
				  corner: {
					 target: 'topMiddle',
					 tooltip: 'bottomMiddle'
				  },
				  adjust: {
					 x: 0,
					 y: -5
				  }			  
			   },
			   hide: {
					fixed: true // Make it fixed so it can be hovered over
			   },
			   style: {
				background: '#ffffff',
				color: '#000',
				border: {
					 width: 5,
					 radius: 5,
					 color: '#6e273d'
				  },
				  width: 454,
				  tip: 'bottomMiddle',
				  name: 'red' // Inherit from preset style
			   }
			})

			
			$('DIV.summaryBox DIV.overlay A.closer').click( function(e){
				$(this).parent('DIV.overlayHeader:eq(0)').parent('DIV.overlay:eq(0)').hide();
				e.preventDefault();
			});
			
			$('#cancelPopUp').click( function(e){
				$('#CancelClose').hide();
				e.preventDefault();
			});
		
			
			//Start of wineplanner functionality
						
			$('DIV.summaryBox DL.information DD A').click( function(e){
				var clickOffset = $(this).position();
				var clickLeft = parseInt( clickOffset.left ,10) + 130;
				var thisItem = $(this).parent('DD:eq(0)');
				thisItem.parent('DL:eq(0)').find('DIV.overlay').hide();
				thisItem.find('DIV.overlay:eq(0)').css({'left': clickLeft + 'px'}).show();
				e.preventDefault();
			} );
		
			$('div.summaryBox div.actionblock ul li a ').click( function(e){
					var clickOffset = $(this).position();
					var clickLeft = parseInt(clickOffset.left + 40 ,0) + 105;
					var clickTop = parseInt(clickOffset.top + 0) - 70;
					var thisItem = $(this).parent('li:eq(0)');
					thisItem.parent('li:eq(0)').find('DIV.overlay').hide();
					thisItem.find('DIV.overlay:eq(0)').css({'left': clickLeft + 'px', 'top' : clickTop }).show();
					e.preventDefault();
				} );
		
		
		
		$("DIV.alternativewines DIV.btls P STRONG").html($("DIV.alternativewines UL LI").size());		
		var selectedbottles=0;
				for(x=0; x < $("DIV.selectedwines UL LI").length; x++){
					var val=parseInt($("DIV.selectedwines UL LI select").eq(x).val());
						selectedbottles = selectedbottles+val;			
				}
		
		//Total No of bottles for the case
		var totalNoOfBottles=0;
		totalNoOfBottles = parseInt($("#noOfBottlesBeforeFlex").val());
		
		$("DIV.selectedwines DIV.btls P STRONG").html(selectedbottles);
		$("DIV.selectedwines DIV.spaces P STRONG").html(totalNoOfBottles-selectedbottles);
		$("#sortable1, #sortable2").sortable({
			connectWith: '.connectedSortable',
			placeholder: 'highlight',
			scroll: false,
			update: function(event, ui) {
				$("DIV.alternativewines DIV.btls P STRONG").html($("DIV.alternativewines UL LI").size());
				
				var selectedbottles=0;
				for(x=0; x < $("DIV.selectedwines UL LI").length; x++){
					var val = parseInt($("DIV.selectedwines UL LI select").eq(x).val());
					selectedbottles = selectedbottles+val;
					
				}
				$("DIV.selectedwines DIV.btls P STRONG").html(selectedbottles);
				$("DIV.selectedwines DIV.spaces P STRONG").html(totalNoOfBottles-selectedbottles);
				
				//var select =  $("DIV.alternativewines UL LI option").val("1");
				//var selectEl = $(this).get(0);
				//var thisfieldval = parseInt(selectEl.text);
				// This check if dragged from sortable1 (ui.sender = null) to sortable2
				if (ui.sender && ui.sender[0].id == "sortable1") {
                   //debugger;

                    ui.item.find("SELECT").get(0).selectedIndex = 0;
                }
				
			}
		}).disableSelection();
		
		
		$('#sortable1').bind('sortreceive', function(event, ui) {
		  	var selectedbottles = parseInt($("DIV.selectedwines DIV.btls P STRONG").html());
				
				if(selectedbottles > totalNoOfBottles){
					
					var el = event.originalTarget;

					//$(el).find("SELECT").val("1");

					$(ui.sender).sortable('cancel'); 
					alert("Sorry! - maximum "+totalNoOfBottles+" bottles. Please reduce the number selected before adding additional wines.");				
				}
		});

		$("DIV.wpSpan2 DIV.sortable UL LI P.draghandle").live("mouseover", function(event){
			$(this).css({"cursor":"move"});
		});
		
		$("DIV.selectedwines li select, DIV.alternativewines li select").bind("change", function(event){
			// Not getting the updated select value.
            //alert("click2");
            //debugger;
            //alert(this.selectedIndex);
            //var selectEl = $(this).get(0);
            //var thisfieldval = parseInt(selectEl.text);
			thisfieldval = parseInt(this.options[this.selectedIndex].value);
			
			//trim spaces
			if(event.keyCode == 32){
				thisfieldval = thisfieldval.replace(/\s/g, "");
				$(this).val(thisfieldval);
			}
			if(isNaN(thisfieldval) || thisfieldval == 0){
				
				if(event.keyCode != 8){
					$(this).val(1);
				}
			}
			if(thisfieldval == 0 && event.keyCode != 8){
				$(this).val(1);
								
				if(thisfieldval == 0){
					var selectedbottles=0;
					var selectedbottlescurrentval=parseInt($("DIV.selectedwines DIV.btls P STRONG").html());
						for(x=0; x < $("DIV.selectedwines UL LI").length; x++){
							// Get the dropdown element.
							var el = $("DIV.selectedwines UL LI select").get(x);

							var val = parseInt(el[el.selectedIndex].value);
							//var val=parseInt($("DIV.selectedwines UL LI select").eq(x).val(),10);
							selectedbottles = selectedbottles+val;					
						}
				}
				if(isNaN(selectedbottles)){
					$("DIV.selectedwines DIV.btls P STRONG").html(selectedbottlescurrentval);
					$("DIV.selectedwines DIV.spaces P STRONG").html(totalNoOfBottles-selectedbottlescurrentval);
				}
				else{
					$("DIV.selectedwines DIV.btls P STRONG").html(selectedbottles);
					$("DIV.selectedwines DIV.spaces P STRONG").html(totalNoOfBottles-selectedbottles);
				}
				
				if(selectedbottles > totalNoOfBottles){
					// new
					$(this).get(0).selectedIndex = parseInt(reductionamount) - 1; 
					alert("Sorry! - maximum "+totalNoOfBottles+" bottles");
					
					
					selectedbottles=0;
					for(x=0; x < $("DIV.selectedwines UL LI").length; x++){
						
						var val=parseInt($("DIV.selectedwines UL LI select").eq(x).val());
						
							selectedbottles = selectedbottles+val;					
					}
					$("DIV.selectedwines DIV.btls P STRONG").html(selectedbottles);
					$("DIV.selectedwines DIV.spaces P STRONG").html(totalNoOfBottles-selectedbottles);
				}
			}
			else{
			var selectedbottles = 0;
			var selectedbottlescurrentval = parseInt($("DIV.selectedwines DIV.btls P STRONG").html());
				for(x=0; x < $("DIV.selectedwines UL LI").length; x++){
					
					// Get the dropdown element.
					var el = $("DIV.selectedwines UL LI select").get(x);
					//debugger;
					var val = parseInt(el[el.selectedIndex].text);
					//var val=parseInt($("DIV.selectedwines UL LI select").eq(x).val(),10);
					selectedbottles = selectedbottles+val;
				}
				if(isNaN(selectedbottles)){
					$("DIV.selectedwines DIV.btls P STRONG").html(selectedbottlescurrentval);
					$("DIV.selectedwines DIV.spaces P STRONG").html(totalNoOfBottles-selectedbottlescurrentval); 
				}
				else{
					$("DIV.selectedwines DIV.btls P STRONG").html(selectedbottles);
					$("DIV.selectedwines DIV.spaces P STRONG").html(totalNoOfBottles-selectedbottles);
				}
				if(selectedbottles > totalNoOfBottles){	
					
					var reductionamount = parseInt(totalNoOfBottles-(selectedbottles-thisfieldval));
					
					var oOption = event.target;
                    //$(this).parent('select').get(0).selectedIndex =parseInt(reductionamount) - 1;
					$(this).get(0).selectedIndex = parseInt(reductionamount) - 1; 

					alert("Sorry! - maximum "+totalNoOfBottles+" bottles");


					//$("select").each( function(){
					//	$(this).val( $("#" + $(this).attr("id")).val("1") );
					//});
										
					selectedbottles=0;
					for(x=0; x < $("DIV.selectedwines UL LI").length; x++){
						var valEl = $("DIV.selectedwines UL LI select").get(x);

						var val = parseInt(valEl[valEl.selectedIndex].text);
							selectedbottles = selectedbottles+val;					
					}
					$("DIV.selectedwines DIV.btls P STRONG").html(selectedbottles);
					$("DIV.selectedwines DIV.spaces P STRONG").html(totalNoOfBottles-selectedbottles);
				}
			}
				
		});
		$("SPAN.reset option").click(function(){
			window.location.reload(true);
		});
	}
	

})
