﻿// Dependencies:
//     jquery.js
//     jquery.micronnexus.js
if (typeof jQuery != "undefined" && typeof jQuery.micronnexus == "object") {
// begin SearchForm

jQuery.micronnexus.SearchForm = function(cfg) { // constructor

	this.langId              = cfg.langId || 0;
    this.supplierId          = cfg.supplierId || 0;
    
	this.preselectedRegionId = cfg.preselectedRegionId || 0; // michal stanko 2009-01-27: as regions are now prefilled server side, this one is a little obsolete 
    
    this.wsUrlRegions = cfg.wsUrlRegions || "webServices/WsRegion.asmx/regions";
    this.wsUrlPickUp  = cfg.wsUrlPickUp || "webServices/WsRegion.asmx/destinations";
    this.wsUrlDropOff = cfg.wsUrlDropOff || this.wsUrlPickUp;
    
    this.controls = {  // form elements we work with (jQuery wrapped)
        $region  : $("select.ddlRegion"), // select
        $pickUp  : $("select.ddlPickUp"), // select
        $dropOffRegion : $("select.ddlDropOffRegion"), // select, used only sometimes
        $dropOff : $("select.ddlDropOff"), // select
        
        $pickUpTypeWrap  : $("span.rblPickUpTypeWrap"), // span
        $dropOffTypeWrap : $("span.rblDropOffTypeWrap"),  // span

		$pickUpTime : $("select.ddlPickUpTime"), // select
		$dropOffTime : $("select.ddlDropOffTime"), // select
		
		$pickUpDateDay : $("select.ddlPickUpDateDay"), // select, not always present
		$pickUpDateMonth : $("select.ddlPickUpDateMonth"), // select, not always present
		$dropOffDateDay : $("select.ddlDropOffDateDay"), // select, not always present
		$dropOffDateMonth : $("select.ddlDropOffDateMonth") // select, not always present
    };
	
	// check the controls (dropOffRegion is an exception and is not required):
	for (var ctl in this.controls) {
		
		// exceptions - controls that may not be present:
		if (ctl == "$dropOffRegion") continue;
		if (ctl.indexOf("$pickUpDate") === 0) continue; // $pickUpDateDay, $pickUpDateMonth 
		if (ctl.indexOf("$dropOffDate") === 0) continue; // $dropOffDateDay, $dropOffDateMonth
		
		// other controls must be there - check them:
		if (this.controls[ctl].length != 1) {
			throw "Failed to initialize "+ ctl +" in SearchForm. Check the controls and their CSS classes.";
		}
	}
	
    this._init();
	
} // end constructor

// An enum:
jQuery.micronnexus.SearchForm.rblTypes = { pickup: "pickup", dropoff: "dropoff" }

// how many days to add to calculate drop-off date after the pick-up date is changed?
// Only implemented for drop-downs as of 2009-02-27. (textboxes w/ajaxtoolkit calendars
// have their own handling of this.)
jQuery.micronnexus.SearchForm.numDaysToShiftDropOff = 7;  

jQuery.micronnexus.SearchForm.prototype.hasDayMonthDropDowns = function() {
	var c = this.controls;
	if (c.$pickUpDateDay.length == 1 && c.$pickUpDateMonth.length == 1 && c.$dropOffDateDay.length == 1 && c.$dropOffDateMonth.length == 1) {
		return true;
	}
	return false;
}

jQuery.micronnexus.SearchForm.getRadioButtonListValue = function($rbListWrap) {
    var $checkedRadio = $("input:radio:checked", $rbListWrap);
    return ($checkedRadio.length == 1) ? $checkedRadio.val() : -1;
}

jQuery.micronnexus.SearchForm.prototype.getPickUpType = function() {
    return jQuery.micronnexus.SearchForm.getRadioButtonListValue(this.controls.$pickUpTypeWrap);
}

jQuery.micronnexus.SearchForm.prototype.getDropOffType = function() {
    return jQuery.micronnexus.SearchForm.getRadioButtonListValue(this.controls.$dropOffTypeWrap);
}

jQuery.micronnexus.SearchForm.prototype.fillRegion = function() {
	var reg = this.controls.$region[0];
	
	// if pre-filled, skip the filling (but locations may need to be refilled):
	if (reg.options.length > 1) {
		if ($("option[selected]", this.controls.$region).length > 1) {
			this.fillPickUpAndDropOff();
		}
		
	    return;
	} else if (reg.options.length == 1 && reg.options[0].value != "0" && reg.options[0].value != "") {
	    return;
	}
	
	this.controls.$region.attr("disabled", "disabled");
    var thisRef = this;
    $.micronnexus.callWebService(this.wsUrlRegions, function(objData) {
        $.micronnexus.fillDropDown(thisRef.controls.$region, objData.d, "RegionId", "RegionName", false, thisRef.preselectedRegionId);
        if (thisRef.preselectedRegionId && thisRef.controls.$pickUp[0].options.length <= 1 && thisRef.controls.$dropOff[0].options.length <= 1) {
            thisRef.fillPickUpAndDropOff();
        }
    }, this.getWSParamsForRegion());
    this.controls.$region.removeAttr("disabled");
}

jQuery.micronnexus.SearchForm.prototype.fillLocation = function($dropDown, $region) {
	if (!$dropDown.hasClass("ddlPickUp") && !$dropDown.hasClass("ddlDropOff")) return false; // error, we want to fill either .ddlPickUp or .ddlDropDown
	
	var $reg;
	if (typeof $region == "undefined" || $region.length != 1) {
		$reg = this.controls.$region;
	} else {
		$reg = $region;
	}
    
	var regionId = $reg[0].value;
	if (regionId == "0") return false; // no filling/requests needed when no region is selected
    
    var types = jQuery.micronnexus.SearchForm.rblTypes;
    var type = ($dropDown.hasClass("ddlPickUp")) ? types.pickup : types.dropoff; // filling a pick-up or a drop-off dropdown?
    
    var destinationTypeId = (type == types.pickup) ? this.getPickUpType() : this.getDropOffType();
    
    $dropDown.attr("disabled", "disabled");
    $dropDown.get(0).options.length = 1; // delete all except first one (having text like "select location")
    var thisRef = this;
    var wsUrl = (type == types.pickup) ? this.wsUrlPickUp : this.wsUrlDropOff;
    $.micronnexus.callWebService(wsUrl, function(objData) {
        var preferredLocationId = 0;
        for (i = 0; i < objData.d.length; i++) {
            if (objData.d[i].IsDefaultValue && objData.d[i].IsDefaultValue == true) {
                preferredLocationId = objData.d[i].DestinationId;
            }
        }
        $.micronnexus.fillDropDown($dropDown, objData.d, "DestinationId", "DestinationName", false, preferredLocationId);
    }, this.getWSParamsForDestinations(regionId, destinationTypeId));
    $dropDown.removeAttr("disabled");
}

jQuery.micronnexus.SearchForm.prototype.fillPickUp = function() {
    return this.fillLocation(this.controls.$pickUp);
}

jQuery.micronnexus.SearchForm.prototype.fillDropOff = function($region) {
	var $ddl;
	if(typeof $region == "undefined" || $region.length != 1) {
		$ddl = this.controls.$region;
	} else {
		$ddl = $region;
	}
    return this.fillLocation(this.controls.$dropOff, $ddl);
}

jQuery.micronnexus.SearchForm.prototype.fillPickUpAndDropOff = function() {
	// if pick up location type and drop off location type are same, only request server data once:
	var pickUpType = this.getPickUpType();
	if (pickUpType == this.getDropOffType()) {
		
		var regionId = this.controls.$region[0].value;
		if (regionId == "0") return false; // no filling/requests needed when no region is selected
	    
	    var $pickUp = this.controls.$pickUp;
		var $dropOff = this.controls.$dropOff;
		
		$pickUp[0].disabled = true;
		$dropOff[0].disabled = true;
		
	    if ($pickUp[0].options.length > 0) {
	        if ($pickUp[0].options[0].value == "" || $pickUp[0].options[0].value == "0") {
	            $pickUp[0].options.length = 1; // delete all except 1st one ("-- select location --")
	        } else {
	            $pickUp[0].options.length = 0;
	        }
	    }
	    
	    if ($dropOff[0].options.length > 0) {
	        if ($dropOff[0].options[0].value == "" || $dropOff[0].options[0].value == "0") {
	            $dropOff[0].options.length = 1; // delete all except 1st one ("-- select location --")
	        } else {
	            $dropOff[0].options.length = 0;
	        }
	        
	    }
	    
	    var thisRef = this;
	    var wsUrl = this.wsUrlPickUp;
	    $.micronnexus.callWebService(wsUrl, function(objData) {
	        var preferredLocationId = 0;
	        for (i = 0; i < objData.d.length; i++) {
	            if (objData.d[i].IsDefaultValue && objData.d[i].IsDefaultValue == true) {
	                preferredLocationId = objData.d[i].DestinationId;
	            }
	        }
	        $.micronnexus.fillDropDown($pickUp, objData.d, "DestinationId", "DestinationName", false, preferredLocationId);
			$.micronnexus.fillDropDown($dropOff, objData.d, "DestinationId", "DestinationName", false, preferredLocationId);
	    }, this.getWSParamsForDestinations(regionId, /*destinationTypeId:*/ pickUpType));
	    
		$pickUp[0].disabled = false;
		$dropOff[0].disabled = false;
		
	} else {
		// pickup/dropoff types are different, must call each one
		this.fillPickUp()
		this.fillDropOff()
	}
}

/**
* @static
*/
jQuery.micronnexus.SearchForm.initAmendSearchSliding = function() {
    var $toggle = $("#amendSearchToggle");
    var $amendWrap = $(".amendWrap");
    
    if ($toggle.length != 1 || $amendWrap.length != 1) return;
    
    if ($amendWrap.hasClass("show")) {
        $toggle.data("isAmendSearchVisible", true);
    } else {
        $toggle.data("isAmendSearchVisible", false);
        $amendWrap.hide();
    }
    
    $toggle.click(function() {
        if ($toggle.data("isAmendSearchVisible") == false) {
            $amendWrap.slideDown(400, function() {
                $toggle.data("isAmendSearchVisible", true);
            });
        } else {
            $amendWrap.hide();
            $toggle.data("isAmendSearchVisible", false);
        }
        return false;
    });
}

jQuery.micronnexus.SearchForm._handlerChangeRegion = function(e) {
	var thisRef = e.data.thisRef;
	if (thisRef.controls.$dropOffRegion.length) {
		thisRef.controls.$dropOffRegion.val(e.target.value);
	}
	
    e.data.thisRef.fillPickUpAndDropOff();
}

jQuery.micronnexus.SearchForm._handlerChangeDropOffRegion = function(e) {
	var thisRef = e.data.thisRef; 
	thisRef.fillDropOff(thisRef.controls.$dropOffRegion);
}

jQuery.micronnexus.SearchForm.prototype.setDropOffDateDropDownsToDate = function(/*Date*/ date) {
	if (this.hasDayMonthDropDowns()) {
		var strDay = date.getDate().toString(); 
		if (strDay.length === 1) { strDay = "0" + strDay; }
		
		var strMonth = (date.getMonth() + 1).toString();
		if (strMonth.length === 1) { strMonth = "0" + strMonth; }
		
		var strYear = date.getFullYear().toString(); 
		var strMonthYear = strMonth+"."+strYear;
		
		this.controls.$dropOffDateDay.val(strDay);
		this.controls.$dropOffDateMonth.val(strMonthYear);
	}
}

jQuery.micronnexus.SearchForm._handlerChangePickUpDateDropDown = function(e) {
	var thisRef = e.data.thisRef;
	
	var tmpMonthYear = thisRef.controls.$pickUpDateMonth.val(); // "02.2009"
	var day   = parseInt(thisRef.controls.$pickUpDateDay.val(), 10);
	var month = parseInt(tmpMonthYear, 10); // turns "03.2009" into 2, etc.
	var year = parseInt(tmpMonthYear.substring(tmpMonthYear.indexOf(".") + 1), 10);
	
	var datePickUp = new Date(year, month - 1, day);
	var dateDropOff = new Date(datePickUp.setDate(day+7)); // add 7 days
	
	thisRef.setDropOffDateDropDownsToDate(dateDropOff);
}

jQuery.micronnexus.SearchForm._handlerClickRblWrap = function(e) {
	
	var $el = $(e.target);
	if ($el[0].nodeName != "INPUT") return;
	
	var thisRef = e.data.thisRef;
	
	var types = jQuery.micronnexus.SearchForm.rblTypes;
	var type = types.pickup;
	if ($el.parents("span[class$='TypeWrap']")[0] == thisRef.controls.$dropOffTypeWrap[0]) { // potential source of error - when radio buttons are not wrapped in <span class="rbl*TypeWrap"/>
		type = types.dropoff;
	}
	
	if (type == types.pickup) {
		
		if (thisRef.controls.$dropOffRegion.length == 1) { // drop-off region is present
			if (thisRef.controls.$region.val() == thisRef.controls.$dropOffRegion.val()) {
				// both regions are the same, change both handover types and fill location drop-downs: 
				$("input:radio[value='" + $el.val() + "']", thisRef.controls.$dropOffTypeWrap)[0].checked = true;
				thisRef.fillPickUpAndDropOff();
			} else {
				thisRef.fillPickUp();
			}
		} else { // drop-off region is not present
			// change both handover types and fill location drop-downs: 
			$("input:radio[value='" + $el.val() + "']", thisRef.controls.$dropOffTypeWrap)[0].checked = true;
			thisRef.fillPickUpAndDropOff();
		}
		
	} else if (type == types.dropoff) {
		
		if (thisRef.controls.$dropOffRegion.length == 1) { // drop-off region is present
			thisRef.fillDropOff(thisRef.controls.$dropOffRegion);
		} else { // drop-off region is not present
			thisRef.fillDropOff();
		}

	}		
}

jQuery.micronnexus.SearchForm._handlerChangePickUp = function(e) {
	var thisRef = e.data.thisRef;
	
	if (thisRef.getPickUpType() == thisRef.getDropOffType()) {
		thisRef.controls.$dropOff.val(e.target.value);
	}
}

jQuery.micronnexus.SearchForm._handlerChangePickUpTime = function(e) {
    var thisRef = e.data.thisRef;
    thisRef.controls.$dropOffTime.val(this.value);
}

jQuery.micronnexus.SearchForm.prototype._addEventListeners = function() {
	this.controls.$region.bind("change", { thisRef: this }, jQuery.micronnexus.SearchForm._handlerChangeRegion); // region change event
	if (this.controls.$dropOffRegion) {
		this.controls.$dropOffRegion.bind("change", { thisRef: this }, jQuery.micronnexus.SearchForm._handlerChangeDropOffRegion)
	}
    this.controls.$pickUpTypeWrap.bind("click", { thisRef: this }, jQuery.micronnexus.SearchForm._handlerClickRblWrap); // pick-up type radio buttons click event
    this.controls.$dropOffTypeWrap.bind("click", { thisRef: this }, jQuery.micronnexus.SearchForm._handlerClickRblWrap); // drop-off type radio buttons click event
    this.controls.$pickUp.bind("change", { thisRef: this }, jQuery.micronnexus.SearchForm._handlerChangePickUp); // pick-up (location) change event
    this.controls.$pickUpTime.bind("change", { thisRef: this }, jQuery.micronnexus.SearchForm._handlerChangePickUpTime); // pick-up time change event
    if (this.hasDayMonthDropDowns()) {
		this.controls.$pickUpDateDay.bind("change", { thisRef : this }, jQuery.micronnexus.SearchForm._handlerChangePickUpDateDropDown); // pick up date day drop-down change event
		this.controls.$pickUpDateMonth.bind("change", { thisRef : this }, jQuery.micronnexus.SearchForm._handlerChangePickUpDateDropDown); // pick up date month drop-down change event
	}
}

jQuery.micronnexus.SearchForm.prototype._init = function() {
	this.fillRegion(); // fill dropdown
	this._addEventListeners();
}

// this parts differs in every website:
jQuery.micronnexus.SearchForm.prototype.getWSParamsForRegion = function() {
    return { "LanguageId": this.langId, "Supplier_ID": this.supplierId };
}

jQuery.micronnexus.SearchForm.prototype.getWSParamsForDestinations = function(regionId, destinationTypeId) {
    return { "LanguageId": this.langId, "RegionId": regionId, "DestinationTypeId": destinationTypeId };
}

// end SearchForm
} // end: if typeof jQuery != "undefined" ...