if(!("JSON" in window))
    $.getScript("/js/json2.js");

var options_visible = false;
var EbayLoading = false;
var Submitting = false;
var SameDayRemaining = 0;
var SameDayTimerID;

var SameDayData = {
    Available:false,
    BeforeCutOff:false,
    message:null,
    pickupdate:null,
    postcode:null,
    state:null,
    SameDaySecondsRemaining:0
};
function SameDayInit(quoteformbox)
{
    if(quoteformbox!==undefined && quoteformbox.length>0){
        var SameDayCutOff = $('input[name^="SameDayCutOff"]', quoteformbox).val();
        var FutureDaysLimit = $('input[name^="FutureDaysLimit"]',quoteformbox).val();
    }else if ($('#service1').length == 0)
    {
        var SameDayCutOff = $("#SameDayCutOff").val();
        var FutureDaysLimit = $("#FutureDaysLimit").val();
    }
    else
    {
        var SameDayCutOff = $("#SameDayCutOff"+(1+parseInt($('input:radio[name=quotenum]:checked').val(),10))).val();
        var FutureDaysLimit = $("#FutureDaysLimit"+(1+parseInt($('input:radio[name=quotenum]:checked').val(),10))).val();
    }

        

    SameDayData.FutureDaysLimit = FutureDaysLimit;

    var  pc;
    if($("#postcodeFrom").length==0) { //multiple booking api 
        pc = $('.postcodeFrom', quoteformbox).val(); 
    }
    else{
        pc = ' ' + $("#postcodeFrom").val();
        pc = pc.split(' ');
        pc = pc.pop();
    }
    SameDayData.postcode = pc;
    SameDayData.State = null;
    if ((SameDayData.postcode>=0200 && SameDayData.postcode<=0299) ||
        (SameDayData.postcode>=2600 && SameDayData.postcode<=2618) ||	 
        (SameDayData.postcode>=2900 && SameDayData.postcode<=2620)) SameDayData.State = "ACT" 
    else
    if ((SameDayData.postcode>=1000 && SameDayData.postcode<=2599) ||
        (SameDayData.postcode>=2619 && SameDayData.postcode<=2898) ||	 
        (SameDayData.postcode>=2921 && SameDayData.postcode<=2999)) SameDayData.State = "NSW" 
    else
    if ((SameDayData.postcode>=0800 && SameDayData.postcode<=0999)) SameDayData.State = "NT"  
    else
    if ((SameDayData.postcode>=4000 && SameDayData.postcode<=4999) ||
        (SameDayData.postcode>=9000 && SameDayData.postcode<=9999)) SameDayData.State = "QLD" 
    else
    if ((SameDayData.postcode>=5000 && SameDayData.postcode<=5999)) SameDayData.State = "SA" 
    else
    if ((SameDayData.postcode>=7000 && SameDayData.postcode<=7999)) SameDayData.State = "TAS" 
    else
    if ((SameDayData.postcode>=3000 && SameDayData.postcode<=3999) ||
        (SameDayData.postcode>=8000 && SameDayData.postcode<=8999)) SameDayData.State = "VIC" 
    else
    if ((SameDayData.postcode>=6000 && SameDayData.postcode<=6999)) SameDayData.State = "WA";
 	
    SameDayData.pickupdate = getTimeAt(pc);

    if (/^([0-1][0-9]|[2][0-3]):([0-5][0-9])$/.test(SameDayCutOff))
    {
        SameDayData.Available = true;
        SameDayData.message = "Same Day Pickup available if booking is made before ";
        var time = SameDayCutOff;
        SameDayCutOff = SameDayCutOff.split(':');
        var hrs = parseInt(SameDayCutOff[0],10);
        if (hrs<12)
            SameDayData.message = SameDayData.message+time+"AM"
        else if (hrs==12)	
            SameDayData.message = SameDayData.message+time+"PM"
        else	
            SameDayData.message = SameDayData.message+(hrs-12)+":"+SameDayCutOff[1]+ "PM";
    	
        var d1 = (SameDayData.pickupdate.getHours()*60)+SameDayData.pickupdate.getMinutes();
        var d2 = (parseInt(SameDayCutOff[0],10)*60)+parseInt(SameDayCutOff[1],10);
        SameDayData.BeforeCutOff = 
        (
            (SameDayData.pickupdate.getHours() * 60) + SameDayData.pickupdate.getMinutes()
            ) < 
        (
            (parseInt(SameDayCutOff[0],10) * 60) + parseInt(SameDayCutOff[1],10)
            );
        SameDayData.SameDaySecondsRemaining = ((parseInt(SameDayCutOff[0],10) * 3600) + parseInt(SameDayCutOff[1],10) * 60) - 
        ((SameDayData.pickupdate.getHours() * 3600) + SameDayData.pickupdate.getMinutes() * 60 + SameDayData.pickupdate.getSeconds());
    }
    else
    {
        SameDayData.message = "Same Day Pickups not available for this particular booking"; 
        SameDayData.Available = false;
    }	
}

function ToggleSameDayMessage()
{
    SameDayInit();
    $("#samedaymessage").text(SameDayData.message);
//	if(!SameDayData.Available)
//		("#samedaytimer").hide();
}

function IsSameDayAvailable(date)
{
    return (SameDayData.Available && SameDayData.BeforeCutOff &&
        date.getFullYear() == SameDayData.pickupdate.getFullYear() &&
        date.getMonth() == SameDayData.pickupdate.getMonth() &&
        date.getDate() == SameDayData.pickupdate.getDate());
}
	

var blogtimer = setInterval(rotateNews, 15000)
var CurrentNewsItem=1;
var NewsItemCount;
function rotateNews()
{
    if (!NewsItemCount) NewsItemCount = $("#NewsItems LI").size();
    if (NewsItemCount<2)
        return;

    /* Note that when CurrentNewsItem==1 we are actually at the LATEST news item, so this logic is back to front */
    $("#News_"+CurrentNewsItem).hide();
    if (CurrentNewsItem == NewsItemCount)
    {
        $("#newsPrev").removeAttr('disabled'); 
        $("#newsPrev IMG").fadeTo('fast',1);
        $("#newsNext IMG").fadeTo('fast',0.5);
        $("#newsNext").attr('disabled','disabled');

        CurrentNewsItem = 1;
    }
    else
    {
        if (CurrentNewsItem==1)
        {
            $("#newsNext").removeAttr('disabled'); 
            $("#newsNext IMG").fadeTo('fast',1);
        }
        CurrentNewsItem++; 
        if (CurrentNewsItem==NewsItemCount)
        {	 
            $("#newsPrev IMG").fadeTo('fast',0.5);
            $("#newsPrev").attr('disabled','disabled');
        }	
    }
    $("#News_"+CurrentNewsItem).show();
}


$(function(){

    $("#autoenablelistings").click(function() {
	
        $.ajax({
            type : "POST",
            url : "/account/",
            data : $("#usersettingsform").serialize(),
            success : function() {
			
            }
        });
		
    });

    $("#ebayunlink").click(function() {
	
        document.location = "/unlinkebay";
	
    });
    
    $(".userservicectl").click(function() {
    
    	var Self = $(this);
    	var CourierService = Self.attr("name").split(/_/);
    	
    	$.ajax({
    		type : "POST",
    		url : "/account/settings",
    		data : { cmd : "usercontrolservice", courierid : CourierService[0], serviceid : CourierService[1], available : Self.attr("checked") }
    	});
    
    });

    $(".listingdetailslink").live("click", function(evt) {
        evt.stopPropagation();
        evt.preventDefault();
		
        var ListingLink = $(this);
        var ListingTable = ListingLink.closest("TR").next(".listingdetail");

        if(/show/i.test(ListingLink.text()))
        {		
            ListingLink.text("Hide details...");
            ListingTable.show();
        }
        else
        {
            ListingLink.text("Show details...");
            ListingTable.hide();
        }
    });


    var DeleteTransactionForm;
    $(".deletetransactionform").submit(function(evt) {
        DeleteTransactionForm = $(this);
        $( "#dialog-confirm" ).dialog('open');
		
        evt.preventDefault();
    });

    $( "#dialog-confirm" ).dialog({
        resizable: false,
        autoOpen: false,
        height:180,
        modal: true,
        buttons: {
            "Delete": function() {
                $( this ).dialog( "close" );
                DeleteTransactionForm.ajaxSubmit({
                    beforeSubmit: function() {
                        DeleteTransactionForm.hide();
                        DeleteTransactionForm.closest("td").find("img").show();
                    },
                    success: function() {
                        DeleteTransactionForm.closest("tr").remove();
                    }
                });

                return false;
            },
            Cancel: function() {
                $( this ).dialog( "close" );
            }
        }
    });

    $("#showmore").click(function(e){
        var MoreListings = $(".morelistings");
        var More = $("#showmore");
        var HTML = More.html();
		
        if (MoreListings.css("display")=="none") 
        {	
            HTML = HTML.replace("more","less");
            HTML = HTML.replace("\u00BB","\u00AB"); // � , �
            More.html(HTML);
            MoreListings.css("display","table-row")
        }	
        else
        {	
            HTML = HTML.replace("less","more");
            HTML = HTML.replace("\u00AB","\u00BB");
            More.html(HTML);
            MoreListings.hide();
        }
		
        e.preventDefault();
        e.stopPropagation();
        return false;
    });				

	
    if ($("#assurancewarn").length > 0) // are we on booking form?
    {	
        var t = $("#transportassurance").val();
        if (t)
        {	
            t = t.replace('$','');
            t = parseFloat(t,10);
        }
		
        if ( t && (t > 0) && (!$("#receipteddelivery").is(":checked")))
            $("#assurancewarn").show()
        else
            $("#assurancewarn").hide();
    }
	
    $("#booking INPUT").keypress(function(evt) {

        var s = String.fromCharCode(evt.which);

        if(/[a-z]/.test(s))
        {
            $(this).val($(this).val() + s.toUpperCase());
            evt.preventDefault();
        }

    });

    $("#contactname, #pickupcontact, #destcontact").keypress(function(evt) {

        var s = String.fromCharCode(evt.which);

        if(/[0-9]/.test(s))
        {
            evt.preventDefault();
        }

    });

    $("#weight, #height, #length, #depth, .numberonly").live("keypress", function(evt) {

        var s = String.fromCharCode(evt.which);
        if(!((/[0-9]/.test(s)) || evt.keyCode == 9 || evt.keyCode == 8 || evt.keyCode == 35 || evt.keyCode == 36 || evt.keyCode == 37 || evt.keyCode == 39))
        {
            evt.preventDefault();
        }

    });

    $("#transportassurance, #transport_assurance_value").live("keypress", function(evt) {

        var s = String.fromCharCode(evt.which);
        if(!((/[0-9|\.]/.test(s)) || evt.keyCode == 9 || evt.keyCode == 8))
        {
            evt.preventDefault();
        }

    });

    // Disabled per ticket 145
    var geocoder = null; //new google.maps.Geocoder();				
	
    $("INPUT[placeholder]").addClass("placeheld").focus(function(evt) {
	
        var me = $(this);
	
        me.removeClass("placeheld");
        if(me.val() == me.attr("placeholder"))
            me.val("");
		
    }).blur(function(evt) {
		
        var me = $(this);
		
        if(me.val() == "" || me.val() == me.attr("placeholder"))
        {
            me.val(me.attr("placeholder"));
            me.addClass("placeheld");
        }
		
    }).each(function() {

        var me = $(this);

        if(!me.val())
            me.val(me.attr("placeholder")).addClass("placeheld");
        else
            me.removeClass("placeheld");

    });
	
    $("#acceptDHL").click(function() {

        $("#acceptDHLAnchor").click();

    });
	
    $('input:radio[name=quotenum]').live("change", function() { 
        ToggleSameDayMessage(); 
        $("#pickupDate").datepicker("setDate",$("#pickupDate").datepicker("getDate")); // forces  calendar refresh 
        if($("#ShowDHLTerms"+(1+parseInt($('input:radio[name=quotenum]:checked').val(),10))).val() == 0)
            $("#acceptDHLDIV").hide();
        else
            $("#acceptDHLDIV").show();

        if($("#ShowPayPal"+(1+parseInt($('input:radio[name=quotenum]:checked').val(),10))).val() == 0)
            $("#paypalSPAN").hide();
        else
            $("#paypalSPAN").show();
			
        if($("#IsExpressService"+(1+parseInt($('input:radio[name=quotenum]:checked').val(),10))).val() == 0)
            $("#lithiumDIV").hide();
        else
            $("#lithiumDIV").show();
		
    });
	
    $("#pickupDate,.pickupDate").datepicker({
		
        dateFormat: 'yy-mm-dd',
        onSelect: function(dateText, dp) {
            var today = new Date();//(2011, 4, 16);
            if(SameDayTimerID)
                {
                    clearInterval(SameDayTimerID);
                    SameDayTimerID = null;
                }
            
            if(today.getFullYear() == dp.selectedYear && today.getMonth() == dp.selectedMonth && today.getDate() == dp.selectedDay)
            {
                SameDayInit($(this).closest('.quoteFormBox'));
                SameDayRemaining = SameDayData.SameDaySecondsRemaining;
                
                SameDayTimerID = setInterval(sameDayTimer, 1000);
            }
            else
            {
                $("#samedaytimer").hide();
                $("#samedaytimer").html("");
               
            }
							
            $(this).next("INPUT").val(dateText);		
        },
        beforeShowDay : function(date) {
                                         
            if (!SameDayData.pickupdate)
                SameDayInit($(this).closest('.quoteFormBox')); 

            var pickupdate = new Date(SameDayData.pickupdate.toDateString()) // strip off time
            if(date.getDay() == 0 || date.getDay() == 6 || (date.valueOf() < pickupdate.valueOf()))
                return [false, "", ""];
			
                        
            if(SameDayData.State)
                for (var x=0;x<PublicHolidays.length;x++)
                {
                    if (date.getFullYear() == PublicHolidays[x].Year &&
                        date.getMonth()+1  == PublicHolidays[x].Month &&
                        date.getDate()     == PublicHolidays[x].Day &&
                        (PublicHolidays[x].States.length==0 || PublicHolidays[x].States.search(SameDayData.State)>=0))
                        return [false, "phol", PublicHolidays[x].Occasion]
                }
			 
            if (IsSameDayAvailable(date))
                return [true, "", SameDayData.message];
				
            if (date.valueOf() == pickupdate.valueOf())
                return [false, "", ""];
			 
            if (date.valueOf() > new Date().valueOf() + (SameDayData.FutureDaysLimit * 24 * 60 * 60 * 1000))
                return [false, "dhllimit", "DHL does not support bookings beyond 10 days in the future"];

            return [true, "", ""];
        }
		
    });
	
    $('#options').click(toggleAdditionalOptions);
    
    $('.ebayoptionslink').live("click", function(evt) {
        toggleeBayOptions(evt, $(this));
    });
    
    $('.ebaydescriptionlink').live("click", function(evt) {
    
        toggleeBayDescription(evt, $(this));
    
    });
    
    $('#ServiceType').change(checkExpressType);
    $('#fullquote').bind('submit', function(evt) {
        Submitting = true;
        setTimeout(function() {
            $("#dangerousGoods").val("no");
        }, 250);
        return checkLastItemLine(evt);
    });
    $('#quickQuote,#payform,#ebayenableform').bind('submit', function(evt) {
        Submitting = true;
    });
    
    $(".ebay_freightsurcharge").live("click", function(){
        if(/discount/i.test($(this).val()))
        {
            $("#freightpercentage").slideDown(300);
            if(/-discount/i.test($(this).val()))
                $("#percentagetype").text("Discount");
            else
                $("#percentagetype").text("Surcharge");
        }
        else
            $("#freightpercentage").slideUp(300);
    })

    $('#quickQuote,#fullquote,#payform,#ebayselectquoteform,#apibookingform').validationEngine();
    userTypeSelector();
	
    $("#ebayconnect").click(function(evt) {
        $("#ebayconnectform").submit();
        evt.preventDefault();
        return false;
    });
	
    Cufon.replace('h1,h2', {
        fontFamily:'Trebuchet MS'
    });	
	
    Cufon.replace('h2', {
        fontFamily:'Trebuchet MS',
        hover: true
    });
  
    $("#eBayHelpLink").click(function(evt) {
   
        $("#eBayHelp").slideToggle();
	   
        $(document).one("click", function() {
	   
            $("#eBayHelp").slideUp();
	   
        });
	   
        evt.preventDefault();
        evt.stopPropagation();
	   
    });
  
  
    if(EbayLoading)
    {
        var EbayLoadingTimer = setInterval(function() {
	  
            $.ajax({
                type : "GET",
                url : "/account/ebaylistings.ajax",
                success : function(html) {
                    if(/^PROGRESS/.test(html))
                    {
                        $("#loadingprogress").html(html.replace("PROGRESS|",""));
                    }
                    else
                    {
                        clearInterval(EbayLoadingTimer);
                        location.reload(true);
                    /*
						$("#EbayListings").replaceWith(html);
						$("#EbayListings").hide().slideDown();
						*/
                    }
                },
                error : function() {
                }
            });
	  
        }, 1000);

        $.ajax({
            type : "GET",
            url : "/account/getebaylistingsinit.ajax",
            success : function(html) {
            },
            error : function() {
            }
        });
    }
  
    $("#EbayListings INPUT:text, #EbayListings SELECT").live("change", function() {

        $(this).closest("DIV").closest("TR").prev().find("INPUT:checkbox").attr("checked", "checked");
  
        if($(".enablelistingcheckbox:checked").length > 0)
        {
            $("#enablesmartsendbutton").removeAttr("disabled");
        }
        else
        {
            $("#enablesmartsendbutton").attr("disabled", "disabled");
        }  
  
    });
  
  
    /*  
  	$("#pickupaddress, #destaddress").autocomplete({
		source : function(request, response) {
			var self = this;

			if(self.xhr) {
				self.xhr.abort();
			}

			var suburb = $({"pickupaddress" : "#PickupSuburbText", "destaddress" : "#DeliverySuburbText"}[self.element.attr('id')]).text();
			
			self.xhr = $.ajax({
				type : "GET",
				url : "/address",
				data : "address=" + encodeURIComponent(request.term) + "&term=" + encodeURIComponent(suburb) + "&jsonp=1",
				dataType : "json",
				cache : true,
				autocompleteRequest : ++requestIndex,
				success : function(data, status) {
					if(this.autocompleteRequest == requestIndex)
					{
						response(data);
					}
				},
				error : function() {
					if(this.autocompleteRequest == requestIndex) {
						response( [] );
					}
				}
			});
		}
	});
*/  
  
    $("#postcodeTo").autocomplete({
        autoFocus : true,
        minLength : 4,			
        change : refreshQuote,
        select : function() {
            $(this).data("autocomplete-selected", true);
        },		
        source : function(request, response) {
            var self = this;

            if(self.xhr) {
                self.xhr.abort();
            }

            if(request.term == "" && geo)
            {
                response( geo );
            }
            else
            {
                self.xhr = $.ajax({
                    type : "GET",
                    url : "/address",
                    data : "term=" + encodeURIComponent(request.term) + "&jsonp=1",
                    dataType : "json",
                    cache : true,
                    autocompleteRequest : ++requestIndex,
                    success : function(data, status) {
                        if(this.autocompleteRequest == requestIndex)
                        {
                            $("#postcodeTo").data("autocomplete-list", data);						
                            response(data);
                        }
                    },
                    error : function() {
                        if(this.autocompleteRequest == requestIndex) {
                            $("#postcodeTo").data("autocomplete-list", []);												
                            response( [] );
                        }
                    }
                });
            }
        },
		
        open : function() {
		
            var list = $("#postcodeTo").data("autocomplete-list") || [];
			
            for(var i = 0; i < list.length; i++)
            {
                if(list[i] == $(this).val())
                {
                    $(this).autocomplete("close");
                }
            }		
		
            if(!$(this).is(":focus"))
                $(this).autocomplete("close");
		
        }

    }).focus(function() {
	
        var self = $(this);
	
        self.validationEngine('hidePrompt');
		
        if(self.val().length >= 4 && !self.data("autocomplete-selected"))
        {			
            self.autocomplete('search');
        }
        else
        {
            self.data("autocomplete-selected", false);
        }
	
    });
	
    $("#ebayselectquoteform INPUT[name=selection], #ebayselectquoteform INPUT:checkbox").live("click", function(evt) {
	
        refreshEbayTransactionQuote();
	
    });

    $("#DeliveryPostcode").autocomplete({
        source : function(request, response) {
            var self = this;

            if(self.xhr) {
                self.xhr.abort();
            }

            if(request.term == "" && geo)
            {
                response( geo );
            }
            else
            {
                self.xhr = $.ajax({
                    type : "GET",
                    url : "/address",
                    data : "term=" + encodeURIComponent(request.term) + "&jsonp=1",
                    dataType : "json",
                    cache : true,
                    autocompleteRequest : ++requestIndex,
                    success : function(data, status) {
                        if(this.autocompleteRequest == requestIndex)
                        {
                            $("#postcodeFrom").data("autocomplete-list", data);
                            response(data);
                        }
                    },
                    error : function() {
                        if(this.autocompleteRequest == requestIndex) {
                            $("#postcodeFrom").data("autocomplete-list", []);						
                            response( [] );
                        }
                    }
                });
            }
        },
        change : refreshEbayTransactionQuote
    }).focus(function() {
        $(".submit").attr("disabled", "disabled");
    }).blur(function() {
        $(".submit").removeAttr("disabled");
    });
	
    var requestIndex = 0;
    var geo;

    $("#postcodeFrom").autocomplete({
		
        autoFocus : true,
        minLength : 4,
        change : refreshQuote,
        select : function() {
            $(this).data("autocomplete-selected", true);
        },
        source : function(request, response) {
            var self = this;

            if(self.xhr) {
                self.xhr.abort();
            }

            if(request.term == "" && geo)
            {
                response( geo );
            }
            else
            {
                self.xhr = $.ajax({
                    type : "GET",
                    url : "/address",
                    data : "term=" + encodeURIComponent(request.term) + "&jsonp=1",
                    dataType : "json",
                    cache : true,
                    autocompleteRequest : ++requestIndex,
                    success : function(data, status) {
                        if(this.autocompleteRequest == requestIndex)
                        {
                            $("#postcodeFrom").data("autocomplete-list", data);
                            response(data);
                        }
                    },
                    error : function() {
                        if(this.autocompleteRequest == requestIndex) {
                            $("#postcodeFrom").data("autocomplete-list", []);						
                            response( [] );
                        }
                    }
                });
            }
        },
		
        open : function() {
		
            var list = $("#postcodeFrom").data("autocomplete-list") || [];
			
            for(var i = 0; i < list.length; i++)
            {
                if(list[i] == $(this).val())
                {
                    $(this).autocomplete("close");
                }
            }
		
            if(!$(this).is(":focus"))
                $(this).autocomplete("close");
		
        }
		
    }).focus(function() {
	
        var self = $(this);
	
        self.validationEngine('hidePrompt');
		
        if(self.val().length >= 4 && !self.data("autocomplete-selected"))
        {			
            self.autocomplete('search');
        }
        else
        {
            self.data("autocomplete-selected", false);
        }
	
    });
	
    $("#defaultAddress").change(function() {

        $.ajax({
            type : "POST",
            url : "/account/",
            data : $("#usersettingsform").serialize(),
            success : function() {
			
            }
        });	
	
    });
	
    $("#defaultFrom").autocomplete({
		
        autoFocus : true,
        minLength : 4,
        change : function() {
		
            $.ajax({
                type : "POST",
                url : "/account/",
                data : $("#usersettingsform").serialize(),
                success : function() {
				
                }
            });			
		
        },
        select : function() {
            $(this).data("autocomplete-selected", true);
        },
        source : function(request, response) {
            var self = this;

            if(self.xhr) {
                self.xhr.abort();
            }

            if(request.term == "" && geo)
            {
                response( geo );
            }
            else
            {
                self.xhr = $.ajax({
                    type : "GET",
                    url : "/address",
                    data : "term=" + encodeURIComponent(request.term) + "&jsonp=1",
                    dataType : "json",
                    cache : true,
                    autocompleteRequest : ++requestIndex,
                    success : function(data, status) {
                        if(this.autocompleteRequest == requestIndex)
                        {
                            $("#defaultFrom").data("autocomplete-list", data);
                            response(data);
                        }
                    },
                    error : function() {
                        if(this.autocompleteRequest == requestIndex) {
                            $("#defaultFrom").data("autocomplete-list", []);						
                            response( [] );
                        }
                    }
                });
            }
        },
		
        open : function() {
		
            var list = $("#defaultFrom").data("autocomplete-list") || [];
			
            for(var i = 0; i < list.length; i++)
            {
                if(list[i] == $(this).val())
                {
                    $(this).autocomplete("close");
                }
            }
		
            if(!$(this).is(":focus"))
                $(this).autocomplete("close");
		
        }
		
    }).focus(function() {
	
        var self = $(this);
	
        self.validationEngine('hidePrompt');
		
        if(self.val().length >= 4 && !self.data("autocomplete-selected"))
        {			
            self.autocomplete('search');
        }
        else
        {
            self.data("autocomplete-selected", false);
        }
	
    });	

    $(".ebaypickuplocation").autocomplete({
        source : "/address?jsonp=1"
    });

    $(".ebaypickuplocation").focus(function(evt) {
        if($(this).val() == "Postcode or Town")
            $(this).val("");
    });

    // Disabled per Ticket 145 
	
    $("#postcodeFrom").focus(function(){

        var me = $(this);

        if(me.val() == "" && geo)
        {
            me.autocomplete("search");
            return;
        }

        if(me.val() == "" && !geo)
        {
            geo = [];

            if(false && ("geolocation" in navigator))
            {
                me.addClass( "ui-autocomplete-loading");
                //setTimeout(function() { me.focus(); }, 3000);

                navigator.geolocation.getCurrentPosition(function(pos) {

                    var lnglat = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
                    geocoder.geocode({
                        'latLng' : lnglat
                    }, function(results, status) {

                        if(status == google.maps.GeocoderStatus.OK)
                        {

                            for(var i = 0; i < results.length; i++)
                            {
                                var Suburb = "";
                                var State = "";
                                var PostCode = "";

                                for(var j = 0; j < results[i].address_components.length; j++)
                                {
                                    var component = results[0].address_components[j];
                                    if(component)
                                    {
                                        if(!PostCode && /postal_code/.test(component.types.join(",")))
                                            PostCode = component.short_name;

                                        if(!Suburb && /locality/.test(component.types.join(",")))
                                            Suburb = component.short_name.toUpperCase();

                                        if(!State && /administrative_area_level_1/.test(component.types.join(",")))
                                            State = {
                                                "NEW SOUTH WALES" : "NSW"
                                            }
                                            [component.short_name.toUpperCase()];
                                    }
                                }

                                if(Suburb && State && PostCode)
                                {
                                    for(var  z = 0; z < geo.length; z++)
                                    {
                                        if(geo[z] == Suburb + " " + State + " " + PostCode)
                                            break;
                                    }

                                    if(z == geo.length)
                                        geo.push(Suburb + " " + State + " " + PostCode);
                                }
                            }

                            me.focus();
                            me.autocomplete("search");
                        }
                    });
			
                }, function() {
                    }, {
                        maximumAge : 1000000
                    });
            }
        }

    });
	
	

    // auction seller
    var timer;
    function EbayUserIDUpdate() {
        if(timer)
            clearTimeout(timer);
				
        var ebayUserID = $(this);
				
        timer = setTimeout(function() {
			
            var userid = ebayUserID.val();
				
            if(userid.length > 0)
            {			
                $.ajax({
                    type : "GET",
                    url : "/auctionid",
                    data : {
                        auctionid : userid
                    },
                    success : function(data) {
                        $("#auctionResult").html(data).css("color", "#090");
                    },
                    error : function() {
                        $("#auctionResult").html("Error retrieving auction data").css("color", "#f00");
                    }
                });
            }
            else
            {
                $("#auctionResult").html("");
            }
        }, 500);
    }	
	
    $("#ebayUserID").keypress(EbayUserIDUpdate);
    $("#ebayUserID").blur(EbayUserIDUpdate);	
	
	
    // corporate client
    function CorporateUserIDUpdate()
    {
        if(timer)
            clearTimeout(timer);
				
        var corporateUserID = $(this);
				
        timer = setTimeout(function() {
			
            var userid = corporateUserID.val();
				
            if(userid.length > 0)
            {			
                $.ajax({
                    type : "GET",
                    url : "/corpuserid",
                    data : {
                        corpuserid : userid
                    },
                    success : function(data) {
                        $("#corpResult").html(data).css("color", "#090");
										
                        if(!/\s+not\s+found\s*/i.test(data))
                            $(corporateUserID[0].form).find("#ServiceType").html("<option value=\"Road\">Best Price</option>\
											<option value=\"Express\">Express</option>\
											<option value=\"All\">Show All</option>\
											<option value=\"AlliedExpressRoad\">Allied Express Road</option>\
											<option value=\"AlliedExpressOvernight\">Allied Express Overnight</option>\
											<option value=\"TNTRoad\">TNT Road</option>\
											<option value=\"TNTOvernight\">TNT Overnight</option>\
											<option value=\"TNTOvernightAM\">TNT Overnight by 9am</option>\
											<option value=\"DHLExpress\">DHL Express</option>\
											<option value=\"AaEExpressEconomy\">AaE Express Economy</option>\
											<option value=\"AaEExpressEconomy\">AaE Express Premium</option>\
											");
                        else
                            $(corporateUserID[0].form).find("#ServiceType").html("\
										<option value=\"Road\">Best Price</option>\
										<option value=\"Express\">Express</option>\
										<option value=\"All\">Show All</option>");
								
                    },
                    error : function() {
                        $("#corpResult").html("Error retrieving corp user data").css("color", "#f00");

                        $(corporateUserID[0].form).find("#ServiceType").html("\
								<option value=\"Road\">Best Price</option>\
								<option value=\"Express\">Express</option>\
								<option value=\"All\">Show All</option>");
                    }
                });
            }
            else
            {
                $("#corpResult").html("");
					
                $(corporateUserID[0].form).find("#ServiceType").html("\
					<option value=\"Road\">Best Price</option>\
					<option value=\"Express\">Express</option>\
					<option value=\"All\">Show All</option>");
            }
        }, 500);		
    }
		
    $("#corporateUserID").bind("keypress, blur", CorporateUserIDUpdate);

    // corporate client
    function CorporateUserIDeBayLink()
    {
        if(timer)
            clearTimeout(timer);
				
        var corporateUserID = $(this);
				
        timer = setTimeout(function() {
			
            var userid = corporateUserID.val();
				
            if(userid.length > 0)
            {			
                $.ajax({
                    type : "GET",
                    url : "/corpuserid",
                    data : {
                        corpuserid : userid
                    },
                    success : function(data) {
                        $("#eBayCorpResult").html(data).css("color", "#090");
								
                        if(!/\s+not\s+found\s*/i.test(data))
                            $("#eBayCorpLinkButton").show();
                        else
                            $("#eBayCorpLinkButton").hide();
                    },
                    error : function() {
                        $("#eBayCorpResult").html("Error retrieving corp user data").css("color", "#f00");
                        $("#eBayCorpLinkButton").hide();
                    }
                });
            }
            else
            {
                $("#ebayCorpResult").html("");
            }
        }, 500);		
    }

    $("#eBayCorporateUserID").bind("keypress, blur", CorporateUserIDeBayLink);
	
    $(".usertype").click(function() {
		
        if(timer)
            clearTimeout(timer);

        if(this.id == "qqcorporate" && $(this).is(":checked"))
            $("#corporateUserID").blur();

        $(this.form).find("#ServiceType").html("\
							<option value=\"Road\">Best Price</option>\
							<option value=\"Express\">Express</option>\
							<option value=\"All\">Show All</option>");		
    });
	
	
    $("#newsPrev").live("click", function() {
        if($("#newsPrev").attr('disabled') != 'disabled')
        {
            $("#newsNext").removeAttr('disabled'); 
            $("#newsNext IMG").fadeTo('fast',1);
		 
            if (!NewsItemCount) NewsItemCount = $("#NewsItems LI").size();
		 
            $("#News_"+CurrentNewsItem).hide();
            CurrentNewsItem++;

            $("#News_"+CurrentNewsItem).show();
            if (CurrentNewsItem == NewsItemCount)
            {
                $("#newsPrev IMG").fadeTo('fast',0.5);
                $("#newsPrev").attr('disabled','disabled');
            }	 
        }
    });
	
    $("#newsNext").live("click", function() {
        if($("#newsNext").attr('disabled') != 'disabled')
        {
            $("#newsPrev").removeAttr('disabled'); 
            $("#newsPrev IMG").fadeTo('fast',1);
			 
            $("#News_"+CurrentNewsItem).hide();
            CurrentNewsItem--;

            $("#News_"+CurrentNewsItem).show();
            if (CurrentNewsItem == 1)
            {
                $("#newsNext IMG").fadeTo('fast',0.5);
                $("#newsNext").attr('disabled','disabled');
            }
        }
    });
	  
	 
    $("#EditQuote").click(function() {
		
        $(".editquote").show();
        $(".describequote").hide();
        $(".postcodelabel").hide();
		
        var FromText = $("#postcodeFrom + .postcodelabel");
        FromText.html(FromText.html().replace(/\d+\s*$/, ""));

        var ToText = $("#postcodeTo + .postcodelabel");
        ToText.html(ToText.html().replace(/\d+\s*$/, ""));
				
        $(this).hide();
		
        $("#booking").slideUp("fast");
		
    });

    $("#EditEbayQuote").click(function() {
		
        $(".editquote").show();
        $(".describequote").hide();
		
        $(this).hide();
		
        $("#booking").slideUp("fast");
        $("#MakeEbayBooking").show();

    });
	
    function get_cookies_array() 
    {
        var cookies = { };
        if (document.cookie && document.cookie != '') 
        {
            var split = document.cookie.split(';');
            for (var i = 0; i < split.length; i++) 
            {
                var name_value = split[i].split("=");
                name_value[0] = name_value[0].replace(/^ /, '');
                cookies[decodeURIComponent(name_value[0])] = decodeURIComponent(name_value[1]);
            }
        }
        return cookies;
    }
		
    $("#MakeBooking").live("click", function() {
        var This = $(this);
        setTimeout(function() {

            if(This.attr("disabled") == "disabled")
                return;

            var pc = $("#postcodeFrom").val().split(' ');
            var PostCode = pc.pop();
            var State = pc.pop();
            var Suburb = pc.join(' ');
            $("#pickupsuburb").val(Suburb);

            var pc = $("#postcodeTo").val().split(' ');
            var PostCode = pc.pop();
            var State = pc.pop();
            var Suburb = pc.join(' ');
            $("#deliverysuburb").val(Suburb);

            if($("#ShowDHLTerms"+(1+parseInt($('input:radio[name=quotenum]:checked').val(),10))).val() == 1)
                $("#acceptDHLDIV").show();
            else
                $("#acceptDHLDIV").hide();

            if($("#ShowPayPal"+(1+parseInt($('input:radio[name=quotenum]:checked').val(),10))).val() == 1)
                $("#paypalSPAN").show();
            else
                $("#paypalSPAN").hide();

            if($("#IsExpressService"+(1+parseInt($('input:radio[name=quotenum]:checked').val(),10))).val() == 1)
                $("#lithiumDIV").show();
            else
                $("#lithiumDIV").hide();

            Submitting = true; // trick validation code
            if (  !($("#quoteFormBox, .quoteFormBox").validationEngine('validateField',$("#postcodeFrom")) || $("#quoteFormBox, .quoteFormBox").validationEngine('validateField',$("#postcodeTo"))) )
            { 
                var c = get_cookies_array(); 
                if (c && "pickupdetails" in c)
                {
                    var p = JSON.parse(c.pickupdetails.replace(/^js:/, ""));
                    if (typeof(p)=="string")
                        p = JSON.parse(p);
				
                    if (typeof(p)=="object")
                    {
                        $("#companyname").val(p.companyname);
                        $("#contactname").val(p.contactname);
                        $("#phone").val(p.phone);
                        $("#email").val(p.email);
                        $("#confirmemail").val(p.email);
                        if ($("#postcodeFrom").val()==p.postcodeFrom)
                        {
                            $("#pickupcompany").val(p.pickupcompany);
                            $("#pickupcontact").val(p.pickupcontact);
                            $("#pickupphone").val(p.pickupphone);
                            $("#pickupaddress1").val(p.pickupaddress1);
                            $("#pickupaddress2").val(p.pickupaddress2);
                            $("#pickupsuburb").val(p.pickupsuburb);
                        }
                    }	
                }
			
                ToggleSameDayMessage();
                $("#pickupDate").datepicker("setDate",$("#pickupDate").datepicker("getDate")); // forces  calendar refresh 


                $("#postcodeFrom + .postcodelabel").html($("#postcodeFrom").val());
                $("#postcodeTo + .postcodelabel").html($("#postcodeTo").val());
	 	 
                $(".editquote").hide();
                $(".describequote").show();
                $(".postcodelabel").show();		
					
                $("#EditQuote").show();	

                $("#quoteFormBox .describequote, .quoteFormBox .describequote").each(function(idx, el) {
			
                    if($(this).closest(".quotecontainer").find("INPUT").val())
                    {
                        if($(this).closest(".quotecontainer").find("INPUT").attr("id") == "transportassurance")
                        {
                            $(this).text("$" + $(this).closest(".quotecontainer").find("INPUT").val());
                        }
                        else
                        {
                            $(this).text($(this).closest(".quotecontainer").find("INPUT").val());
                        }
                    }
                    if($(this).closest(".quotecontainer").find("SELECT option:selected").text())
                        $(this).text($(this).closest(".quotecontainer").find("SELECT option:selected").text());
			
                });

                $("#EditQuote").hide().attr('disabled',true);
			
                if(/MSIE (?:6|7)\./.test(navigator.appVersion))
                {
                    $("#booking").show();
                    $("#booking INPUT:first").focus();
                    $("#buckets").hide();
                }
                else
                {			
                    $("#booking").slideDown("fast", function() {
                        $("#booking INPUT:first").focus();
                    });
                }
            }
            Submitting = false; // trick validation code

        }, 100);
    });

    $("#MakeEbayBooking").live("click", function() {
        var This = $(this);
        setTimeout(function() {

            if(This.attr("disabled") == "disabled")
                return;

            if($("#ShowDHLTerms"+(1+parseInt($('input:radio[name=quotenum]:checked').val(),10))).val() == 1)
                $("#acceptDHLDIV").show();
            else
                $("#acceptDHLDIV").hide();

            if($("#ShowPayPal"+(1+parseInt($('input:radio[name=quotenum]:checked').val(),10))).val() == 1)
                $("#paypalSPAN").show();
            else
                $("#paypalSPAN").hide();

            if($("#IsExpressService"+(1+parseInt($('input:radio[name=quotenum]:checked').val(),10))).val() == 1)
                $("#lithiumDIV").show();
            else
                $("#lithiumDIV").hide();

            Submitting = true; // trick validation code
            if ( true )
            { 
                ToggleSameDayMessage();
                $("#pickupDate").datepicker("setDate",$("#pickupDate").datepicker("getDate")); // forces  calendar refresh 


                $(".editquote").hide();
                $(".describequote").show();
					
                $("#EditQuote").show();	

                $("#quoteFormBox .describequote").each(function(idx, el) {
			
                    if($(this).closest(".quotecontainer").find("INPUT").val())
                    {
                        if($(this).closest(".quotecontainer").find("INPUT").attr("id") == "transportassurance")
                        {
                            $(this).text("$" + $(this).closest(".quotecontainer").find("INPUT").val());
                        }
                        else
                        {
                            $(this).text($(this).closest(".quotecontainer").find("INPUT").val());
                        }
                    }
                    if($(this).closest(".quotecontainer").find("SELECT option:selected").text())
                        $(this).text($(this).closest(".quotecontainer").find("SELECT option:selected").text());
			
                });

                if(/MSIE (?:6|7)\./.test(navigator.appVersion))
                {
                    $("#booking").show();
                    $("#booking INPUT:first").focus();
                    $("#buckets").hide();
                }
                else
                {			
                    $("#booking").slideDown("fast", function() {
                        $("#booking INPUT:first").focus();
                    });
                }
            }
            Submitting = false; // trick validation code

            $("#MakeEbayBooking").hide();
            $("#EditEbayQuote").show();

        }, 100);
    });
	
    $("#Lithium").change(function() {
        if($(this).val() == "yes")
        {
            $("#Quotes").find('.isexpressservice[value="1"]').closest("TR").hide();
            $("#Quotes").find('.isexpressservice[value="0"]:first').closest("td").children('input[type="radio"]:first').attr("checked", "checked");
            var err = "Unfortunately Lithium batteries cannot be transported via an air freight service. A road freight service has automatically been chosen for this booking";
            
            if($('select[name=ServiceType] option').length>2) //corporate customer
                {
                    $('#booking').hide();
                    $("#EditQuote").show().attr('disabled',false);
                    $('#MakeBooking').validationEngine("showPrompt",err , "load");
                    $('select[name=ServiceType] option[value=AlliedExpressRoad]').attr('selected',true).trigger('change');
                    $('#MakeBooking').click();
                    
                }
            else
                $(this).validationEngine("showPrompt", err, "load");
        };
        if($(this).val() == "no")
        {
            $("#Quotes").find('.isexpressservice').closest("TR").show();
            $("#Quotes").find('.isexpressservice:first').closest("td").children('input[type="radio"]:first').attr("checked", "checked");
        };
    });
	
	$("#agreeterms").fancybox({
	
		mode : "ajax",
		frameWidth : 780,
		frameHeight : 580,
		hideOnContentClick : false
	
	});
	
    $(".popup").fancybox({
        mode : "ajax",
        frameWidth : 780,
        frameHeight : 580,
        hideOnContentClick : false
    });
	
    $("#termslink").fancybox({
		
        mode : "ajax",
        frameWidth: 780,
        frameHeight: 580,
        hideOnContentClick : false
		
    });

    $("#track").fancybox({ 
		
        itemArray : function() {

            return [{
                href : "/track?popup&consignment=" + encodeURIComponent($("#consignment").val())
            }];
			
        },
        mode : "ajax",
        frameWidth: 800,
        frameHeight: 600,
        hideOnContentClick : false
		
    });
	
    $("#logoutlink").click(function(evt) {
	
        $("#logoutform").submit();
	
        evt.preventDefault();
	
    });
	
    $("#suggestionslink").fancybox({
		
        mode : "ajax",
        frameWidth: 712,
        frameHeight: 448,
        hideOnContentClick : false
		
    });

    $("#trackform").submit(function(evt) {

        evt.preventDefault();

        $("#track").click();
		
    });
	
    $("#receipteddelivery").live("change", function(e) {
        $(this).val($(this).is(":checked") ? "yes" : "no");
        refreshQuote();
    });

    $("#taillift, #TailLift, #ServiceTypeQuote, #ServiceType, #corporateUserID").live("change", function(e) {

        refreshQuote();
		
    });
	
    $("#gotodescribeitem").live("click", function(e) {
	
        document.location.hash = "#" + $("#product").val();
	
        e.preventDefault();
		
    });
		
    $("#companyname,#contactname,#phone").change(function(evt) {
	
        var me = $(this);
        var pickup = $({
            "companyname" : "#pickupcompany", 
            "contactname" : "#pickupcontact", 
            "phone" : "#pickupphone"
        }
        [me.attr("id")]);
        var value = me.data("originalvalue");
		
        if(value == undefined)
        {
            value = me[0].defaultValue;
        }
		
        if(value == pickup.val())
            pickup.val(me.val());
		
        me.data("originalvalue", me.val());
    });
	
    $("#paywithpaypal,#paywithcreditcard").click(function(evt) {
	
        $("#paymentmethod").val(this.id.replace(/^paywith/, ""));
        $("#payform").submit();
	
        evt.preventDefault();
		
    });
	
    $("#quoteFormBox INPUT, .quoteFormBox INPUT").live("change", function(e){

        if (this.id == "transportassurance")
        {	
            var t = $("#transportassurance").val();
            if (t)
            {	
                t = t.replace('$','');
                t = parseFloat(t,10);
            }
			
            if ( t && (t > 0) )
                $("#acceptTWDIV").show()
            else	
                $("#acceptTWDIV").hide();
        }

        setTimeout(refreshQuote, 100);
		
    });
	
    $("#QuoteAddItem, .QuoteAddItem").live("click", function(evt) {

        $("#booking").hide();

        var me = $(this);
        var eBay = me.closest('form').attr('id') == 'ebayenableform';
        if (eBay)
            var ListingPart = '_'+me.attr("id").split('_')[1]
        else
            var ListingPart = '';
		
        var lastrow = $("#quoteFormBox"+ListingPart+" TABLE > TBODY > TR:last-child, .quoteFormBox"+ListingPart+" TABLE > TBODY > TR:last-child");
        var newrow = lastrow.clone(true);

        var target = $("SELECT", newrow);
        var ID = target.attr("id").match(/[^_]+$/); 

        var oldsuffix = ListingPart + "_" + (parseInt(ID,10));
        var newsuffix = ListingPart + "_" + (parseInt(ID,10) + 1);
        target.attr("id","description" + newsuffix);
        if (eBay) target.attr("name","description" + newsuffix);
		
        var target = $("#weight"+oldsuffix, newrow);
        target.attr("id","weight" + newsuffix);
        if (eBay) target.attr("name","weight" + newsuffix);
		
        var target = $("#height"+oldsuffix, newrow);
        target.attr("id","height" + newsuffix);
        if (eBay) target.attr("name","height" + newsuffix);
		
        var target = $("#length"+oldsuffix, newrow);
        target.attr("id","length" + newsuffix);
        if (eBay) target.attr("name","length" + newsuffix);
		
        var target = $("#depth"+oldsuffix, newrow);
        target.attr("id","depth" + newsuffix);
        if (eBay) target.attr("name","depth" + newsuffix);
	
        newrow.find("TD:first-child").text($("#quoteFormBox"+ListingPart+" TABLE > TBODY > TR, .quoteFormBox"+ListingPart+" TABLE > TBODY > TR").length + 1);
        newrow.find("SELECT,INPUT").val("");
	
        $("#quoteFormBox"+ListingPart+" TABLE > TBODY, .quoteFormBox"+ListingPart+" TABLE > TBODY").append(newrow);
		
        if(ID == 19)
            $(this).hide();
	
        evt.preventDefault();
        evt.stopPropagation();
		
    });
    /*	
	$("#quoteFormBox TABLE > TBODY > TR:last-child INPUT, #quoteFormBox TABLE > TBODY > TR:last-child SELECT").live("change", function() {
	
		$("#QuoteAddItem").click();
		
	});
*/	
    $(".removequoteline").live("click", function(evt) {
        var me = $(this);
        var eBay = me.closest('form').attr('id') == 'ebayenableform';
        if (eBay)
            var ListingPart = '_'+me.attr("id").split('_')[1]
        else
            var ListingPart = '';
	
        me.closest("TR").remove();
        $("#quoteFormBox"+ListingPart+" TABLE > TBODY > TR > TD:first-child, .quoteFormBox"+ListingPart+" TABLE > TBODY > TR > TD:first-child").each(function(idx, el) {
		
            $(el).text(idx + 1);
			
        });
	
        $("#quoteFormBox"+ListingPart+",.quoteFormBox"+ListingPart).validationEngine('hideAll');
		
        if ($("#booking").length>0)// we are on booking screen, not quote screen
            setTimeout("refreshQuote()", 100);
		
    });
	
    $("BODY#payment INPUT#Ecom_Payment_Card_Number").focus();
	
    function checkhash()
    {
        if(/^\#!?\/?track\?(?:.*&)*consignment=/.test(document.location.hash))
        {
            var m = document.location.hash.match(/consignment=([^&]*)/)[1];

            $("#consignment").val(m);
            $("#track").click();
        }		
    }
	
    $(window).bind("hashchange", checkhash);
	
    checkhash();
	
	$("#ebaydeletesold, #ebaydeletepaid, #ebaydeletebooked").click(function() {
	
        var EbayForm = $(this).closest("TABLE");
	
        EbayForm.fadeTo(300, 0.2);	
        $(".ajaxloader").show();
		
        var PostData = "";
		
        EbayForm.find("INPUT:checked").each(function() {
		
            var Line = $(this).val().split(/_/);
			
            PostData += "listingid=" + encodeURIComponent(Line[0]) + "&transactionid=" + encodeURIComponent(Line[1]) + "&";
		
        });
		
        $.ajax({
            type : "POST",
            url : "/account/",
            data : "action=deletetransaction&" + PostData,
            success : function() {
			
                EbayForm.find("TR:has(INPUT:checked),TR:has(INPUT:checked)+TR").remove();
			
            },
            complete : function() {
			
                EbayForm.fadeTo(300, 1);	
                $(".ajaxloader").hide();
			
			
            }
        });
	
    });
	
    $("#ebayemailsold").click(function() {
	
        var EbayForm = $("#ebaysolditems");
	
        EbayForm.fadeTo(300, 0.2);	
        $(".ajaxloader").show();
		
        var PostData = "";		
		
		EbayForm.find("INPUT:checked:not(:disabled)").each(function() {
		
            var Line = $(this).val().split(/_/);
			
            PostData += "listingid=" + encodeURIComponent(Line[0]) + "&transactionid=" + encodeURIComponent(Line[1]) + "&";
		
        });
		
        $.ajax({
            type : "POST",
            url : "/account/",
            data : "action=resendemail&" + PostData,
            success : function() {
			
				EbayForm.find("TD:has(INPUT:checked) .EmailSent").show();
				EbayForm.find("INPUT:checked").attr("disabled", "disabled");
						
            },
            complete : function() {
			
                EbayForm.fadeTo(300, 1);	
                $(".ajaxloader").hide();
			
			
            }
        });		

		
    });
	
    $("#ebaymarkpaidsold").click(function() {
	
        var EbayForm = $("#ebaysolditems");
	
        EbayForm.fadeTo(300, 0.2);	
        $(".ajaxloader").show();
		
        var PostData = "";		
		
        EbayForm.find("INPUT:checked").each(function() {
		
            var Line = $(this).val().split(/_/);
			
            PostData += "listingid=" + encodeURIComponent(Line[0]) + "&transactionid=" + encodeURIComponent(Line[1]) + "&";
		
        });
		
        $.ajax({
            type : "POST",
            url : "/account/",
            data : "action=markaspaid&" + PostData,
            success : function() {
			
			
						
            },
            complete : function() {
			
                document.location = "/account/ebay/awaitingbooking";
			
            }
        });			
	
    });
	
   	$("#ebayprintbooked").click(function() {

		var EbayForm = $("#ebaybookeditems");	
		var Bookings = [];
		
		EbayForm.find("TD:has(INPUT:checked) INPUT[name=bookingid]").each(function() {
		
			Bookings.push("id=" + $(this).val());
		
		});
		
		if(Bookings.length > 0)
		{
			window.open("/account/booking/smartsend.pdf?" + Bookings.join("&"), "ssmultibook");	
		}
		
	});

	$("#ebaysolditems TH INPUT:checkbox, #ebaypaiditems TH INPUT:checkbox, #ebaybookeditems TH INPUT:checkbox").click(function() {
	
        var This = $(this);
        var Form = This.closest("TABLE");
	
        if(This.attr("checked"))
        {
            Form.find("TD INPUT:checkbox").attr("checked", "checked");
            Form.find("TFOOT INPUT").removeAttr("disabled");
        }
        else
        {
            Form.find("TD INPUT:checkbox").removeAttr("checked");
            Form.find("TFOOT INPUT").attr("disabled", "disabled");		
        }
	
    });
	
	$("#ebaysolditems TD INPUT:checkbox, #ebaypaiditems TD INPUT:checkbox, #ebaybookeditems TD INPUT:checkbox").click(function() {
	
        var Form = $(this).closest("TABLE");
	
        if(Form.find("TD INPUT:checked").length > 0)
            Form.find("TFOOT INPUT").removeAttr("disabled");
        else
            Form.find("TFOOT INPUT").attr("disabled", "disabled");			
	
    });
	
    if($("#ebaysolditems TD INPUT:checked").length > 0)
        $("#ebaysolditems TFOOT INPUT").removeAttr("disabled");
    if($("#ebaypaiditems TD INPUT:checked").length > 0)
        $("#ebaypaiditems TFOOT INPUT").removeAttr("disabled");
	if($("#ebaybookeditems TD INPUT:checked").length > 0)
		$("#ebaybookeditems TFOOT INPUT").removeAttr("disabled");

    $("#ebaydisableform").submit(function(evt) {
	
        var EbayForm = $(this);
	
        EbayForm.fadeTo(300, 0.2);	
        $(".ajaxloader").show();		
	
    });
	
    $("#ebayenableform").submit(function(evt){

        evt.preventDefault();
        evt.stopPropagation();

        var EbayForm = $(this);

        EbayForm.find(".ui-autocomplete-input").autocomplete('close');

        result = true;
		
        var LocationList = [];
        var LocationsVisited = {};

		
        $("#EbayListings TR:has(INPUT:checked)+TR+TR .ebaypickuplocation").each(function() {
		
            var LocationValue = $(this).val();
			
            if(!(LocationValue in LocationsVisited))
            {
                LocationList.push(LocationValue);
            }
		
        });
		
        $('#EbayListings input[name=listingid]:checked').each(function() { 
            var ListingID = $(this).val();
   
            var suffix = "_" + ListingID; 
            var options	= $('#options'+suffix+',#ebayoptions'+suffix);
            if (options.val())
                var obj = JSON.parse(options.val());
            else
                var obj = {
                    TailLift:0
                };

            checkLastItemLine(evt,ListingID);

            for(var i=1;;i++)
            {
                var suffix = "_" + ListingID + "_" + i;
                var description=$('#description'+suffix);
                if (description.length==0)
                    break;
			
                var weight	= $('#weight'+suffix);
                var height 	= $('#height'+suffix);
                var depth 	= $('#depth'+suffix);
                var length 	= $('#length'+suffix);
			  
                if (!description.val() || description.val().length==0)
                {
                    result = false;
                    description.validationEngine('showPrompt','please select a package description','error','topRight',true);
                }
                if (!weight.val() || weight.val()==0 || !height.val() || height.val()==0 || !depth.val() || depth.val()==0 || !length.val() || length.val()==0)
                {
                    result = false;
                    if (!weight.val() || weight.val()==0)
                        weight.validationEngine('showPrompt','please enter a weight','error','topRight',true);
                    if (!height.val() || height.val()==0)
                        height.validationEngine('showPrompt','please enter a height','error','topRight',true);
                    if (!depth.val() || depth.val()==0)
                        depth.validationEngine('showPrompt','please enter a depth','error','topRight',true);
                    if (!length.val() || length.val()==0)
                        length.validationEngine('showPrompt','please enter a length','error','topRight',true);
                    
                    
                }
                
                //check the length
                var items = [height,depth,length];
                for( idx in items)
                {
                    var x = checkLength(items[idx]);
                    if(typeof(x)!=="undefined") 
                    {
                           items[idx].validationEngine('showPrompt',x,'error','topRight',true);
                           result=false;
                    }
                }			  
                var ebaytaillift = $("input[name='ebay_TailLift']:checked").val();

                if (weight.val()>80 && !(obj.TailLift == 2 || obj.TailLift == 3 || ebaytaillift > 1))
                {
                    result = false;
                    //removed: ebayoptionslink.click
                    if(description.val()==6) //pallet
                            checkForkLift(weight);
                        else
                            weight.validationEngine('showPrompt',"Individual items over 80kgs require a 'Tail-Lift Truck' service to be added at the pickup and/or delivery address, otherwise drivers may refuse to pickup and/or deliver the goods, resulting in additional charges to you. A 'Tail-Lift Truck' pickup is optionable if you have a forklift available to help load the goods. However a 'Tail-Lift Truck' delivery service is mandatory and can be added to the quoting process from the options listed here",'error','topRight',true);
                    
                    
                }	  
            } // for each item

        });
		
        if(result == false)
            return;
		
        EbayForm.fadeTo(300, 0.2);
        $(".ajaxloader").show();		
		
        $.ajax({
            type : "GET",
            url : "/addresscheck?a=" + encodeURIComponent(JSON.stringify(LocationList)),
            dataType : "json",
            success : function(result) {
			
                if(result.valid)
                {
                    EbayForm.unbind("submit");
                    EbayForm.submit();
					
                    EbayForm.find("INPUT").attr("disabled", "disabled");
                }
                else
                {
                    EbayForm.fadeTo(300, 1);
                    $(".ajaxloader").hide();
				
                    $(".ebaypickuplocation").validationEngine('showPrompt','Suburb / Postcode combination could not be found','error','topRight',true);
                }
			
            },
            error : function() {
			
                EbayForm.fadeTo(300, 1);
                $(".ajaxloader").hide();
			
            }
        });		
		
    });
	
    $("#genkey").click(function(evt) {

        $.ajax({
            type : "GET",
            url : "/admin/genkey",
            success : function(data) {
                $("#key").val(data);
            }
        });

        evt.preventDefault();
        evt.stopPropagation();

    });

    $("#linkcorporateaccountlink").click(function(evt) {
        evt.preventDefault();
        $("#linkcorporateaccountdiv").slideDown();
        $("#linkcorporateaccountdiv INPUT").focus();
    });

    $(".resendemailform").submit(function(evt) {
    
        evt.preventDefault();
    
        var ThisForm = $(this);
		
        ThisForm.ajaxSubmit({
            beforeSubmit: function() {
                ThisForm.hide();
                ThisForm.closest("td").find("img").show();
            },
            success: function() {
                ThisForm.closest("td").html("Email sent");
            }
        });

        return false;
    });

    $(".descriptionselect").change(function() {

        if($(this).val()==12)
        {
            $(this).validationEngine('showPrompt', 'Tyres/Wheels should preferably be packaged in sturdy cartons/boxes to provide protection and security during transport. If you do not have suitable boxes available, layers of shrinkwrap (pallet plastic wrapping) or bubblewrap around the individual items should be sufficient but ensure they are tightly wrapped with no loose wrapping.', 'load');
        }
        else
            $(this).validationEngine('hidePrompt');

    });

    $(".enablelistingcheckbox").live("click", function()
    {
        SetNewEbayListinngsButtonState();
    });

    $(".disablelistingcheckbox").live("click", function()
    {
        if($(".disablelistingcheckbox:checked").length > 0)
            $("#disablesmartsendbutton").removeAttr("disabled");
        else
            $("#disablesmartsendbutton").attr("disabled", "disabled");
    });
	
    $("#ebay_mandatory_transport_assurance").validationEngine();
    $("#ebay_mandatory_transport_assurance").change(function() {
	
        $("#ebay_mandatory_transport_assurance").validationEngine('showprompt', "Transport Assurance is limited to $10,000", "load", true);
	
    });

	if(/agreeterms/.test(document.location.search))
	{	
		$("#agreeterms").click();
	}

}); // $(function(){

function SetNewEbayListinngsButtonState()
{
    if($(".enablelistingcheckbox:checked").length > 0)
    {
        $("#enablesmartsendbutton").removeAttr("disabled");
    }
    else
    {
        $("#enablesmartsendbutton").attr("disabled", "disabled");
    }
}

function refreshQuote()
{
    if($("#fullquote #ServiceType, #payform #ServiceTypeQuote").val() == "DHLExpress")
    {
        if($("#TailLift").val() > 0)
        {
            $("#TailLift").val(0);
            $("#notailliftmessage").show();
        }
        $(".question:has(#TailLift)").hide();
    }
    else
    {
        $(".question:has(#TailLift)").show();
        $("#notailliftmessage").hide();
    }

    //	Submitting = true;
    if(!$('#payform').validationEngine('validate'))
    {
        if(this.xhr)
        {
            this.xhr.abort();
            this.xhr = null;
        }

        this.currentquote = "";

        return;
    }

    var quotedata = $("#payform").serialize();
    if(this.currentquote == quotedata || quotedata == "")
        return;

    this.currentquote = quotedata;

    $("#QuoteLoading").show();

    if(this.xhr)
    {
        this.xhr.abort();
        this.xhr = null;
    }
	
    this.xhr = $.ajax({
        type : "GET",
        url : "/quoteajax",
        data : quotedata,
        dataType : "json",
        success : function(data) {

            Submitting = false;
            for(var i = 0; i < data.length; i++)
            {			
                $(data[i].id).replaceWith(data[i].content);
            }
			
            var t = $("#transportassurance").val();
            if (t)
            {	
                t = t.replace('$','');
                t = parseFloat(t,10);
            }
			
            if ( t && (t > 0) && (!$("#receipteddelivery").is(":checked")))
                $("#assurancewarn").show()
            else
                $("#assurancewarn").hide();

			
            ToggleSameDayMessage(); 
            $("#pickupDate").datepicker("setDate",$("#pickupDate").datepicker("getDate")); // forces  calendar refresh 
			
            $("#QuoteLoading").hide();
            /* We need to remove this hidden element after the first load so that any subsequent edits will not result in quotes
			 * being limited to the original service type. See ticket #154 */
            //$("#payform #ServiceType").remove();

			
            this.xhr = null;
        },

        error : function(xhr, textStatus, errorThrown)
        {
            Submitting = false;
            this.xhr = null;
        }
    });
}

function refreshEbayTransactionQuote()
{
    $(".submit").attr("disabled", "disabled").fadeTo(300, 0.2);
    $("#ebayquotetable").fadeTo(300, 0.2);
    $(".ajaxloader").show();
    $.ajax({
        type : "GET",
        url : "/selectquoteajax",
        data : {
            "listingid" : $("#ListingID").val(), 
            "transactionid" : $("#TransactionID").val(), 
            "location" : $("#DeliveryPostcode").val(), 
            "selection" : $("INPUT[name=selection]:checked").val(), 
            "rd" : $("#rd:checked").val(), 
            "ta" : $("#ta:checked").val()
        },
        success : function(html) {
            $("#ebayquotetable").html(html);
            $(".ajaxloader").hide();
            $("#ebayquotetable").fadeTo(300, 1);
            $(".submit").removeAttr("disabled").fadeTo(300, 1);			
        },
        error : function() {
            $(".submit").removeAttr("disabled").fadeTo(300, 1);					
        }
    });	
}

function checkLastItemLine(evt,ListingID){
    if (ListingID)
        var ListingPart = '_'+ListingID;
    else
        var ListingPart = '';

	
    var p = $('#quoteFormBox'+ListingPart+' table tbody tr').not(':first');
	
    var names = ['description','weight','height','length','depth'];

    p.each(function(){
	
        var remove = true;
        for(i=0;i<names.length;i++)
        {
            if($(':input[name^="'+names[i]+'"]',this).val())
                remove = false;
        }
        if(remove) $(this).remove();
		
    })

}

function userTypeSelector(){
    $('INPUT[type=radio].usertype').click(function(){
        var me = $(this);
        var input = me.parents('.left-col').next();
			
        $('P:has(INPUT.usertype:radio) + P, DIV.left-col:has(INPUT.usertype:radio) + DIV').not(input).slideUp('fast');
			
        if(input.is(':hidden')){
            input.slideDown('fast', function() {
                input.find("INPUT[type=text]").focus();
            });
        }
    });
    
    var Selected = $('INPUT[type=radio].usertype:checked');
    if(Selected.length == 0)
        $('#qqcasual').click();
    else
        Selected.parents('.left-col').next().show();
}

var lastdescription;
function toggleeBayDescription(evt, ctrl, listingid)
{
    lastdescription = ctrl;
    var description = $("#ebaydescription");
    var that = description.data("attached_to");
    var ListingID = listingid;
	
    if(!ListingID)
    {
        ListingID = "";
	
        try
        {
            ListingID = ctrl.attr("id").split(/_/)[1];	
        }
        catch(e)
        {
		
        }
    }
			
    if(evt)
    {
        evt.preventDefault();
        evt.stopPropagation();
    }
	
    var Frame = $("#ebaydescription IFRAME");	

    if(description.is(":visible") && this != that)
    {
        var DescriptionHTML = Frame.contents().find("BODY").html();	
	
        description.stop(true, true).show("slide", {
            direction : "up"
        }, 400, function() {
		
            });	
		
        $.ajax({
            type : "POST",
            url : "/account/",
            data : {
                "action" : "ebaysavedescription",
                "listingid" : ListingID,
                "description" : DescriptionHTML
            }
        });			
    }



    if(description.is(":hidden"))
    {
        description.data("attached_to",this);
        description.css('left', "228px");
        description.css('top', (ctrl.position().top+ctrl.height() + 4) + "px");
		
        Frame.fadeTo(300, 0.2);
        Frame.attr("src", "/account/ebay/itemdescription?l=" + encodeURIComponent(ListingID));
        $(".ajaxloader").show();
		
        Frame.one("load", function() {
		
            Frame.fadeTo(300, 1);
            $(".ajaxloader").hide();		
		
        });
		
        description.stop(true, true).show("slide", {
            direction : "up"
        }, 400, function() {
		
            });		
		
        $(document).bind("click", function(evt){

            if(description.is(':visible'))
            {
                if($.contains(description[0],evt.target))
                    return
                else
                    setTimeout(function() {
                        toggleeBayDescription(null,lastbutton, ListingID);
                    }, 0);
            }
            $(this).unbind(evt);
        });		
    }
    else
    {
        var DescriptionHTML = Frame.contents().find("BODY").html();

        description.stop(true, true).hide("slide", {
            direction : "up"
        }, 400, function() {

            Frame.fadeTo(300, 1);
            $(".ajaxloader").hide();
		
        });		
		
        $.ajax({
            type : "POST",
            url : "/account/",
            data : {
                "action" : "ebaysavedescription",
                "listingid" : ListingID,
                "description" : DescriptionHTML
            }
        });			
    }
	
    return false;
}

var lastbutton;
function toggleeBayOptions(evt,button,fn)
{
    lastbutton = button;
    var options = $('#ebayoptions');
    var HTML = button.html();
    var that = options.data("attached_to");
    var ListingID;
    var optionsinput;

    if(evt)
    {
        evt.preventDefault();
        evt.stopPropagation();
    }

    if (options.is(':visible') )
        $('#ebay_both').validationEngine('hideAll');	

    
    // if div is already displayed for a different listing we have to process...
    if (options.is(':visible') && this != that)
    {
        var lastbutton = $(that);
        ListingID = lastbutton.attr("id").replace("optionslink_","");

        HTML = lastbutton.html();

        SaveeBayOptions(ListingID);

        options.stop(true, true).hide("slide", {
            direction : "up"
        }, 400, function() {
            HTML = HTML.replace("Hide","Additional");
            HTML = HTML.replace("\u00AB","\u00BB");
            lastbutton.html(HTML);
            options.data("attached_to",null);
            button.click();
        });
		
        return false;
    }	

    ListingID = button.attr("id").replace("optionslink_","");
		
    if(options.is(':hidden')) // or options.css("display")=="none"
    {
        options.data("attached_to",this);
        options.css('left', "208px");
        options.css('top', (button.position().top+button.height() - 1) + "px");
		
        LoadeBayOptions(ListingID);
		
        options.stop(true, true).show("slide", {
            direction : "up"
        }, 400, function() {
            HTML = HTML.replace("Additional","Hide");
            HTML = HTML.replace("\u00BB","\u00AB"); // � , �
            button.html(HTML);
			

            if(fn)
                fn();

            $(document).bind("click", function(evt){

                if(options.is(':visible'))
                {
                    if($.contains(options[0],evt.target))
                        return
                    else
                        setTimeout(function() {
                            toggleeBayOptions(null,lastbutton);
                        }, 0);
                }
                $(this).unbind(evt);
            });
        });
    }
    else
    {
        if(options.validationEngine('validate'))
        {
            SaveeBayOptions(ListingID);
	
            options.stop(true, true).hide("slide", {
                direction : "up"
            }, 400, function() {
                HTML = HTML.replace("Hide","Additional");
                HTML = HTML.replace("\u00AB","\u00BB");
                button.html(HTML);
                options.data("attached_to",null);
            });
        }
    }

    return false;
    
    function LoadeBayOptions(ListingID)
    {
        $("#ebay_ServiceType").val($("#servicetype_" + ListingID).val());
        $("input[name=ebay_receipt][value=" + $("#receipt_" + ListingID).val() + "]").attr("checked", "checked");
        $("#ebay_transport_assurance_value").val($("#assurancevalue_" + ListingID).val());
		
        if(/^true$/i.test($("#assurancemandatory_" + ListingID).val()))
            $("#ebay_mandatory_transport_assurance").attr("checked", "checked");
        else
            $("#ebay_mandatory_transport_assurance").removeAttr("checked");
		
        $("input[name=ebay_TailLift][value=" + $("#taillift_" + ListingID).val() + "]").attr("checked", "checked");
        $("input[name=ebay_freightsurcharge][value=" + $("#pricefunction_" + ListingID).val() + "]").attr("checked", "checked");
    }
    
    function SaveeBayOptions(ListingID)
    {    
        var FreightPriceOption = $('input[name=ebay_freightsurcharge]:checked').val();
        if(!FreightPriceOption)
            FreightPriceOption = "0";
			
        var FreightDiscount = parseInt($("#ebay_freightpercentagevalue").val(), 10);
        if(!FreightDiscount)
            FreightDiscount = 0;
			
        FreightPriceOption = FreightPriceOption.replace(/Discount/ig, (FreightDiscount / 100.0).toFixed(2));
		
        $("#servicetype_" + ListingID).val($("#ebay_ServiceType option:selected").val());	
        $("#receipt_" + ListingID).val($("input[name=ebay_receipt]:checked").val());
        $("#assurancevalue_" + ListingID).val($("#ebay_transport_assurance_value").val());
        $("#assurancemandatory_" + ListingID).val($("#ebay_mandatory_transport_assurance:checked").length > 0);
        $("#taillift_" + ListingID).val($("input[name=ebay_TailLift]:checked").val());
        $("#pricefunction_" + ListingID).val(FreightPriceOption);
		
        var data = {
            "action" : "saveebayitem",
            "listingid" : ListingID,
            "servicetype" : $("#ebay_ServiceType option:selected").val(),
            "receipt" : $("input[name=ebay_receipt]:checked").val(),
            "assurancevalue" : Math.min($("#ebay_transport_assurance_value").val(), 10000),
            "assurancemandatory" : $("#ebay_mandatory_transport_assurance:checked").length > 0,
            "taillift" : $("input[name=ebay_TailLift]:checked").val(),
            "pricefunction" : FreightPriceOption
        };
		
        $.ajax({
            type : "POST",
            url : "/account/",
            data : data
        });
    }
}

function toggleAdditionalOptions(evt,fn){
    if(!options_visible)
    {
        $('#quote').addClass('additional');
        $('#additional').stop(true, true).show("slide", {
            direction : "left"
        }, 400, function() {

            $('#options').html('Less Options &laquo;');
            if(fn) fn();
        });

    }
    else
    {
        $('#additional').stop(true, true).hide("slide", {
            direction : "left"
        }, 400, function() {

            $('#options').html('Additional Options &raquo;');
            $('#quote').removeClass('additional');

        });

    }
    options_visible = !options_visible;

    if(evt)
    {
        evt.preventDefault();
        evt.stopPropagation();
    }
    return false;
}

function checkPhone(me, rules, i, options)
{
	if (!(/0{1}\d{9}\s*$/.test($(me).val())))
    {	
        Submitting = false;
        return "A valid phone number containing 10 numbers must be provided. Landline phone numbers must contain the area code. This is vital to the delivery process.";
    }
    if(/000000000|111111111|222222222|333333333|444444444|555555555|666666666|777777777|888888888|999999999|123456789|1234567890/.test($(me).val()))
    {	
        Submitting = false;
        return "Phone number is invalid";
    }
    if ($(me).attr('name') == "destphone")
    {
        if ($(me).val() == $("#pickupphone").val())
        {
            Submitting = false;
            return "A different phone number is required for pickup and delivery. This is vital to the delivery process.";
        }
    }
}

function checkGrays(me, rules, i, options)
{
    if (/gr[a|e]y+\'*s*\s*on+\s*(?:line*)/i.test(($(me).val())))
    {	
        Submitting = false;
        return "Unfortunately Smart Send cannot pick up from Grays Online Branches.";
    }
}

function checkPOBox(me, rules, i, options)
{
    if (/p+[\s\.]*o+[\s\.]*box/i.test(($(me).val())))
    {	
        Submitting = false;
        return "Smart Send cannot deliver to PO Boxes.";
    }
    if (/post+\s*office+\s*box+/i.test(($(me).val())))
    {	
        Submitting = false;
        return "Smart Send cannot deliver to PO Boxes.";
    }
}

function checkFurniture(me, rules, i, options){ 
    if($(me).val() == 13)
    {
        Submitting = false;
        return "Smart Send does not transport assembled furniture or bedding. We can however transport new furniture that is disassembled and well packaged inside a flat pack or strong sturdy box/carton. Please change the description to FLAT PACK or CARTON to proceed.";
    }
}

function checkLength(me, rules, i, options){
	
    var options = checkSetup(me);
    var prompt = false;
    var currLength = parseInt($(me).val());

    if(isNaN(currLength) && !options.eBay) // eBay listings are checked on 'enablement'
    {
        Submitting = false;
        return me.attr('id').replace(/^\w/, function($0) {
            return $0.toUpperCase();
        }) + " is a required field";
    }
    
    if(currLength == 0)
    {
        Submitting = false;
        return me.attr('id').replace(/^\w/, function($0) {
            return $0.toUpperCase();
        }) + " cannot be 0";    	
    }
    
    
    //this function is yet to work for ebay auctions. 
    var serviceType = $('#ServiceType,#ServiceTypeQuote', options.formParent); 
    //test and error message


    if(serviceType.length>0 && $.inArray(serviceType.val(), 
            ['Express','AlliedExpressOvernight', 'TNTOvernight', 'TNTOvernightAM','DHLExpress','AaEExpressEconomy','AaEExpressPremium']))
    {
        options.maxlength=$('#ServiceType option:selected,#ServiceTypeQuote option:selected', options.formParent).attr('maxlength');
        
        if(currLength>options.maxlength)
        {
            prompt = "Maximum "+$(me).attr('name')+" we can accept for Express is "+options.maxlength+" cm (" + (options.maxlength / 100) + " metres).";
        }
    }
    else
    {
        if(currLength>options.maxlength)
        {
            prompt = "Maximum "+$(me).attr('name')+" we can accept is "+options.maxlength+" cm (" + (options.maxlength / 100) + " metres).";
        }
    }
    //return
    if(prompt!=false)
    {	
        Submitting = false;
        // for ticket #151
        if ($(me).attr('name').toUpperCase() == "HEIGHT")
            return prompt.replace($(me).attr('name'),"dimension")
        if (options.eBay)
            return prompt.replace($(me).attr('name'), $(me).attr('name').split('_')[0]); //remove the listing part and the number
        
            return prompt;
    }
}

function checkExpressType(me, rules, i, options){
    
    var jqme = $(me);
    var myparent = jqme.parents('form');
    
    if("DHLExpress" == $("#ServiceType").val())
    {
        $("#truck-none").click();
        $(".section.truck INPUT").attr("disabled", "disabled");
        $(".section.truck STRONG, .section.truck LABEL").css("color", "#aaa");
    }
    else
    {
        $(".section.truck INPUT").removeAttr("disabled");
        $(".section.truck STRONG, .section.truck LABEL").css("color", "");
    }

    $("#fullquote, #quickQuote, #payform").validationEngine('hide');
    $("#fullquote, #quickQuote, #payform").validationEngine('validate');
}


//Pull in the details for this check.
function checkSetup(me){
    var options = {};
    //parent
    options.formParent = $(me).closest('form');

    options.eBay = options.formParent.attr('id') == 'ebayenableform';
    if (options.eBay)
        options.ListingPart = '_'+me.attr("id").split('_')[1]
    else
        options.ListingPart = '';
   
    
    //what if this is the quote.cfm form?
    options.idx = "";
    if($(me).attr('id').indexOf('_') != -1)
        options.idx = "_" + $(me).attr('id').match(/[^_]+$/);
    
    //setup
    options.desc = $('#description, #description'+options.ListingPart+options.idx, options.formParent);
    //options.desc_option = $('#description option:selected, #description'+options.idx+' option:selected', options.formParent);
    options.desc_option = $('#description'+options.ListingPart+options.idx+' option:selected');
    options.val = options.desc_option.val();

    //second person
    options.secondperson = options.desc.attr('secondperson'); //default
    if(options.desc_option.attr('secondperson')>0)
        options.secondperson = options.desc_option.attr('secondperson');

    //check forklift weight
    options.forklift = options.desc.attr('forklift'); //default
    if(options.desc_option.attr('forklift')>0)
        options.forklift = options.desc_option.attr('forklift');
    
    //check max weight
    options.maxweight = options.desc.attr('maxweight');
    if(options.desc_option.attr('maxweight')>0)
        options.maxweight = options.desc_option.attr('maxweight');
    
    //check max length
    options.maxlength = options.desc.attr('maxlength');
    if(options.desc_option.attr('maxlength')>0)
        options.maxlength = options.desc_option.attr('maxlength');
    
    return options;
}

function checkWeight(me, rules, i, options){
    var prompt=false;
    var options = checkSetup(me);
    
    //defaults
    var msg=false;

    //test and error message
    if(parseInt($(me).val())>options.maxweight)
    {
        msg = "Maximum weight for '"+options.desc_option.text().match(/^([^\(])+/)[0]+"' is "+options.maxweight+" kgs."
        if(options.desc_option.attr('maxweight_msg')) msg = msg + " " + options.desc_option.attr('maxweight_msg');
    }

    //return
    if(msg!=false) 
    {
        Submitting = false;
        return msg;
    }	
}

function checkSecondPerson(me, rules, i, options){
    var prompt=false;
    
    var options = checkSetup(me);

    if($(me).val() < parseInt(options.maxweight) && $(me).val()>parseInt(options.secondperson) && (options.forklift == undefined || $(me).val()<parseInt(options.forklift)))
    {
        prompt = options.desc_option.attr("secondperson_msg");
		
        if(!prompt)
        {		
            switch(options.val){
                case '2':
                case '5':
                case '6':
                case '7':
                case '8':
                case '10':
                    //prompt = options.desc_option.text().match(/^([^\(])+/)[0] + "s over " + options.secondperson + "kgs require a 2nd person to help the driver load and unload the goods. If you cannot guarantee someone will be available for pickup or delivery, you should consider adding a 'Tail-Lift Truck' service to your booking to ensure there are no issues with pickup or delivery.";
		    prompt = "Items over 30kgs require a forklift to load and unload the goods.  If you cannot arrange a forklift you MUST add a 'Tail-Lift Truck' service to your booking via the Quick Quote section.  Otherwise driver's may refuse to pickup and/or deliver the goods resulting in cancellation or additional charges to you";
                    break;
                default:
                    prompt = options.desc_option.text().match(/^([^\(])+/)[0] + "s over " + options.secondperson + "kgs require a 2nd person to help the driver load unload the goods. Pickup will be refused by the driver otherwise.";
                    break;
            } 
        }
        if(prompt)
        {
            Submitting = false;
            if(options.formParent.attr('id')!='quickQuote')
            {
                if (options.eBay)
                {
                    var position = $("#optionslink_"+me.attr("id").split('_')[1]);
                    toggleeBayOptions(null,position, function(){
                        $('#ebay_both', options.formParent).validationEngine('showPrompt',prompt,'load', true);
                    });
                }	
                else
                    $("#TailLift").validationEngine('showPrompt',prompt,'load', true);
            }
            else
            {
                toggleAdditionalOptions(null,function(){
                    $('#both', options.formParent).validationEngine('showPrompt',prompt,'load', true);
                });
            }
        }
    }
   
}

function checkEmails(me, rules, i, options)
{
    if ($(me).val() != $('#email').val())
    {
        Submitting = false;
        return "Confirmation email address does not match email address";
    }	
}


function checkName(me, rules, i, options)
{
    if ($(me).val() != $('#pickupcontact').val()) 
        return;
	
    if (confirm("IF YOU ARE BOTH THE SENDER AND RECEIVER IN THIS BOOKING PLEASE CLICK OK TO PROCEED. IF YOU ARE NOT SENDING AND RECEIVING THE GOODS YOURSELF, PLEASE ENTER THE CORRECT SENDER OR RECEIVER CONTACT NAME TO ENSURE THERE ARE NO ISSUES WITH PICKUP OR DELIVERY."))
        return;   
	
    $(me).val("");
    Submitting = false;
    return "Please enter correct destination contact name";
}



function checkPostcodes(me, rules, i, options)
{
    if (!Submitting) // can't check postcode fields on blur etc as the autocomplete plugin populates fields AFTER valdiation plugin is invoked, resulting in false negatives
        return;

    var description = ($(me).attr('name') == "postcodeTo") ? "destination" : "pickup";
    var location = jQuery.trim($(me).val());
	
    if (location == "Postcode or Town" || location.length<4)
    {	
        Submitting = false;
        return "You must select a " + description + " location ";
    }	
    else
    {
        $.ajax({
            type : "GET",
            url : "/validatelocation",
            data : "location=" + location,
            success : function(msg) {
                if(msg != "ok")
                {
                    Submitting = false;
                    return "Please select a " + description + " location town and state from the list provided. If no list was provided, this postcode is not a valid postcode. Please note we cannot pickup from or deliver to PO Box/GPO/Mail Bag postcodes.";
                }
            }
        });

        location = location.split(' ');
		
        if (location.length < 3)
        {
            Submitting = false;
            return "Please select a " + description + " location town and state from the list provided. If no list was provided, this postcode is not a valid postcode. Please note we cannot pickup from or deliver to PO Box/GPO/Mail Bag postcodes.";
        }	
        else
        {
            var pc = location.pop(); // get postcode
            try
            {
                ValidatePostcode(pc);
            }
            catch (e)
            {
                Submitting = false;
                return description + " postcode is not valid";
            }
            var state = location.pop(); // get state
            if (jQuery.inArray(state.toUpperCase(),["ACT", "NSW", "NT", "QLD", "SA", "TAS", "VIC", "WA"])==-1)
            {
                Submitting = false;
                return description + " state is not valid";
            }	
        }	
    }
}

function checkForkLift(me, rules, i, options){
  
    //defaults
    var options = checkSetup(me);
    var prompt=false;
    if($(me).val() < parseInt(options.maxweight) && $(me).val() > parseInt(options.forklift))
    {
        switch(options.val)
        {
            case '10':
                prompt = "Maximum weight for '" + options.desc_option.text().match(/^([^\(])+/)[0] + "' description is " + (options.desc_option.attr('maxweight')?options.desc_option.attr('maxweight'):desc.attr('maxweight')) + "kgs. Please strap the Length to a SKID or PALLET and choose the correct description from the drop down list. You should also consider adding a 'Tail-Lift Truck' service to your booking to ensure there are no issues with pickup or delivery.";
                break;
            case '5':
            case '6':
            case '7':
                prompt =  options.desc_option.text().match(/^([^\(])+/)[0]+ "s over " + options.forklift + "kgs require a fork lift to load & unload the goods.  If you cannot arrange a forklift you must add a 'Tail-Lift Truck' service to your booking. Otherwise drivers may refuse to pickup and/or deliver the goods, resulting in additional charges to you.";
                break;
            default:
                prompt = options.desc_option.text().match(/^([^\(])+/)[0] + 's over ' + options.forklift + 'kgs require a fork lift to load and unload the goods. Pickup will be refused by driver otherwise.';
                break;
        }
        Submitting = false;
        if (options.eBay)
            var PromptTarget = $("#ebay_both", options.formParent);
        else
            var PromptTarget = $("#both", options.formParent);
        
        if(PromptTarget.length == 0)
        {
            $("#TailLift").validationEngine('showPrompt',prompt,'load', true);
        }
        else
        {
            if (options.eBay)
            {
                
                var position = $("#optionslink_"+me.attr("id").split('_')[1]);
                toggleeBayOptions(null,position, function(){
                    PromptTarget.validationEngine('showPrompt',prompt,'load', true);
                });
            }	
            else
                toggleAdditionalOptions(null,function(){
                    PromptTarget.validationEngine('showPrompt',prompt,'load', true);
                });		
        }		
    }
}


/*
 * getTimeAt() will return the current time at the given postcode, which is provided as a 4 character string
 * 
 * Will throw an exception for an invalid australian postcode, and assumes 1st sunday in October through 1st Sunday in April (rules as of 2011)
 * DST calculate does not check time of day, so will be innacurate betweeen midnight and 2AM on day of switchover
 *  
 *  There are two australian postcodes which contain multiple timezones:
 *
 *  	7151: Antartic bases. Function will simply return AEST (same as Hobart)
 *  	6443: WA border towns. Majority of population (<200) are in CWST so that is returned. The time will be wrong for the 2 or 3 towns in AWST
 *  
 */
function getTimeAt(postcode)
{
    var d = new Date(); 
    var utc = d.getTime() + (60000*d.getTimezoneOffset()); // local time converted to UTC
    return new Date(utc + (60000*getTZOffset(postcode))); 
}

function ValidatePostcode(postcode)
{
    if (!/^\d{4}$/.test(postcode))	
        throw("invalid postcode:"+postcode);
    var pc = parseInt(postcode,10);
	
    if (postcode<200 || (postcode>299 && postcode<800))
        throw("invalid postcode:"+postcode);
	
    return pc;
}

/* Australian post codes:
ACT 0200�0299, 2600�2618, 2900�2920
NSW 1000�2599,2619-2898, 2921�2999
NT 0800-0999
QLD 4000�4999, 9000�9999
SA 5000�5999
TAS 7000-7999
VIC 3000�3999, 8000�8999
WA 6000-6999
Places with timezone exceptions:
broken hill 2880
Norfolk Island 2899
Christmas Island 6798
Cocos (Keeling) Islands 6799
Antartic bases 7151
Lord howe 2898
WA border towns 6443
*/

function getTZOffset(postcode)
{
    /* Note that all antartic bases are in TAS postcode 7151 but have different timezones. AEST will be used.
	   Note that the 6443 post code contains some towns that are on AWST rather than CWST as calculated here 
	*/
    var pc;
	
    try
    {
        ValidatePostcode(postcode);
    }
    catch(e)
    {
        return 600;
    }
	
    var offset = 600; // start with AEST assumption of UTC+10. QLD, NSW (except broken hill), VIC, TAS and ACT
	
    // test for other cases
    if (postcode==2880 /*broken hill*/ || (postcode>=5000 && postcode<=5999) /*SA*/ || (postcode>=800 && postcode<=999) /*NT*/ )
        offset = 570  // ACST UTC+9.5
    else 
    if (postcode==2899) // Norfolk Island
        offset = 690   // UTC+11.5
    else 
    if (postcode==2898) // Lord Howe Island
        offset = 630   // UTC+10.5
    else 
    if (postcode==6798) // Christmas Island
        offset = 420   // UTC+7
    else 
    if (postcode==6799) // Cocos (Keeling) Islands
        offset = 390   // UTC+6.5
    else 
    if (postcode==6443) // Eucla, Caiguna, Madura, Mundrabilla and Border Village etc. on SA/WA border
        offset = 525   // CWST UTC+8.75
    else 
    if (postcode>=6000 && postcode<=6999) // WA
        offset = 480;  // AWST UTC+8

    return offset + getDSTOffset(postcode);	
}

function checkDST()
{
    /* return true if the date (ignoring time) is withing DST in Australia 
 * NOTE - not all states follow DST
 */
    var date = new Date();
    var m = date.getMonth();

    if (m>4 && m<10) return false;
    if (m>10 || m<4) return true;
    var d = date.getDate();
    if (m==10 && d>=6) return true;
    if (m==4  && d>=6) return false;	

    /* we are somewhere in the first week of April or October */
	
    var lsm = new Date(date.getFullYear(),2,31); // last day of March
    lsm.setDate(31-lsm.getDay()); // last Sunday of March
    lsm.setTime(lsm.getTime()+(7*24*60*1000)); // first Sunday of April
    var lso = new Date(date.getFullYear(),8,30); // last day of September
    lso.setDate(30-lso.getDay()); // last Sunday of Sep
    lso.setTime(lso.getTime()+(7*24*60*1000)); // first Sunday of October
    return (date < lsm || date >= lso);
}

function getDSTOffset(postcode)
{
    /* Note that all antartic bases are in TAS postcode 7151 but have different timezones. AEST will be used.
	   Note that the 6443 post code contains some towns that are on AWST rather than CWST as calculated here 
	*/
    if (postcode==7151 /*Antartic bases*/ 
        || postcode==6798 || postcode==6799 || postcode==2899 /*Christmas, Cocos (Keeling) and Norfolk Islands*/ 
        || (postcode>=4000 && postcode<=4999) || (postcode>=9000 && postcode<=9999) /*QLD*/
        || (postcode>=800 && postcode<=999) /*NT*/
        || (postcode>=6000 && postcode<=6999 && postcode!=6443) /*WA except border towns*/
            ) return 0;


    if (checkDST())
    {
        // so it IS DST, what is the offset?	
        if (postcode==2898) return 30; //Lord Howe Island		
        return 60; 
    }
    return 0;
}

function sameDayTimer()
{
    var hours=Math.floor(SameDayRemaining/3600); 
    var minutes=Math.floor(SameDayRemaining/60)-(hours*60); 
    var seconds=SameDayRemaining-(hours*3600)-(minutes*60);
    var TimeString = "";
    if(hours == 1)
        TimeString += hours + " hour, "
    else if(hours > 1)
        TimeString += hours + " hours, ";
    if(minutes == 1)
        TimeString += minutes + " minute, "
    else if(minutes > 1)
        TimeString += minutes + " minutes, ";
    if(seconds == 1)
        TimeString += seconds + " second"
    else
        TimeString += seconds + " seconds";
	
    $("#samedaytimer").show();
    $("#samedaytimer").html("You have " + TimeString + " remaining to book a pickup for today.");
    SameDayRemaining--;
    if(SameDayRemaining <= 0)
    {
        $("#samedaytimer").hide();
        $("#samedaytimer").html("");
        clearInterval(SameDayTimerID);
        SameDayTimerID = null;
        alert("Same day pickup no longer available");
    }
}

$(function() {

    $("#EbayListings > THEAD INPUT:checkbox").click(function() {

        $("#EbayListings > TBODY > TR > TD:last-child INPUT:checkbox").attr("checked", $(this).attr("checked"));
        SetNewEbayListinngsButtonState();

    });

});

$(function() {

    var cud = document.cookie;
    if(cud)
        cud = cud.match(/(?:^|\s|;)cud=([^;|\s]*)/);
    if(cud)
        cud = cud[1];
    if(!cud)
        cud = "";

    $("INPUT#corporateUserID:text").change(function() {

        document.cookie = "cud=" + encodeURIComponent($(this).val()) + ";";

    }).val(cud);

});


/*
 *
 * post code required
description, weight, height, length and depth required.

if dangerous goods - we do not carry dangerous goods


if(document.getElementById("ServiceType").value == "Express")
									aryIssuesDisplayed[oItem.name] = 'We cannot accept items over 2.4 metres on the EXPRESS FREIGHT service';
								else
									aryIssuesDisplayed[oItem.name] = 'Maximum length of ' + checkItem + 'cm';
 */

