
var lastUsedWaitListSource = "";

/*
* availability and colour/size combination display functions
*/

/* shows the relevant colour options for the selected size */
function showColourSelection(clicked){
	//make a jquery object of the selected radio button
	var c=$(clicked);	
	var selector_prefix='.estar_modal ';
	// if the clicked button is in a popup there will be a <div class="estar_modal"> somewhere in its parents
	// otherwise we are looking at a main product detail form
	if(c.closest(selector_prefix).length==0){
		selector_prefix='';
	}
	//clear the 'on' class from all of the colour options lis, and add it to the selected one
	$(selector_prefix+'.add_to_cart .colour li').removeClass('on')
	c.parent().addClass('on');	
	//find the selected size (if any)
	var s=$(selector_prefix+'input[name="szID"]:radio:checked').val();
	var clickMe=[];
	if(c.length>0&&c.val()!=undefined){		
		//display the colour name in the selection message
		$(selector_prefix+'.selections .message').html(c.attr('title'));
		//hide all of the size radio button lists		
		$(selector_prefix+'.size ol').css('display','none');
		// find and display the size list that corresponds with the selected colour (or the default one if not found)
		var sizes=$(selector_prefix+'.size ol.'+c.attr('id'));
		if(sizes.length==0){
			sizes=$(selector_prefix+'.size ol.default');
		}
		sizes.css('display','block');
		// do the same for alternate images
		var lisToShow=$(selector_prefix+' li.colourway_'+c.val());
		
		if(lisToShow.length>0){
			$(selector_prefix+'.zoom_message').html('Roll over image to zoom')
			if(lisToShow.css('display')=='none'){
				lisToShow.siblings().css('display','none')
				lisToShow.css('display','');
				$(lisToShow[0]).addClass('first').find('a').trigger('click');
			}
		}else{
			$(selector_prefix+'.zoom_message').html('There are currently no images in this colour ('+c.attr('title')+') available')
		}
		
		// hide all the availability key entries
		$(selector_prefix+'.size .availability_key li').css('display','none');	
		// iterate through the selected size list and display any availability key entries with the same availability class
		var sizecount=0;
		$('li',sizes).each(function(){
				sizecount++;
				$(selector_prefix+'.size .availability_key li.'+this.className.split(' ')[0]).css('display','');	
				// if a size has been selected previously presumably they want the same size in this colour
				if(s!=undefined){					
					var myInput=$('input',this);
					// if this input has the same value as the previously selected size make a reference
					if(myInput.val()==s){
						clickMe=myInput;
					}
				}
		})										
	}
	if(clickMe.length==0 && sizecount==1){
		clickMe=$('li input',sizes)
	}
	//if there is a reference to a size input that needs to be selected, select it
	if(clickMe.length>0){
		$(selector_prefix+'[name="szID"]:radio:checked');
			clickMe.attr('checked','checked').trigger('click');
	}else{
		updateSelectionMessages(selector_prefix);
		//updateSelectionPrice(selector_prefix);
	}
}

/* shows the relevant availability messages when a size is selected */
function showSizeSelection(clicked){
	// make a jquery object of the selected radio button
	var s=$(clicked);
	// if the clicked button is in a popup there will be a <div class="estar_modal"> somewhere in its parents
	// otherwise we are looking at a main product detail form
	var selector_prefix='.estar_modal ';
	if(s.closest(selector_prefix).length==0){
		selector_prefix='';
	}
	//find the selected colour(if any) in the current form
	var c=$(selector_prefix+'input[name="clID"]:radio:checked');
	if(c.length==0){
		c=$(selector_prefix+'input[name="clID"]')
	}
	//clear the 'on' class from all of the colour options lis, and add it to the selected one
	var p=s.closest('li').addClass('on');
	p.siblings().removeClass('on');
	//if the selected colour/size combination is unavailable hide the form sumnit buttons
	if(p.hasClass('unavailable')){
	 $(selector_prefix+'.product_details .submit input').css('display','none');
	}else{
		$(selector_prefix+'.product_details .submit input').css('display','');
	}
	// display the colour name in the selections message
	updateSelectionMessages(selector_prefix);
	// updateSelectionPrice(selector_prefix);
	// display the relevant availability message
	var selector='selection_avail';
	// if we are in a popup the ids are preceded by popup_
	if(selector_prefix.length>0){
		selector='popup_selection_avail';
	}
	// hide all the availability messages (ids all begin with selection_avail or popup_selection_avail)
	$('*[id^="'+selector+'"]').css('display','none');
	// display the availability corresponding to the selected colour/size combination (or the default if no colour chosen)
	selector='#'+selector; 
	if(c.val()!=undefined){
		selector+='_'+c.val()+'_'+clicked.value;
	}
	$(selector).css('display','inline');									
}

function updateSelectionMessages(selector_prefix){	
	//find the selected size and colour(if any) in the current form
	var c=$(selector_prefix+'.add_to_cart .colour input[name="clID"]:radio:checked');
	if(c.length==0){
		c=$(selector_prefix+'.add_to_cart .colour input[type="hidden"][name="clID"]')
	}
	var s=$(selector_prefix+'.add_to_cart .size input[name="szID"]:radio:checked');
	if(s.length==0){
		s=$(selector_prefix+'.add_to_cart .size input[type="hidden"][name="szID"]')
	}
	// build an array of selected options
	var arr=[];
	if(c.length>0 && c[0].title){
		arr.push(c[0].title);
	}
	if(s.length>0 && s[0].title){
		arr.push(s[0].title);
	}
	//populate the selection message area
	$(selector_prefix+'.selections .message').html(arr.join(', '));	
	// clear the availability message
	$(selector_prefix+'.availability_key .status_message').html('');	
	if (c.length>0 && s.length>0) {
		var id_prefix='';
		if(selector_prefix.length>0){
			id_prefix='popup_';
		}
		$(selector_prefix+".product_pricing .message").removeClass("on");
		$("#"+id_prefix+"selection_price_" + c.val() + "_" + s.val()).addClass("on");
		$(selector_prefix+".product_availability .message").removeClass("on");
		$("#"+id_prefix+"selection_avail_" + c.val() + "_" + s.val()).addClass("on");
		//add an eta message if appropriate
		var cs_li=$(selector_prefix+"#colour_size_" + c.val() + "_" + s.val()).closest('li');		
		if ( cs_li.length > 0){ if (cs_li.is('.delayed')) $(selector_prefix+'.availability_key .delayed .status_message').html($('.message',cs_li).html()); else if(cs_li.is('.waitlist')) $(selector_prefix+'.availability_key .waitlist .status_message').html($('.message',cs_li).html()); else if(cs_li.is('.unavailable')) $(selector_prefix+'.availability_key .unavailable .status_message').html($('.message',cs_li).html()); }
	}
}

/* Selects a colour/size combination by simulating clicks on the form objects */
/* This function is called from the pricing matrix links*/
function selectColourSize(colourVal, sizeVal){	
	// product form can be in a popup box or on the page, so we need to make sure we are referencing the correct instance, we do this by adding '.estar_modal ' to the start of the selectors when we have detected a popup form.
	var prefix=''
	var isPopup=($('.estar_modal input[name="clID"], .estar_modal input[name="szID"]').length>0);
	if(isPopup){
		prefix='.estar_modal '
	}
	//triggering the click event on a radio button does not work on all browsers, so we need to manually clear the checked attribute on each one in the list and add it to the relevent one, then trigger the click event to fire any display related functions
	// click the colour button
	$(prefix+'input[name="clID"]').attr('checked','')
	$(prefix+'input[name="clID"][value="'+colourVal+'"]').attr('checked','checked').trigger('click');
	// click the size button, the colour button click event will have hidden the ones that do not match the selected colour, so we can use the :visible selector
	$(prefix+'input[name="szID"]').attr('checked','')
	$(prefix+'input[name="szID"][value="'+sizeVal+'"]:visible').attr('checked','checked').trigger('click');
	//close the pricing matrix popup
	$('.pricing_matrix:visible').closest('.ui-dialog-content').dialog('close');
	return false;
}



//    function fPost(){
//        var c = document.getElementById("clID").value;
//        var s = document.getElementById("szID").value;
//        var q = document.getElementById("qty").value;

////        <xsl:choose>
////          <xsl:when test="count(//PRODUCT_DETAIL/colour) = 1">c = "<xsl:value-of select="//PRODUCT_DETAIL/colour/@clID"/>";</xsl:when>
////          <xsl:otherwise>c = document.getElementById("clID").value;</xsl:otherwise>
////          </xsl:choose>
////          <xsl:choose>
////          <xsl:when test="count(//PRODUCT_DETAIL/size) = 1">s = "<xsl:value-of select="//PRODUCT_DETAIL/size/@szID"/>";</xsl:when>
////          <xsl:otherwise>s = document.getElementById("szID").value;</xsl:otherwise>
////          </xsl:choose>
//          
//          if(c == "" || s == ""){
//            if(c == "" && s == ""){ alert("Please select your preference and size you require before adding this item."); }
//            else if(c == ""){ alert("Please select your preference you require before adding this item."); }
//            else if(s == ""){ alert("Please select your size you require before adding this item."); }
//            else{ alert("Please select your preference/size you require before adding this item."); }
//            return false;
//          }
//          if(q == "" || isNaN(q)){
//            alert("Please select your quantity you require before adding this item.");
//            return false;
//          }							
//          return true;
//    }
        
        
    function fAdvPost() {
          var a = $("#AddToCartForm input[id = 'action']").val(); 
          if(a == "orderlist") {
            return true;
          } else {
            // Get vars from hidden fields
            var size = "", c = "";
            size = $("#AddToCartForm input[name = 'szID']").val(); 
            if (!size) { size = $("#szID option:selected").val(); }
            colour = $("#AddToCartForm input[name = 'clID']").val();
            if (!colour) { colour = $("#clID option:selected").val(); }
            var prod = $("#AddToCartForm input[name = 'pdID']").val();
            var cat = $("#AddToCartForm input[name = 'T']").val();
            
            var ppo = $("#AddToCartForm input[name = 'ppo']").val();
            if (!ppo) { ppo = '';}
            var ppo_g = $("#AddToCartForm input[name = 'ppo_g']").val();
            if (!ppo_g) { ppo_g = '';}
            var parent = $("#AddToCartForm input[name = 'parent']").val();
            if (isNaN(cat)) {cat = 0;}
            var quantity = $("#AddToCartForm input[name = 'qty']").val();
            
            if (quantity && size && colour && quantity > 0 && size >= 0 && colour >= 0) {

                  try { 
                    if(typeof(hideAddToCart)=="function"){ 
                      hideAddToCart(); 
                    } 
                    else {
                      var add = $("#addtocartimage");
                      var adding = $("#addingtocartimage");
                      if (add.is(':visible')) {                                 
                        add.hide();
                        adding.show();              
                      } 
                    }
                  } catch (e) { } // hide add to cart button
                  setTimeout('showBasicAddToCart()', 20000);
                  
                  $.ajax({
                  type: "GET",
                  url: "/default.aspx",
                  cache: false,
                  data: { z: "c", action: "addspecify", pdID: prod, catID: cat, szID: size, clID: colour, qty: quantity, ppo: ppo, ppo_g: ppo_g, parent: parent, addpopup: "1", qs: "6" },
                  success: ShowAddToCartPopup
                  });
            } else {
                  alert("Please select the colour and size that you require before adding this item.");
            }
            return false; // Prevent form submit
          }
        }
        
        function ShowAddToCartPopup(data) {
            var cartPopup = $("#cart_item_added");
		        if(typeof(showCartResult)=="function"){
		  	        showCartResult();							
		        } else{
		            cartPopup.html(data);
			          cartPopup.css('display','');  	// showCartResult() is not defined, so show message
		        }
            return false;			
            
            			
        }

        function fSelectColourSize(clID, szID) {
          try {
            // Update the sizes
            $('input#szID').val(szID);
		        $("select[id^='szID_' ]").each(function() {
              $(this).val(szID);
              if ($(this).val() != szID) { $(this).val(""); }
            });
            // Update the colours
            $('#clID').val(clID);
            $("select[id='clID']").trigger('change');
            $('#colour_' + clID).click();
          } catch (e) { } 
          if(typeof(closePopup)=='function'){
            closePopup();
          }
		    } 
 		    function AddToList() {
          if(fPost()) {
            document.getElementById('action').value = 'orderlist';
            return true; 	
			    }
			    return false;        
        }
        
        function showhide(listid) {
          var a = document.getElementById(listid);
          if (a.style.display == "none") { a.style.display = ""; }
          else { a.style.display = "none"; }
        }
        
        function showBasicAddToCart() {
          try { 
            if(typeof(showAddToCart)=="function"){ 
              showAddToCart(); 
            } else { 
              var add = $("#addtocartimage");
              var adding = $("#addingtocartimage");
              if (add.is(':hidden')) {                 
                adding.hide();                    
                add.show();              
              } 
            } 
          } catch (e) { } // display add to cart button
        }
        
        
        function fn_showItemAvailability() {
          var c = -1;
          var s = -1;
          s = $("#AddToCartForm input[name = 'szID']").val(); 
          if (!s) { s = $("#szID option:selected").val(); }
          c = $("#AddToCartForm input[name = 'clID']").val();
          if (!c) { c = $("#clID option:selected").val(); }
          
          if (!c || isNaN(c)){c=-1}
          if (!s||isNaN(s)){s=-1} 
          
          $("div[id^='selection_avail']").hide();
          $("div[id^='selection_avail']").removeClass('on');
          
          if (c > -1 && s > -1) {
            $('#selection_avail_' + c + '_' + s).show();
            $('#selection_avail_' + c + '_' + s).addClass('on');
          } else {
            $('#selection_avail').show();
            $('#selection_avail').addClass('on');
          }
        }

/*
        function popupCartSummary(){
            var dataUri = $('#BagViewLink').data('ajax_src');
            if(dataUri.length>0){
                renderCartSummary()
                $.ajax({ type: "POST", url: dataUri, data: {}, success: renderCartSummary });
            }
        } 

        function renderCartSummary(content) {
            if (!content || content.length == 0)
                content = '<div id="BagSummary"><div class="element_wrapper"><div class="element_body"><img src="/assets/preloader.gif" /></div></div></div>';
            $('#CartSummaryPopUp').html(content).css('display', 'block');
            $('input[placeholder]', $('#CartSummaryPopUp')).trigger('blur');
            closePopup();
        }

        function closeCartSummary() {
            $('#CartSummaryPopUp').empty().css('display', 'none');
        }*/
		
        function WinOpenWH(page, width, height){window.open(page, "", "width=" + width + ",height=" + height + ",toolbar=no,header=no,location=no,resizable=1,scrollbars=1");}
        function WinOpenW(page, width){window.open(page, "", "width=" + width + ",height=600,toolbar=no,header=no,location=no,resizable=1,scrollbars=1");}

        function printReceipt(page, width, height) {
            var a;
            a = width / 2;
            var b;
            b = height / 2;
            var LeftPosition = (screen.width / 2) - a;
            var TopPosition = (screen.height / 2) - b;
            window.open(page, "", "width=" + width + ",height=" + height + ",toolbar=yes,header=no,location=no,resizable=0," + "left=" + LeftPosition + ",top=" + TopPosition + ",scrollbars=1");
        }

/*
        ///<summary>
        /// Opens the email cart summary form in a popup layer
        ///</summary>
        function popupCartMail() {
            // the link with the ID BagMailLink should have a data-ajax_src attribute with a url that requests the popup contents
            var dataUri = $('#BagMailLink').data('ajax_src');
            popup(7, dataUri);
        }
*/
        function validateEmail(str) {
            var at = "@"
            var dot = "."
            var lat = str.indexOf(at)
            var lstr = str.length
            var ldot = str.indexOf(dot)
            if (str.indexOf(at) == -1) {
                return false
            }

            if (str.indexOf(at) == -1 || str.indexOf(at) == 0 || str.indexOf(at) == lstr) {
                return false
            }

            if (str.indexOf(dot) == -1 || str.indexOf(dot) == 0 || str.indexOf(dot) == lstr) {
                return false
            }

            if (str.indexOf(at, (lat + 1)) != -1) {
                return false
            }

            if (str.substring(lat - 1, lat) == dot || str.substring(lat + 1, lat + 2) == dot) {
                return false
            }

            if (str.indexOf(dot, (lat + 2)) == -1) {
                return false
            }

            if (str.indexOf(" ") != -1) {
                return false
            }

            return true
        }

// Personalised Product Javascript    
// Update date fields from dd/mm/yyyy to yyyy/mm/dd for POST
function DateFieldsUpdateValue() {
    if ($(this).val().length == 0) return;

    var dateParts = $(this).val().split("/");
    
    if (dateParts.length == 3 && dateParts[2].length == 4) {
        $(this).val(dateParts[2] + '/' + dateParts[1] + '/' + dateParts[0]);
    }
}

// Updates input fields that have example text to ensure the example text is not submitted.
function ExampleTextUpdateValue() {
    if ($(this).attr('example') == $(this).val()) {
        $(this).val('');
    }
}

// Returns the personalisation input fields serialized
function PersonalisationFormSerialized(suffix) {
    suffix = (typeof suffix == 'undefined') ? '' : suffix;
    return $('#pers_form' + suffix + ' :input:not(.ignored)').serialize();
}

function toggleGuide(itemid){
	var nearest_info_container = $(itemid).closest(".personalised_details").find(".file_info_container");
	if(nearest_info_container.is(":visible")){
			$(nearest_info_container).slideUp();
			$(itemid).val("Show Guide");
		}else{
			$(nearest_info_container).slideDown();
			$(itemid).val("Hide Guide");
		}
}


function enableClosest(itemid){
	var showhidebtn = $(itemid).closest(".personalised_details").find(".file_info_btn");
	showhidebtn.val("Show Guide");
	showhidebtn.css("display","block");	
	var nearest_info_container = $(itemid).closest(".personalised_details").find(".file_info_container");
	$(nearest_info_container).slideUp();
}

function ConfirmTocOnClick(e) {
    var checkBox = $(e).closest('table').parent().find('.confirm_toc input');
    if (checkBox.is(':checked')) {            
        $('span.error_msg_inline',checkBox.parent()).hide();				
				if(checkBox.is('.ui-dialog input')){
					fPost_popup();
				}else{
					fPost();
				}
        return true;
    } else {
        $('span.error_msg_inline',checkBox.parent()).css('display','block');
				checkBox.personalisedProduct('sync_popup_message'); 
        return false;
    } 
}

function PersonalisationToggleOptIn(e) {
	var f = $(e).closest('form');
	var checkedVal=''
	$('input[name="personalise"]', f).each(function(){
		if(this.checked){
			checkedVal=this.value;
		}
	})
	if(checkedVal=='yes'){
    $('.hide_options', f).show();
		$('.no_personalise', f).hide();
	}else{	
    $('.hide_options', f).hide();
		$('.no_personalise', f).show();        
	}
}

// Personalised Product (personalisedProduct) Functions
// See http://docs.jquery.com/Plugins/Authoring for details on the javascript notation.
(function($){
 
    var methods = {
        /* Validate parent form.
            * Can use this to make a button or link validate the form it's contained in.            
            * Example: $('a').click(function(){$(this).personalisedProduct('validateParentForm')});             
            */
        validateParentForm : function() {            
            var form = $(this).closest('form');
            if(form.length>0){
            if(form.valid()) {
                $(form).personalisedProduct('enableControls');
                return true;
            }

            $(form).personalisedProduct('disableControls');   
            }
            return false;
        },

        enableControls : function() {
            $('.disabled_control', this).hide();
            $('.enabled_control', this).show();
        },

        disableControls : function() {
            $('.disabled_control', this).show();
            $('.enabled_control', this).hide();
        },

        /* Serialize the form's personalisation fields.             
            * Example: $('form').personalisedProduct('serialize');
            */
        serialize : function() {
            return $(':input[name^=pers_]:not(.ignored)', this).serialize();
        },

        /* Displays terms and conditions dialog box.             
            */
        toc : function() {
          var r=$($(this).data('toc'));
          r.find('.check_details_title + div').html($(this).personalisedProduct('preview'));
          r.modalDialogOpen();
          return r;
        },

        userOptedOut : function() {
            return $('input[name=personalise]', this).length > 0 && $('input[name=personalise]:checked', this).val() == 'no';
        },

        /* Resets the form
            */
        reset : function() {                
            $(':input[name^=pers_], :input[name$=_confirm]', this)
            .not(':button, :submit, :reset, :radio')
            .val('')
            .removeAttr('checked')
            .removeAttr('selected');

            $(':radio[name^=pers_]', this).removeAttr('checked')                

            $('.GrammarPreview:not(.disabled), div.GrammarOption:not(.disabled)', this)
            .addClass('disabled')
            .find('span.UserValue').text('');

            $($(this).data('toc')).find('.confirm_toc input').removeAttr('checked');

            $(this).personalisedProduct('disableControls');
        },            
            
        /* Generates a preview for the given from into the given preview location.
            *
            * Remarks: Takes the current form values that are filled in, but currently will not
            *          correctly reflect grammar options or remove example text.             
            * Params:  previewLocation (required) (expression)
            * Example: $(form).personalisedProduct('preview').appendTo('body');
            */
        preview : function() {                
            var preview = $('<div>');                

            $(':input[type=radio][name^=pers_]:checked:not(.ignored), :input[type!=radio][name^=pers_]:filled:not(.ignored)', this).each(function(index) {
                var newCell = $('<td align="left" valign="top"><strong><span class="preview_field_name"></span></strong><br/><span class="preview_field_value"></span></td>')
                var name = $(this).parent().prev().children('label').text();

                if (/:\*$/.test(name)) {
                    name = name.slice(0, -2); // Remove :* from end of name
                } else if (/:$/.test(name)) {
                    name = name.slice(0, -1); // Remove : from end of name
                }

                newCell.find('.preview_field_name').text(name);

                var value = $(this).val();
                if ($(this).is(':radio')) {
                    value = $(this).next('label:not(.error_msg_inline)').text();
                }

                newCell.find('.preview_field_value').text(value);
								//override if an img.
										
								if ($(this).attr("type") && $(this).attr("type") == "hidden") {											
										if ($(this).val() && $(this).val().length > 0) {																							
												newCell.find('.preview_field_value').html('<img class="perscarticon" src="/Personalisation_Images/icon/'+$(this).val()+'.jpg"></img>');
										}											
								}

                if (index % 4 == 0) { // First row, get the new table to build
                    var newTable = $('<table width="100%" border="0" cellspacing="0" cellpadding="0" class="check_details"><tr></tr></table><br/>');
                    preview.append(newTable);

                    currentRow= newTable.find('tr');
                }

                currentRow.append(newCell);

            });

            return preview;
        },
        /*
        * copies the validation messages from the hidden form to the popped up (fake) form
        *
        */
        sync_popup_message:function(){
          var original=$(this).closest('.popped_up_form');
          //console.log('sync_popup_message '+(original.length>0))
          if((original).length>0){
            var popform=original.data('popup_layer');
            if(popform.length>0){
              $('dd .error_msg_inline',popform).remove();
              var source_dds=$('dd',original);
              $('dd',popform).each(function(idx){
                var orig_dd=source_dds[idx];
                var err=$('.error_msg_inline',orig_dd);
                if(err.length>0){
                  if(err.is(':first-child')){
                    $(this).prepend(err);
                  }else{
                    $(this).append(err);
                  }
                }								
              })
              $('.confirm_toc .error_msg_inline',popform).css('display',$('.confirm_toc .error_msg_inline',original).css('display'))
            }
          }
        },

        /* Setup personsalisation form validation.
            * Example: $('form').personalisedProduct('setup', {rules: <validation rules>});
            * Options: rules (object) (required) List of validation rules.
            *          onsubmit (function) (optional) Function to use to submit the form.
            */
        setup : function(options) {
			if(options.rules){
				for(var n in options.rules){
					if(typeof(options.rules[n].date)=='object' && options.rules[n].date===false){
						delete options.rules[n].date;
					}
				}
			}
            $(this).validate({

                rules: options.rules,
                submitHandler: function(form) {
                    var toc = $($(form).data('toc'));

                    if (toc.is('.popped_up_form') == false) {
                        // Remove example text from form fields
                        $('input.ExampleText', form).each(ExampleTextUpdateValue);

                        /* Show terms and conditions and prevent form submit unless:
                         * 1) Terms already checked
                         * 2) User has opted out of personalisation
                         * 3) Product is a giftcard
                         */
                        if(toc.find('.confirm_toc input').is(':checked') == false && $(form).personalisedProduct('userOptedOut') == false && options.type!='GIFTCARD')  {
                            $(form).personalisedProduct('toc');
                            return; // Stop rest of execution
                        }
                         
                    } else {
                        toc.modalDialogClose();

                    }         
                        
                    // Call optional onsubmit function
                    if (typeof options.onsubmit == 'function') {
                        options.onsubmit.apply(form);
                    }
                },
                errorClass: 'error_msg_inline',
                // Override validation's default error/valid highlighting behaviour
                highlight: function(element, errorClass, validClass) {},
                unhighlight: function(element, errorClass, validClass) {},
                errorPlacement: function(error, element) {
                    if (options.type != 'undefined' && options.type.toLowerCase() == 'complex') {
                        element.before(error);  // Place errors before input element
                    } else {
                        element.after(error);   // Place errors after input element
                    }
                },
                // Hack to let the form ignore validation if user has opted out (essentially we want to disable validation)
                invalidHandler: function(form, validator) {
                    if ($(form.currentTarget).personalisedProduct('userOptedOut') == true) {                                            
                        if (typeof options.onsubmit == 'function') {
                            options.onsubmit.apply(form);
                        }
                        // TODO otherwise call submit on form
                    }
                }
            });
        }
    };

    $.fn.personalisedProduct = function(method) {
    
    // Method calling logic
    if (methods[method]) {
        return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
    } else if (typeof method === 'object' || ! method) {
        return methods.init.apply(this, arguments);
    } else {
        $.error('Method ' +  method + ' does not exist on jQuery.personalisedProduct');
    }
    };

})(jQuery);


// Trigger for input fields with grammar options changing
function GrammarOptionTrigger(e) {
    var options = $('#grammar_' + $(this).attr('id'));
    var preview = $('#preview_' + $(this).attr('id'));

    if (/s$/.test($(this).val())) { // Ends in 's'        
        options.removeClass("disabled");                        // Show grammar option display
        preview.addClass("disabled");
        options.find('span.UserValue').text($(this).val());     // Update grammar option label with current value
    } else {
        options.addClass("disabled");
        if ($(this).val().length > 0) {
            preview.removeClass('disabled');                        // Show preview                    
            preview.find('span.UserValue').text($(this).val());     // Update preview label with current value
        } else {
            preview.addClass("disabled");
        }
    }
}

function GrammarOptionsUpdateValue() {
    var options = $('#grammar_' + $(this).attr('id'));
    var preview = $('#preview_' + $(this).attr('id'));

    if (/s$/.test($(this).val())) { // Ends in 's'
        // Using grammar option
        var id = options.find(':input:checked').attr('id');
        if (id.charAt(id.length - 1) == '1') { // Option 1  - append "'" to input value
            $(this).val($(this).val() + "'");
        } else if (id.charAt(id.length - 1) == '2') { // Option 2 - append "'s" to input value
            $(this).val($(this).val() + "'s");
        }
    } else { // No option required - append "'s" to input value
        $(this).val($(this).val() + "'s");
    }
}


/* Validation Setup
 * Adds additional validation types and setups some different defaults.
 */    
function InitValidation() {    
    // Default required message
    $.validator.messages.required = "This field is required";
    $.validator.messages.equalTo = "The personalisation details you have entered do not match. Please try again.";

    // customDateFormat - Validates that the field matches a 'dd/mm/yyyy' format
    $.validator.addMethod(
        "customDateFormat",
        function(value, element) {
            return this.optional(element) || value.match(/^(0?[1-9]|[12][0-9]|3[01])[- /.](0?[1-9]|1[012])[- /.](19|20)\d{2}$/);
        },
        "Please enter a valid date in the format dd/mm/yyyy."
    );

    // Allowed characters (restriction on type of characters users can enter)
    $.validator.addMethod(
        "validChar",
        function(value, element) {
            if (value == $(element).attr('example')) return true; // Example text can have invalid chars
            return this.optional(element) || value.match(/^([a-zA-Z0-9.! \-'])+$/);
        },
        "Sorry, we cannot accept accents and symbols in personalised fields."
    );
        
    // exampleText
    $.validator.addMethod(
        "exampleText",
        function(value, element, exampleText) {                 
            return value != exampleText;
        },
        "This field is required"
    );
              
    // grammarOption - Validates that a grammar option is selected if required.    
    $.validator.addMethod(
    "grammarOption",
    function(value, element) {
        if (this.optional(element)) {
            return true;
        }
                    
        if (/s$/.test(value)) { // Ends in s - grammar option required
            $(element).val();
            var option = $(element).attr('id') + '_GRAMMAR_OPTION';
            return $('input[name = "' + option +'"]:checked').length == 1;
        }
                    
        return true;
    },
    "Please select a grammar option."
    );

}

(function($){
$.fn.exampleText = function(text) {
    this.focus(function() {
        if ($(this).val() == text) {
            $(this).val('');
        }
    });
                    
    this.blur(function() {
        if ($(this).val() == '') {
            $(this).val(text);
        }
    });
};
})(jQuery);

// we need to be able to pop up a section of a form and use validation functionality written into the original
// jQuery ui.dialog moves content into an added div (which is outside the original form), 
// so we need to clone a copy of the hidden form section for displaying in the popup dialog box
// and bind change/click events to the original form elements
// we also need to copy eny error messages from the hidden form to the fake one after validation has taken place
(function ($) {
  $.fn.modalDialogOpen = function() {
    // make a reference to the hidden form section, and flag it as being popped up
    var frm=this.addClass('popped_up_form');
    // create an ID for the popped up version of the form section
    var ffID='fakeform_'+this.attr('id');
    // remove any previously versions
    $('#'+ffID).remove();
    //create a container to hold the cloned form section 
    var ff=$('<div style="display:none" id="'+ffID+'" class="fakeform" />');
    // make a reference to the actual form HTML element that holds our foprm section
    if(frm.is('form')){
      ff.data('source_form',frm);
    }else{
      ff.data('source_form',frm.closest('form'));
    }
    $('body').append(ff);
    //clone the form section and add it to the container
    ff.append(this.contents().clone());
	//hide the header image and replace it with some text
	$('img.personalisation_popup_header',ff).css('display','none').after('<div class="heading">Personalise This Item</div>');
    // change the ids of anything in the form so that we have unique ones oin the page, making a reference to the original
    $('*[id]',ff).each(function(){var me=$(this); me.data('bindID',this.id);var newID=ffID+'_'+me.attr('id');me.attr('id',newID);});	
    // bind click and change events for the new input fields to generate the same event on the original field 					
    var originalInputs=$('input',frm);
    $('input',ff).each(function(idx){
      var inp=$(this);
      var myIdx=idx;
      // make a reference to the original field and associate it with the new field
      inp.data('matchField',$(originalInputs[myIdx]))
      // bind events on the popped up field to trigger the same evenyt on their hidden counterpart
      switch(inp.attr('type')){
        //triggering click events on rasdio and checkboxes does not always have the desired effect.
        // so we need to manually change the checked attributes
        case 'radio':
          inp.bind('click',function(evt){
            var matchField=$(this).data('matchField');
            $('input[type=radio][name=['+matchField.attr('name')+']',originalInputs).attr('checked','');
            matchField.attr('checked','checked');			
            });
        break;
        case 'checkbox':        
          inp.bind('click',function(evt){
			  var matchField=$(this).data('matchField');
            matchField.trigger('click');
            if($(this).is(':checked')){
              matchField.attr('checked','checked');
            }else{
              matchField.attr('checked','');
            }
            });
        break;
        // the image button invokes the validation, so we need to show the validation messages
        case 'image':				
          inp[0].onclick=function(){$(this).data('matchField').trigger('click').personalisedProduct('sync_popup_message');return false;}
        break; 
				case 'hidden': //hidden fields for the personalisation images.
					if (inp.val() && inp.val().length > 0) {
						var img=$("#"+inp.attr("id")+"img");
						var src = img.attr("src");
						//if the image exists, update it to display the current image.
						if (src && src.length > 0) {
							img.attr("src", "/Personalisation_Images/icon/"+inp.val()+".jpg");
    					img.css("display", "block");
						}		
					}		
					inp.bind('change',function(){$(this).data('matchField').val(inp.val())})
        break;
        default:
          inp.bind('change',function(){$(this).data('matchField').val(inp.val()).closest('form').valid();if(window.console && console.log){console.log('$(this).data("matchField"):'+$(this).data('matchField').closest('form').attr('id')+', inp.val()inp.val()'+inp.val())};})
        break;
      }
    })
    // we have changed the ids of the inputs so we will need to change the for attributes of any labels that refer to them
    // we will also need to bind the click action as binding between labels and their inputs happens only when the page is rendered
    $('label[for]',ff).each(function(){
      var lb=$(this);
      var newID=ffID+'_'+lb.attr('for'); 
      lb.attr('for',newID); 
      lb.bind('click',function(){
        $('#'+newID).trigger('focus');
        })
    ;})
    // any links that have javascript need to have their actions bound as well 
    var scriptlinks=$('a[onclick]',frm);
    $('a[onclick]',ff).each(function(idx){
      var oldLink=scriptlinks[idx];
      this.onclick=function(){$(oldLink).trigger('click');return false;}
    })
    //create the popup layer 
    var p=popup(7,'#'+ffID)
    //make a reference to the popup in the hidden form
    this.data('popup_layer',p);
    //any datepickers need to be initialised every time the form is rendered
    $('input.date', p).removeClass('hasDatepicker').each(function() {
          $(this).datepicker({
              changeMonth: true,
              changeYear: true,
              dateFormat: 'dd/mm/yy',
              yearRange: 'c-40:c+10'
          });
      });
      //$('body').append($('#ui-datepicker-div'))
    return this;
  };

  $.fn.modalDialogClose = function() {				
    
    if(this.hasClass('popped_up_form')){
      // the function has been called from the original hidden div
      this.removeClass('popped_up_form');
      //close the associated popup
      this.data('popup_layer').dialog('close');
      $('#ui-datepicker-div').hide();
    }else { // Not container, so find it and close it
      return this.closest('.popped_up_form').modalDialogClose();
    }
    return this;
  };

})(jQuery);
    

///<summary>
/// adds a message to products that have been added to the cart.
///</summary>
///<param name="pdid">
/// string, product id of item added to cart
///</param>
///<param name="quantity">
/// Number of this product added to cart
///</param>
///<param name="size">
/// Size of product added to cart
///</param>
///<param name="colour">
/// Size of product added to cart
///</param>

var writeable_products={};

function show_product_added(pdid, quantity, size, colour){
	// there should be a flag in the writeable_products object for this pdid, otherwise the display has already been updated
	if(!writeable_products[pdid]){return}
	writeable_products[pdid]=false;
	// find any products in the page that correspond to the one that has been added
	// the element holding the product will have a data-pdpid that matches the pdid value passed in
	$('div[data-pdid='+pdid+']').each(function(idx){
		//alert('idx '+idx)
		//make a jQuery object of the current product
		var me=$(this).addClass('in_cart');
		if(me.is('.item')){
			// alert('item '+pdid)
			// this is an item in a catalogue, search result or a cross-sell
			var amount_span=$('span.in_cart_number',me);
			if(amount_span.length>0){
				    // there is already some of this product in the cart so just add the new amount to it
				    var amt=parseInt(amount_span.text());
				    if(isNaN(amt)||!amt>0){amt=0;}
				    amt+=quantity;
				    amount_span.html(amt);
			}else{            
				    // we need to hide the 'buy now' button and replace it with a message				
				    var msg=$('<p class="in_cart_message">You already have <span class="in_cart_number">'+quantity+'</span> of these in your bag</p>');
				    $('.buy_now a',me).css('display','none').after(msg);
				    // also need to change the 'more details' link to read 'add more'
				    $('.view_details a',me).attr('title','add more').html('add more');                   
			}
		 
		}else if (me.is('.product_details')){
			 // this is a product details page so it will need the full message
			 // if we already have this colour/size combination than we just need to increase the amount
			 // otherwise we add a whole new message
			 // set a flag to show whether we have found a matching colour/size combination
			 var updated=false;
			 // find the message holder <li>, if we don't have one add it in
			 var holder=$('.in_cart_message',me);
			 if(holder.length==0){
				 holder=$('<li class="in_cart_message"/>');
				 $('li.quantity',this).before(holder);
			 }
			 // iterate though the messages
			 $('p',holder).each(function(){
				 if(!updated){
					 // do we have a size match?
					 var size_match=false;
					 if(!size || size.length==0){
						 size_match=$('.in_cart_size',this).length==0;
					 }else{						 
						 size_match=($('.in_cart_size',this).text()==size||(size=='none'));
                        // size_match=(size=='none');
					 }
					 //do we have a colour match?
					 var colour_match=false;
					 if(!colour || colour.length==0){
						 colour_match=$('.in_cart_colour',this).length==0;
					 }else{						
						 colour_match=($('.in_cart_colour',this).text()==colour || (colour=='none'));
                         //colour_match=(colour=='none');
					 }
					 if(size_match && colour_match){
						 //colour and size match so add the quantity
						 	var amount_span=$('.in_cart_number',this);
							var amt=parseInt(amount_span.text());
							if(isNaN(amt)||!amt>0){amt=0;}
							amt+=quantity;
							amount_span.html(amt);
							// set the flag so we kow not to continue
							updated=true;
					 }
				 }
			 })
			 // add the message if necessary
			 if(!updated){
				 var coloursize="";
				 if(size&&size.length>0&&size!='none'){
					 coloursize+='<span class="in_cart_size">'+size+'</span>';
				 }
				 if(colour&&colour.length>0 &&colour!='none'){
					 if(coloursize.length>0){
						 coloursize+=', ';
						 coloursize+='<span class="in_cart_colour">'+colour+'</span>'
					 }
				 }
				 if(coloursize.length>0){
					 coloursize=' in '+coloursize;
				 }
				 var msg=$('<p>You already have <span class="in_cart_number">'+quantity+'</span> of these'+coloursize+' in your bag</p>');
				 holder.append(msg);
			 }
		}
	});
}

/// This function sets current Qty and Value after an item was inserted into the shopping bag
function updateCartQty(qty, val) {
    var cartCommentDiv = document.getElementById("qtyCartArea");
    var cartCommentDiv2 = document.getElementById("valueCartArea");

    try {
    if(!isFinite(qty)) {
        qty = '0';
    }
    } catch (e) { qty = '0'; }

    try {
    if(!isFinite(val)) {
        val = '0.00';
    }
    } catch (e) { val = '0.00'; }

    if (cartCommentDiv != null) {
        cartCommentDiv.innerHTML =  qty;
    }

    if (cartCommentDiv2 != null) {
        cartCommentDiv2.innerHTML = val;
    }

    return false;
}
//dummy function perevents errors occuring where onclick attribute has not been removed from template
function selectColour_popup(){
}
