﻿function rasMain()
{
    this.StringValue = "This is a String"; 
    this.ajaxSection = "#content";
    this.dialogCounter = 0;
    this.ajaxPanel=null;
    this.currentDialog=null;
    this.ajaxMessage=null;
    this.loadGrid=false;
    this.currentGrid=null;
    this.currentPaginator=null;
    this.defaultDate = new Date();
    this.maxDays = 1;
    this.minDays = 1;

    
    var self=this;
    
    this.formatJSONDate = function(jsonDate){
        
        //alert(jsonDate);
        //var parseDate = new Date(parseInt(jsonDate.replace("/Date(", "").replace(")/",""), 10));
        
        var newDate = jsonDate;
        
        //var newDate = dateFormat(parseDate, "dd/mm/yyyy");
        //var newDate = parseDate.format("dd/mm/yyyy");
        //alert(parseDate);
        //alert(parseDate.getDate());
        
        //var newDate = parseDate.getDate() + "/" + (parseDate.getMonth() + 1) + "/" + parseDate.getFullYear();

        //return newDate;
        return newDate;
        //return parseDate;
    }


    this.showDialog = function(header, body, icon, buttons, onClose, width, modal, closeIcon) {

        if (!header) header = "Information";
        if (!body) body = "";
        if (!width) width = "300px";

        if (modal === false)
            modal = false;
        else
            modal = true;

        if (closeIcon === false) closeIcon = false; else closeIcon = true;
        var dialog = new YAHOO.widget.SimpleDialog("message_dialog_" + self.dialogCounter++, {
            width: width,
            fixedcenter: true,
            modal: modal,
            visible: false,
            close: closeIcon,
            constraintoviewport: true,
            draggable: false
        });
        if (onClose) {
            dialog.hide = function() {
                this.destroy();
                onClose();
            };
        }
        dialog.setHeader(header);
        dialog.setBody("<div style='padding-left:25px;text-align:justify;'>" + body + "</div>");
        if (!buttons) buttons = [];
        if (icon == 'warning') dialog.cfg.setProperty("icon", YAHOO.widget.SimpleDialog.ICON_WARN);
        else if (icon == 'ask') dialog.cfg.setProperty("icon", YAHOO.widget.SimpleDialog.ICON_HELP);
        else if (icon == 'info') dialog.cfg.setProperty("icon", YAHOO.widget.SimpleDialog.ICON_INFO);
        else if (icon == 'tip') dialog.cfg.setProperty("icon", YAHOO.widget.SimpleDialog.ICON_TIP);
        else if (icon == 'block') dialog.cfg.setProperty("icon", YAHOO.widget.SimpleDialog.ICON_BLOCK);
        else if (icon == 'alarm') dialog.cfg.setProperty("icon", YAHOO.widget.SimpleDialog.ICON_ALARM);
        else dialog.setBody(body);
        dialog.cfg.queueProperty("buttons", buttons);
        dialog.cfg.setProperty("zIndex", 10000 + self.dialogCounter);
        dialog.render(document.body);
        dialog.show();
        return dialog;



    }
    
    this.loadingPanel=function(msg, dontShow){
	    var panel = new YAHOO.widget.Panel("wait_panel_" + self.dialogCounter++, {
            width:"240px",
            fixedcenter:true,
            close:false,
            draggable:false,
            zindex:10000 + self.dialogCounter,
            modal:true,
            visible:false
        });
	    if(!msg) msg = "Loading, please wait...";
	    panel.setHeader(msg);
	    panel.setBody("<img src='/Content/Images/rel_interstitial_loading.gif'/>");
	    //panel.cfg.setProperty("zIndex", 10000 + self.dialogCounter);
	    panel.render(document.body);
	    if(!dontShow) panel.show();
	    return panel;
    }

    
    this.leftMenuUpdate = function(option){
        self.ajaxSection="#lefContent";
        $("#lefContent").load("/Nav/LeftMenu?option=" + option);
    }    
    
    this.contentUpdate = function(url){
        self.loadGrid=true;
        $("#content").load(url);
    }    
    
    this.submitForm = function(){
        //$("#errorList").hide();
        self.ajaxMessage="Saving, please wait...";
        var options = { 
            //target:     "#content"
            dataType:  'json', 
            success:   self.processJson
        };
        $("#dataForm").ajaxSubmit(options); 
        //$("form").ajaxForm(options); 
        return false;
    }  
    
    this.processJson = function (data) { 
        // 'data' is the json object returned from the server 
        //alert(data); 
        
        
        if (data.success)
        {
            //alert("Success"); 
            if (self.currentDialog)
            {
                if (self.currentGrid)
                {
                    if (self.currentPaginator)
                    {
                        self.createGrid();
                    }
                }
                    
                self.currentDialog.hide();
            }
        }
        else
        {
            if (data.errors)
            {
                $("input[type='text'], textarea, input[type='password']").each(function (i, domElement) {
                        $('#'+domElement.id).css({border:"1px solid #80BFDE"});
                });

            
                var errors = "<br />";
                for (var i = 0; i < data.errors.length; i++) {
                    errors += "<li>" + data.errors[i].Message + "</li>";
                    $('#'+data.errors[i].Field).css({border:"1px solid #FF0000"});
                }
                
                var d = self.showDialog("Validation Errors", errors, "warning", [
        	        { text:"Close", isDefault:true, handler: function(){ this.hide(); } } 
                ], null, "400px");
            }
            else
            {
                 if (data.message)
                 {
                    var d = self.showDialog("Rentaskip", data.message, "alarm", [
        	            { text:"Close", isDefault:true, handler: function(){ this.hide(); } } 
                    ], null, "400px");
                 }
                 else
                 {
                    var d = self.showDialog("Rentaskip", "General error, please contact System Administrator.", "alarm", [
        	            { text:"Close", isDefault:true, handler: function(){ this.hide(); } } 
                    ], null, "400px");
                 }
            }


            
            //alert('tt');
            
            
            //$("#errorList").html(errors);
            //$("#errorList").show();

        }
    }  
    
    // A custom function to translate the js paging request into a query 
	    // string sent to the XHR DataSource 
    this.buildQueryString = function (state,dt) { 
        var query = "startIndex=" + state.pagination.recordOffset + 
               "&results=" + state.pagination.rowsPerPage +
               "&query=" + $('#SearchGrid').val()+ "&time=" + new Date().getTime(); 
        return query;
	}
    
    this.loadStates = function(){
        self.ajaxSection="#State";
        $.getJSON("/Ajax.aspx/GetStates",{countryID: $('#Country').val(), ajax: 'true'}, function(j){
          var options = '';
          options += '<option value="">Select an State</option>';
          for (var i = 0; i < j.records.length; i++) {
            options += '<option value="' + j.records[i].ID + '">' + j.records[i].Name + '</option>';
          }
          $("#State").html(options);
        });
    }
    this.setAjaxLoader = function(){
        
        jQuery().ajaxStart(function()
        {
            //$(self.ajaxSection).fadeOut("fast"); 
            self.ajaxPanel = self.loadingPanel(self.ajaxMessage);
            self.ajaxMessage=null;
        });
        
        jQuery().ajaxStop(function()
        {
            //$(self.ajaxSection).fadeIn("fast"); 
            //self.ajaxSection = "#content";
            self.ajaxPanel.hide();
            if (self.loadGrid)
            {
                if ($('#dynamicdata').length != 0)
                {
                    //alert('creategrid');
                    self.createGrid();
                }
                self.loadGrid=false;
            }
            
            self.createYUIButtons();
            
        });
    }    
    
    this.addNewClient = function()
    {
        $.ajax({
          url: "/Administration/Client",
          cache: false,
          success: function(html){
            //$("#results").append(html);
            var d = self.showDialog("Information Insert", html, "info", [
                { text:"Save", isDefault:true, handler: function(){ self.submitForm(); } },
                { text:"Close",  handler: function(){ this.hide(); } } 
            ], null, "600px");
            
            self.currentDialog=d;
            
          }
        });
    }
    
    this.deleteClient = function(id){
        self.ajaxMessage="Deleting, please wait...";
        $.ajax({
          url: "/Ajax.aspx/DeleteClient?ID=" + id,
          cache: false
        });
    }
    
    this.createGrid = function()
    {
        
        
        var formatAddress = function(elCell, oRecord, oColumn, oData) {
            elCell.innerHTML = "<span id=\"updaterow"+oRecord._sId.replace("yui-rec","")+"\" class=\"yui-button yui-push-button\"> <span class=\"first-child\"> <button id='update' type=\"button\">Update</button> </span> </span> <span id=\"deleterow"+oRecord._sId.replace("yui-rec","")+"\" class=\"yui-button yui-push-button\"> <span class=\"first-child\"> <button id='delete' type=\"button\">Delete</button> </span> </span>";
        }; 
        
    
        // Column definitions
        var myColumnDefs = [ // sortable:true enables sorting
            {key:"ID", label:"ID", hidden:true},
            {key:"Name", label:"Name",width: 400, sortable:false},
            //{key:"button", label:"Show record data", formatter:YAHOO.widget.DataTable.formatButton}
            {key:"button", label:"Action", width: 110, formatter:formatAddress}
        ];

        // Custom parser
        var stringToDate = function(sData) {
            var array = sData.split("-");
            return new Date(array[1] + " " + array[0] + ", " + array[2]);
        };
        
        // DataSource instance
        var myDataSource = new YAHOO.util.DataSource("/Ajax.aspx/GetClients?");
        myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
        myDataSource.responseSchema = {
            resultsList: "records",
            fields: [
                {key:"ID"},
                {key:"Name"}
            ],
            metaFields: {
                totalRecords: "totalRecords" // Access to value in the server response
            }
        };
        
        
        
        
        
        var myPaginator = new YAHOO.widget.Paginator({ 
	        containers         : ['paging'], 
	        updateOnChange     : false,
	        pageLinks          : 5, 
	        rowsPerPage        : 10, 
	        rowsPerPageOptions : [10,30,60], 
	        previousPageLinkLabel :'<small>&lt;&lt;</small>previous',
	        nextPageLinkLabel :'next<small>&gt;&gt;</small>',
	        template           : '{PreviousPageLink} {PageLinks} {NextPageLink}'
	        //template           : '<span class="yui-button yui-push-button"> <span class="first-child">{PreviousPageLink}</span></span> <span class="yui-button yui-push-button"> <span class="first-child"> {PageLinks} </span></span> <span class="yui-button yui-push-button"> <span class="first-child">{NextPageLink}</span></span> {RowsPerPageDropdown}'
	        //template           : '<span class="yui-button yui-push-button"> <span class="first-child">{PreviousPageLink} <span style="border: 1px solid #CBCBCB;"></span> {PageLinks} <span style="border: 1px solid #CBCBCB;"></span> {NextPageLink}</span></span> {RowsPerPageDropdown}'
	    }); 
	    
	    self.currentPaginator=myPaginator;
        
        
        // DataTable configuration
        var myConfigs = {
            initialRequest: "startIndex=0&results=10" + "&query=" + $('#SearchGrid').val() , // Initial request for first page of data
            generateRequest : self.buildQueryString, 
            dynamicData: true, // Enables dynamic server-driven data
            //sortedBy : {key:"Name", dir:YAHOO.widget.DataTable.CLASS_ASC}, // Sets UI initial sort arrow
            //paginator: new YAHOO.widget.Paginator({ rowsPerPage:25 }) // Enables pagination 
            paginator: myPaginator
        };
        
        // DataTable instance
        var myDataTable = new YAHOO.widget.DataTable("dynamicdata", myColumnDefs, myDataSource, myConfigs);
        // Update totalRecords on the fly with value from server
        myDataTable.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
            oPayload.totalRecords = oResponse.meta.totalRecords;
            return oPayload;
        }
        
        myDataTable.subscribe("buttonClickEvent", function(oArgs){
                var oRecord = this.getRecord(oArgs.target);
                //alert(YAHOO.lang.dump(oRecord.getData()));
                //alert(YAHOO.lang.dump(oArgs));
                //alert(oArgs.target.id);
                
                if (oArgs.target.id=="update")
                {
                    $.ajax({
                      url: "/Administration/Client?ID=" + oRecord.getData().ID,
                      cache: false,
                      success: function(html){
                        //$("#results").append(html);
                        var d = self.showDialog("Information Update", html, "info", [
                            { text:"Save", isDefault:true, handler: function(){ self.submitForm(); } },
        	                { text:"Close",  handler: function(){ this.hide(); } } 
                        ], null, "600px");
                        
                        self.currentDialog=d;
                        
                      }
                    });

                
                    //alert('update ' + oRecord.getData().ID);
                    
                }
                    
                if (oArgs.target.id=="delete")
                {
                    var d = self.showDialog("Confirmation", "This operation will delete client: " + oRecord.getData().Name + "<br /> Do you want to delete it ?" , "ask", [
                        { text:"Yes", isDefault:true, handler: function(){ self.deleteClient(oRecord.getData().ID);this.hide();self.createGrid();} },
        	            { text:"No",  handler: function(){ this.hide(); } } 
                    ], null, "400px");
                }
                
            });
            
            
            self.currentGrid=myDataTable;
    
    }
 
    this.createYUIButtons = function() {
        var btn, id;
        $(".yuiButton").each(function (i, domElement) {
                //$('#'+domElement.id).css({border:"1px solid #80BFDE"});
                var onClickAttr = $('#'+domElement.id).attr('onclick');
                btn = new YAHOO.widget.Button(domElement, { onclick: {fn: onClickAttr} });
        });
    }

    this.showMsg = function(header, msg, icon, width, modal) {

        if (icon == undefined)
            icon = "alarm";

        if (width == undefined)
            width = "400px";



        var d = self.showDialog(header, msg, icon, [
        	            { text: "Close", isDefault: true, handler: function() { this.hide(); } }
                    ],
        	            //function() { this.hide(); },
                    false, 
                    width, modal);

        self.currentDialog = d;

    }
    
    this.showNoPostCode = function()
    {
        var msgText = "To avoid our customers wasting time searching for a " +
        "quote only to find that we do not service the post code, "
        "we only show post codes where we do currently have "
        "skips available";
        
        self.showMsg("Why is my post code missing?",msgText, "info");
    }
    
    this.showMoreInfo = function()
    {
        var msgText = "Many municipal and shire councils impose a fee on the householder for placement of a skip outside their property on public land.<br />" +
        "You should consider this when deciding where to place the skip and also when selecting the placement option on the quotation page of rentaskip. If you select the option to place the skip on public land, in many cases this fee will be added to the skip service charge so you will not have to do this seperately yourself.<br />"
        "It is advised that you inquire with your local council if you need to place the skip on public land in order to know if council fee applies."
        
        self.showMsg('Council "kerbside" fees',msgText, 'info', '600px');
    }
    
    this.comboChange = function(combo, newCombo, url, params, selectTitle, selectValues)
    {
        if(combo.value!="")
        {
            $.getJSON(url,params, function(j){
              var options = '';
              options += '<option value="">' + selectTitle + '</option>';
              for (var i = 0; i < j.records.length; i++) {
                options += '<option value="' + j.records[i][selectValues.key] + '">' + j.records[i][selectValues.value] + '</option>';
              }
              $(newCombo).removeAttr("disabled"); 
              $(newCombo).html(options);
              
              if (j.availableDays!=undefined)
              {
                //alert('days');
                $("#dateStart").datepicker('option', 'maxDate', '+' + j.availableDays + 'd');
                $("#dateEnd").datepicker('option', 'maxDate', '+' + j.availableDays + 'd');
              }
              
            });
        }
        else
        {
            $(newCombo).html("");
            $(newCombo).attr("disabled", true); 
        }
    }
    
    this.postCodeChange = function(combo)
    {
        self.comboChange(combo, "#resourceCharge","/Ajax.aspx/ResourceCharge",{postCode: combo.value}, "Select a size",{key:"ResourceTypeID", value:"ResourceType"});
    
        /*
        if(combo.value!="")
        {
            $.getJSON("/Ajax/ResourceCharge",{postCode: combo.value}, function(j){
              var options = '';
              options += '<option value="">Select a size</option>';
              for (var i = 0; i < j.records.length; i++) {
                options += '<option value="' + j.records[i].ResourceTypeID + '">' + j.records[i].ResourceType + '</option>';
              }
              $("#resourceCharge").removeAttr("disabled"); 
              $("#resourceCharge").html(options);
            });
        }
        else
        {
            $("#resourceCharge").html("");
            $("#resourceCharge").attr("disabled", true); 
        }
        */
    }
    
    this.resourceChargeChange = function(combo)
    {
        self.comboChange(combo, "#wastetype","/Ajax.aspx/GetWasteTypes",{postCode:$("#postcode").val() , resourceType: combo.value}, "Select a waste type",{key:"WasteTypeID", value:"WasteTypeDescr"});
    }
    
    this.changeHTML = function(url, params)
    {
        $.ajax({
          url: url,
          data: params,
          cache: false,
          success: function(html){
            $("#mainContent").html(html);
          }
        });
        
    }
    
    this.StepTwo = function()
    {
        var er = false;
        
        var errors = "The following fields are required:<br />";
	    
	    if ($("#postcode :selected").val()==undefined || $("#postcode :selected").val()=="")
	    {
	        errors += "<li>" + "Post code" + "</li>";
	        er = true;
	    }
	        
	    if ($("#resourceCharge :selected").val()==undefined || $("#resourceCharge :selected").val()=="")
	    {
	        errors += "<li>" + "Skip size" + "</li>";
	        er = true;
	    }

	    if($("#dateStart").val()=="" || $("#dateStart").val()==undefined)
	    {
	        errors += "<li>" + "Delivery date" + "</li>";
	        er = true;
	    }    
	        
	    if($("#dateEnd").val()=="" || $("#dateEnd").val()==undefined)
	    {
	        errors += "<li>" + "Collection date" + "</li>";
	        er = true;
	    }
	        
	    if ($("#wastetype :selected").val()=="" || $("#wastetype :selected").val()==undefined)
	    {
	        errors += "<li>" + "Waste type" + "</li>";
	        er = true;
	    }
	    
	    if (er)
            self.showMsg("Validation Errors",errors, "warning");
        else
        {
            var params = {
                postCode : $("#postcode :selected").val(),
                resourceCharge: $("#resourceCharge :selected").val(),
                dateStart: $("#dateStart").val(),
                dateEnd: $("#dateEnd").val(),
                wasteType : $("#wastetype :selected").val(),
                skipPlacement : $("#placement").val()
            };
                
            self.changeHTML("/Home.aspx/Quote", params);
        }
    }
    
    this.StepThree = function()
    {
        self.changeHTML("/Home.aspx/BookIt");
    }
    
    this.StepFour = function()
    {
        self.changeHTML("/Home.aspx/Payment");
    }

    this.setDatePickers = function() {
        $("#dateStart").datepicker({
            //minDate: new Date(), 
            onSelect: function(dateText, inst) {
                //alert(dateText);
                newDate = new Date(dateText);
                //$("#dateEnd").datepicker('option', 'minDate', new Date(dateText));
                //if (newDate.getDay() == 1)
                //    $("#dateEnd").datepicker('option', 'defaultDate', +2);
                    
                $("#dateEnd").datepicker('option', 'minDate', newDate);
            }
        });
        //$("#dateEnd").datepicker({ minDate: new Date() });
        $("#dateEnd").datepicker({ defaultDate: +1 });

    }

    this.initStep1 = function() {

        self.initLocationTypeAh();
        $('#stepone').submit(function() {
            return self.validateStep1();
        });
    }



    this.initLocationTypeAh = function() {
        // Use an XHRDataSource
        var oDS = new YAHOO.util.XHRDataSource("/Ajax.aspx/GetLocations");
        //var oDS = new YAHOO.util.LocalDataSource(preloadDataLC); 
        // Set the responseType
        oDS.responseType = YAHOO.util.XHRDataSource.TYPE_JSON;
        // Define the schema of the JSON results
        oDS.responseSchema = {
            resultsList: "records",
            fields: ["Name", "ID"]
        };
        //oDS.maxCacheEntries = 5000; 
        oDS.queryMatchSubset = true;

        // Instantiate the AutoComplete
        var oAC = new YAHOO.widget.AutoComplete("postcode", "postCodeAuto", oDS);
        // Throttle requests sent
        //oAC.typeAhead = true;
        oAC.queryDelay = 0.0;
        oAC.forceSelection = true;
        // The webservice needs additional parameters
        oAC.generateRequest = function(sQuery) {
            return "?locality=" + sQuery;
        };

        oAC.useIFrame = true;
        oAC.useShadow = true;

        var myHandler = function(sType, aArgs) {
            var oData = aArgs[2];
            $("#LocalityID").val(oData[1] + "");
        };

 
        oAC.itemSelectEvent.subscribe(myHandler);
 

        return {
            oDS: oDS,
            oAC: oAC
        };

    }

    this.validateStep1 = function() {
        var emptySelection = false;

        if ($("#LocalityID").val() == "")
            emptySelection = true;

        if ($("#postcode").val() == "")
            emptySelection = true;


        if (emptySelection) 
            self.showMsg("Rentaskip", "Please select a valid Post Code or Town.", "warning");
        else
            return true;


        return false;

    }
    
    this.addCheckBox = function(name, valueName)
    {
        /*
        if ($("#chkbox"+name).val() == null)
        {
            $("#rentaskip").append("<input  type='hidden' name='" + valueName + "' id='chkbox" + name +"' value ='" + name +"' />");
        }
        else
            $("#chkbox"+name).remove();
        */
        
        $("#" + valueName).val(name);
    }
    
    this.validateStep2 = function()
    {
        var oVal = false;
        $("input:radio:checked").each(
            function() {
                oVal=true;
            }
         );
         
         if (!oVal)
            self.showMsg("Rentaskip", "Please select a skip type.", "warning");

        return oVal;
        
    }
    
    this.validateWasteTypeSelection = function()
    {
        var oVal = false;
        $("input:radio:checked").each(
            function() {
                oVal=true;
            }
         );
         
         if (!oVal)
            self.showMsg("Rentaskip", "Please select a waste type.", "warning");

        return oVal;
        
    }

    this.noSunday = function (date){
          var day = date.getDay();
                      return [(day > 0), ''];
      }

      this.initStepFour = function() {


          //$("#date").datepicker();
          $("#dateStart").datepicker({ minDate: self.minDays,
              maxDate: +40,
              showOn: 'button',
              buttonImage: '../content/images/ac-arrow-dn2.png',
              buttonImageOnly: false,
              dateFormat: 'dd/mm/yy',
              //beforeShowDay: $.datepicker.noWeekends,
              beforeShowDay: self.noSunday,
              onSelect: self.dateChanged
              /* function(dateText, inst) {
              //var newDate = inst.getDate();
              var newDate = $("#dateStart").datepicker('getDate');
              newDate.setDate(newDate.getDate() + 1);
              $('#dateEnd').datepicker('option', 'minDate', newDate);

                  var maxDate = new Date(newDate);
              maxDate.setDate(maxDate.getDate() + self.maxDays);

                  if (maxDate.getDay() == 0)
              maxDate.setDate(maxDate.getDate() + 1);

                  $('#dateEnd').datepicker('option', 'maxDate', maxDate);

              }*/
          });

          $("#dateEnd").datepicker({ minDate: 1,
              maxDate: +40,
              showOn: 'button',
              dateFormat: 'dd/mm/yy',
              buttonImage: '../content/images/ac-arrow-dn2.png',
              buttonImageOnly: false,
              beforeShowDay: self.noSunday
          });

          var endDate = $("#dateEnd").datepicker('getDate');
          if (endDate != null)
              self.dateChanged();
      }

      this.dateChanged = function(dateText, inst) {
          //var newDate = inst.getDate();
          var newDate = $("#dateStart").datepicker('getDate');
          newDate.setDate(newDate.getDate() + 1);
          $('#dateEnd').datepicker('option', 'minDate', newDate);

          var maxDate = new Date(newDate);
          maxDate.setDate(maxDate.getDate() + self.maxDays);

          if (maxDate.getDay() == 0)
              maxDate.setDate(maxDate.getDate() + 1);

          $('#dateEnd').datepicker('option', 'maxDate', maxDate);

      }
    
    this.validateStep4 = function()
    {
        var oVal = true;
        var newDate = $("#dateStart").datepicker('getDate');
        if (newDate == null)
            oVal = false;
        
        newDate = $("#dateEnd").datepicker('getDate');
        
        if (newDate == null)
            oVal = false;
        
         
         if (!oVal)
            self.showMsg("Rentaskip", "Please select a valid delivery and collection date.", "warning");

        return oVal;
        
    }

    this.validateStep5 = function() {
        var oVal = true;
        var msg = "";
        if ($("#address").val() == "") {
            msg = "Street Address is invalid.";
            oVal = false;
        }


        if ($("#name").val() == "") {
            msg = "Name is invalid.";
            oVal = false;
        }

        if ($("#phone").val() == "" && $("#mobile").val() == "") {
            msg = "Phone or Mobile should be input.";
            oVal = false;
        }

        if ($("#email").val() == "") {
            msg = "Email is invalid.";
            oVal = false;
        }

        if ($("#townID").val() == "") {
            msg = "Please select a suburb.";
            oVal = false;
        }


        if (!($('input[name=PrivateLand]').is(':checked') || $('input[name=PublicLand]').is(':checked'))) {
            msg = "Please select a placement.";
            oVal = false;
        }

        if (!oVal)
            self.showMsg("Rentaskip", msg, "warning");

        return oVal;

    }
    
    
    this.validateStep6 = function()
    {
        var oVal = true;
        var msg = "";
        if ($("#specialInstructions:checked").val() == undefined)
        {
            msg = "Please check the terms and conditions.";
            oVal = false;
        }
        
        if (!oVal)
            self.showMsg("Rentaskip", msg, "warning");


        if(oVal)
        {
            self.DoPayment();
        }
        
    }
    
    this.DoPayment = function()
    {
        self.ajaxMessage = "Sending...";
        var $inputs = $('#rentaskip :input');

        $.ajax({
          url: "/Home.aspx/Payment",
          cache: false,
          data: $inputs,
          dataType: "json",
          success: function(json){
          
            if (json.success)
            {
                var rental = json.rent;
                var newHtml = '<h2 class="checkout">Book your skip on-line process</h2><div class="progress_strip seven">&nbsp;</div><h3>Thank you ' + rental.CustomerInformation.Name +  '.</h3><p>Your order has been processed.</p>';
                newHtml = newHtml + '<form id="rentaskip">';
                newHtml = newHtml + '<fieldset><legend>Service Details</legend>';
  	            newHtml = newHtml + '<p class="info"><span class="legend">Order Number</span> <span class="value"> ' + json.orderNumber + '</span></p>';
  	            newHtml = newHtml + '<p class="info"><span class="legend">Client Name</span> <span class="value"> ' + rental.CustomerInformation.Name + '</span></p>';
  	            newHtml = newHtml + '<p class="info"><span class="legend">Delivery Address</span> <span class="value">' + rental.CustomerInformation.Address + ' ' + rental.CustomerInformation.Town + ' ' + rental.PostCode.Name + '</span></p>';
  	            newHtml = newHtml + '<p class="info"><span class="legend">Skip Size</span> <span class="value">' + rental.SkipType + '</span></p>';
  	            newHtml = newHtml + '<p class="info"><span class="legend">Waste Type</span> <span class="value">' + rental.WasteType.Name + '</span></p>';
  	            newHtml = newHtml + '<p class="info"><span class="legend">Delivery Date</span> <span class="value">' + self.formatJSONDate(rental.DateStart) + '</span></p>';
  	            newHtml = newHtml + '<p class="info"><span class="legend">Collection Date</span> <span class="value">' + self.formatJSONDate(rental.DateEnd) + '</span></p>';
  	            newHtml = newHtml + '<p class="info"><span class="legend">Your credit card has been charged the amount of </span> <span class="value">$' + rental.LowestFare.TotalCardCharged + '</span></p>';
  	            newHtml = newHtml + '<p class="info"><span class="legend">Confirmation email sent to</span> <span class="value">' + rental.CustomerInformation.Email + '</span></p>';
                newHtml = newHtml + '</fieldset>';
                newHtml = newHtml + '</form>';
                newHtml = newHtml + '<br/>For support please email <a href="mailto:info@rentaskip.com.au?subject=Information"> info@rentaskip.com.au</a>';
                newHtml = newHtml + '<p><br /><br /><br /></p>';
            
                $('html, body').animate({scrollTop: '0px'}, 200);
                $("div#maincol-in").fadeOut("slow", function () {
                    $("div#maincol-in").html(newHtml);
                    $("div#maincol-in").fadeIn("slow");
                });
            }
            else
            {
                var d = self.showDialog('Rentaskip', json.error, "alarm", [
                    { text:"Close",  handler: function(){ this.hide(); }} 
                ], null, "300px");
                self.currentDialog=d;
            }

          },
          error: function(){
            var d = self.showDialog('Rentaskip', "Error contacting the server. <br /> Try again please.", "alarm", [
                { text:"Close",  handler: function(){ this.hide(); }} 
            ], null, "300px");
            self.currentDialog=d;
          }
        });
        
        
    }
    
    this.EmailUS = function()
    {
        self.ajaxMessage = "Sending...";
        var $inputs = $('#rentaskip :input');

        $.ajax({
          url: "/Home.aspx/EmailUS",
          cache: false,
          data: $inputs,
          dataType: "json",
          success: function(json){
          
            if (json.success)
            {
                $('html, body').animate({scrollTop: '0px'}, 200);
                $("div#emailForm").fadeOut("slow", function () {
                                    $("div#emailForm").html("<br /><br /><h3><p>Thank you for your inquiry. We will respond to you as soon as possible.<br /><br /><br /><br /><br /><br /><br /><br /><br /></p></h3>");
                                    $("div#emailForm").fadeIn("slow");
                                });
            }
            else
            {
                var d = self.showDialog('Rentaskip', json.error, "alarm", [
                    { text:"Close",  handler: function(){ this.hide(); }} 
                ], null, "300px");
                self.currentDialog=d;
            }

          },
          error: function(){
            var d = self.showDialog('Rentaskip', "Error contacting the server. <br /> Try again please.", "alarm", [
                { text:"Close",  handler: function(){ this.hide(); }} 
            ], null, "300px");
            self.currentDialog=d;
          }
        });
        
        
    }

    this.showWhatSkipTrailer = function() {
        self.asyncHTMLLoad("/Home.aspx/WhatSkipTrailer", "What is a mobile skip?");
    }
    
    
    this.showWhatSkipBag = function()
    {
        //self.showMsg('Privacy Policy', '<p>We collect only information that is necessary for the effective running of this site. This includes the processing of skip orders and market analysis. Rentaskip places the most importance on the security of your credit card information and we do not store credit card details in our database. At no time are Rentaskip staff able to see your credit card details. Card details are stored in a secure, encrypted form by the payment gateway, Eway (<a href="www.eway.com.au">www.eway.com.au</a>) to enable us to refund your card if necessary, or to bill you for the second payment in cases where your quote includes a second charge (disposal charge). We guarantee not to sell any of your personal information to any third party at any time.</p>', 'info');
        self.asyncHTMLLoad("/Home.aspx/WhatSkipBag", "What is a skip bag?");
    }

    this.showPrivacyPolicy = function() {
        //self.showMsg('Privacy Policy', '<p>We collect only information that is necessary for the effective running of this site. This includes the processing of skip orders and market analysis. Rentaskip places the most importance on the security of your credit card information and we do not store credit card details in our database. At no time are Rentaskip staff able to see your credit card details. Card details are stored in a secure, encrypted form by the payment gateway, Eway (<a href="www.eway.com.au">www.eway.com.au</a>) to enable us to refund your card if necessary, or to bill you for the second payment in cases where your quote includes a second charge (disposal charge). We guarantee not to sell any of your personal information to any third party at any time.</p>', 'info');
        self.asyncHTMLLoad("/CustPrivacyPolicy.aspx", "Privacy Policy");
    }
    
    this.showRefoundPolicy = function()
    {
        self.asyncHTMLLoad("/CustTermsRefundPolicy.aspx","Refund Policy");
    }
    
    this.showSecurityPolicy = function()
    {
        self.asyncHTMLLoad("/SecurityPolicy.aspx","Security Policy");
    }
    
    
    this.asyncHTMLLoad = function(url, title)
    {
        $.ajax({
          url: url,
          cache: false,
          success: function(html){
            var d = self.showDialog(title, html, "info", [
                { text:"Close",  handler: function(){ this.hide(); }} 
            ], null, "600px");
            
          }
        });
        
        self.currentDialog=d;
    }
    
    this.uncheck = function(checkBox)
    {
        $('input[name=' + checkBox + ']').attr('checked', false);
    }

    this.closeDialog = function(checkBox) {
        
        if (self.currentDialog != undefined)
            self.currentDialog.hide();
        
        self.currentDialog = undefined;
    }
   
}

var rasObj = new rasMain(); 

$(document).ready(function(){
    
   //$.datepicker.setDefaults($.extend({showMonthAfterYear: false}, $.datepicker.regional['en-GB']));
    
    rasObj.setAjaxLoader();
    //alert('rr');
    //alert(preloadData.records[0]);
    //rasObj.setDatePickers();
    //rasObj.showMsg("Error", "General error, please contact System Administrator.");
   
 });

