/**
 * @author Sunil
 */

$(function() {
	//Toggles a password field between text and password
	jQuery.fn.toggleInputType = function(setFocus){
		
		if ($(this).length > 0) {
			if (setFocus == null) 
				setFocus = false;
			
			var newEle = document.createElement("INPUT");
			var curEle = $(this).get(0);
			if (curEle.type == "text") {
				newEle.type = "password";
				newEle.size = "26"; 
			}
			else {
				newEle.type = "text";
				newEle.value = curEle.alt;
				newEle.size = "26";
				setFocus = false;
			}
			
			var props = ['id', 'name', 'className', 'title', 'alt'];
			for (var i = 0, l = props.length; i < l; i++) {
				if (curEle[props[i]]) 
					newEle[props[i]] = curEle[props[i]];
			}
			
			if (curEle.parentNode) {
				curEle.parentNode.replaceChild(newEle, curEle);
				if (setFocus == true) {
				    window.setTimeout("$('#" + newEle.id + "').focus();", 1);
				}
			}
			
			return $("#" + newEle.id);
		}
		else
			return $(this);
	};
	
	jQuery.fn.positionCursor = function(position){
		if ($(this).length > 0 && $.browser.msie) {
			var range = ($(this).get(0)).createTextRange();
			range.move("character", position);
			range.select();
		}
		return $(this);	
	};
	
	//@Sunil : Adding additional rule -> notEqualTo
	jQuery.validator.addMethod(
		"notEqualTo", 
		function(value, element, param){
			return this.optional(element) || (value != $(param).val() && $(param).length >= 1) ||  value != param;
		}, 
		"This has to be different...");
	
	
	/* Dialog to show alerts	*/
	$("#AlertBox").dialog({
		autoOpen: false,
		width: 340,
		height: 250,
		modal:true
	});
	
	$("#alert_ok, #alert_close").click(function(){
		$("#AlertBoxHeader").text("");
		$("#AlertBoxBody").text("");
		$("#AlertBox").dialog('close');					
	});

	jQuery.showAlert = function(header, body){
		$("#AlertBoxHeader").text(header);
		$("#AlertBoxBody").text(body);
		$("#AlertBox").dialog('open');
		$("#alert_ok").focus();
	};
	/* End of alert */
	
	/* Dialog to confirmation alerts	*/
    $("#ConfirmationBox").dialog({
	    autoOpen: false,
	    width: 340,
	    height: 250,
	    modal:true
    });
    
    $("#confirm_ok").click(function(){
        jQuery.showConfirm.okCallback.call(null, $("#ConfirmBoxFormToSubmit").val());
		$("#ConfirmationBox").dialog('close');
		$("#ConfirmBoxFormToSubmit").val("");
		$("#ConfirmBoxHeader").text("");
		$("#ConfirmBoxBody").text("");
		//jQuery.showConfirm.okCallback.call(this, $("#ConfirmBoxFormToSubmit").val());
	});
	
	$("#confirm_cancel, #confirm_close").click(function(){
	    jQuery.showConfirm.cancelCallback.call(null, $("#ConfirmBoxFormToSubmit").val());
		$("#ConfirmBoxHeader").text("");
		$("#ConfirmBoxBody").text("");
		$("#ConfirmBoxFormToSubmit").val("");
		$("#ConfirmationBox").dialog('close');
		//jQuery.showConfirm.cancelCallback.call(this, $("#ConfirmBoxFormToSubmit").val());
		
	});

	jQuery.showConfirm = function(header, body, data, okClick, cancelClick){
		$("#ConfirmBoxHeader").text(header);
		$("#ConfirmBoxBody").text(body);
		jQuery.showConfirm.okCallback = okClick;
		jQuery.showConfirm.cancelCallback = cancelClick;
		$("#ConfirmBoxFormToSubmit").val(data);
		$("#ConfirmationBox").dialog('open');
		$("#confirm_ok").focus();
	};
	/* End of alert */
	
	/* Dialog to show large text */
	$('#CommonDialog').dialog({
		autoOpen: false,
		width: 455,
		height: 440,
		resizable: false,
		modal:true
	});
	
	$(".CommonDialogClose").click(function(){
	    $("#CommonDialogHeader").html("");
		$("#CommonDialogBody").html("");
		$("#CommonDialog").dialog('close');
	});

	jQuery.showDialog = function(header, body){
		$("#CommonDialogHeader").html(header);
		$("#CommonDialogBody").html(body);
		$("#CommonDialog").dialog('open');
	};
	
	/* End of dialog */
	
	/*	FORM FIELDS */
	//@Sunil : Select entered text in email field
	$("INPUT[type=text], INPUT[type=password]").live("focus", function() {
		$(this).select();
		if($(this).attr("id").indexOf("pass") != -1 && $(this).attr("type") != "password" && $(this).attr("id") != "current_password") {
		    $(this).toggleInputType(true).val("");
		}
	});
	
	$("INPUT[type=text], INPUT[type=password]").live("click", function() {
		$(this).select();
		//alert($(this).attr("id") + "\n" + 
		if($(this).attr("id").indexOf("pass") != -1 && $(this).attr("type") != "password") {
		    $(this).toggleInputType(true).val("");
		}
	});
	
	
	$("INPUT[type=text], INPUT[type=password]").live("blur", function() {
	    var id = $(this).attr("id");
		if($(this).val() == "")
		{
		    if($(this).attr("type") == "password") {
				$(this).toggleInputType();
			}

			if (!($(this).hasClass("nolabel")))	{
				$("#" + id).val($("#" + id).attr("title"));
			}
		}
	});	
	/*	END OF FORM FIELDS */
	
	
	/*	SHOPPING CART */
	$(".showCart").click(function(){
		showCart();
	});
	
	$("#clearCart").click(function(){
		removeAllFromCart();
	});
	
	$("#cartUndo").click(function() {
		$.getJSON("/HolidayCart?page.action=undocart&TimeStamp="+ new Date(), "", function(data){
			if(data.code != "0")
				$.showAlert("Holiday Cart", data.message);
			showCart();
		});
	});
	/*	END OF SHOPPING CART */
	
	/* HELP CONTENT */
	jQuery.helpJSONData = null;
	jQuery.currentLanguage = "English";
	jQuery.showHelp = function(field) {
		if($.helpJSONData === (null)) {
			$.ajax({
			    type: 'GET',
			    url: '/help/popupHelp.json',
			    dataType: 'json',
			    success: function(data) {
					$.helpJSONData = data;
				},
			    data: {},
			    async: false
			});
		}
		try {
			
			var keyVal = field;
		var index =	field.indexOf("_");
        while(index != -1){

            field = field.replace("_"," ");

            index = field.indexOf("_");
        }

			$.showDialog(field, $.helpJSONData[keyVal][$.currentLanguage]);
		}
		catch (e) {
			$.showDialog(field, "No help available for this category.");
		}
	};
	/* END OF HELP CONTENT */
	
	$(".interestedButton").click(function(){
		 $("#hidden_customer_plan_name").val("");
		 $("#hidden_customer_plan_type").val("");
	     var plan_name = $(".plan_name_hidden", $(this).closest("form")).val();
		 var plan_type = $(".plan_type_hidden", $(this).closest("form")).val();
	   	 $("#hidden_customer_action_param").val($(".plan_name_hidden").val());
		 $("#hidden_customer_plan_name").val(plan_name);
		 $("#hidden_customer_plan_type").val(plan_type);
		 $("#customer_email").val("Email Address");
		
         $("#customer_name").val("Name");
		 $("#customer_details_captcha").val("Enter verification text");
         $("#customer_contact_number").val("Contact Number");
		 $("#customer_promo_code").val("Discount Code");

		 var post_url="/makeMyHoliday?page.action=getHolidayUser&ts="+ new Date().getTime();
		 $.post(post_url,"", function(data){
			 if(data[0].email != null && data[0].email != ""){
				 $("#customer_email").val(data[0].email);
			 }else{
				 $("#customer_email").val("Email Address");
			 }
			 if(data[0].name != null &&  data[0].name != ""){
				$("#customer_name").val(data[0].name);
			 }else{
				$("#customer_name").val("Name");
			 }
			 if(data[0].contact != null & data[0].contact != ""){
				$("#customer_contact_number").val(data[0].contact);
			 }else{
				 $("#customer_contact_number").val("Contact Number");
			 }
				$("#custDetailsCaptchaImg").attr("src", "/captcha?ts=" + (new Date().getTime()));
				$("#CustomerContactDialog").dialog('open');
				 $("#customer_email").focus();
			}, "json");

		return false;
			
        //$.showConfirm("Experience", "Clicking OK will send your expression of interest to Discover91 for this experience. Please give us 48 hours to respond.", $(this).closest("form").attr("id"));
       
    });
    

	$.ajaxError = function(event, request, settings) {
	    alert(settings.url);
	};

	//Generic help button action
	$(".genericHelp").click(function(event){
		$.showHelp(event.target.id);
		return false;
	});
   $.fn.imageLoader = function(src, f){
		
		var idList=src.split(";");
        return this.each(function(){
			var i= this.id;
	    $("<img>").appendTo(this).attr("src",idList[i]); 
	    });
};
});

function showCart() {
	$.getJSON("/HolidayCart?page.action=showcart&TimeStamp="+ new Date(), "", function(data){
		$("#cityChild").html("&nbsp;");
		$("#locationCount").text("0");
		if(data.locations){
			$("#locationCount").text(data.locations.length);
			$.each(data.locations, function(){
				$("#cityChild").append('<div id="divLocation_' + this.locationId + '" class="rowMergeFloat" style="width:85px">' +
							'<div class="leftBottomCurve curvesCart"></div><div class="midBottomCurve curvesCart" style="width:40px;overflow:hidden;" title="' + this.locationName + '" >' + (this.locationName.length > 10 ? this.locationName.substring(0, 7) + "..." : this.locationName) + '</div>' +
							'<div class="midBottomCurveX curvesCart" onclick=removeLocationFromCart("' + this.locationId + '");>x</div><div class="rightBottomCurve curvesCart"></div>' +
						'</div>');
			});
		}
		
		$("#intChild").html("&nbsp;");
		$("#activityCount").text("0");
		if(data.managedActivities){
			$("#activityCount").text(data.managedActivities.length);
			$.each(data.managedActivities, function(){
				$("#intChild").append('<div id="divActivity_' + this.id.activityId + '_' + this.id.locationId  + '" class="rowMergeFloat" style="width:85px">' +
							'<div class="leftBottomCurve curvesCart"></div><div class="midBottomCurve curvesCart" style="width:40px;overflow:hidden;" title="' + this.activityName + '">' + (this.activityName.length > 10 ? this.activity.activityName.substring(0, 7) + "..." : this.activity.activityName) + '</div>' +
							'<div class="midBottomCurveX curvesCart" onclick=removeActivityFromCart("' + this.id.locationId + '","' + this.id.activityId + '");>x</div><div class="rightBottomCurve curvesCart"></div>' +
						'</div>');
			});
		}
		resizeOpenCart();
	});
}

function removeAllFromCart() {
	$.getJSON("/HolidayCart?page.action=removeall&TimeStamp="+ new Date(), "", function(data){
		if(data.code != "0")
			$.showAlert("Holiday Cart", data.message);
		showCart();
	});
}

function addActivityToCart(locationId, activityId){
	$.getJSON("/HolidayCart?page.action=addactivity&locationid=" + locationId + "&activityid=" + activityId+ "&TimeStamp="+ new Date(), "", function(data){
		if(data.code != "0")
			$.showAlert("Holiday Cart", data.message);
		showCart();
	});
}

function removeActivityFromCart(locationId, activityId){
	$.getJSON("/HolidayCart?page.action=removeactivity&locationid=" + locationId + "&activityid=" + activityId+ "&TimeStamp="+ new Date(), "", function(data){
		if(data.code != "0") 
			$.showAlert("Holiday Cart", data.message);
        showCart();
	});
}

function addLocationToCart(locationId){
	$.getJSON("/HolidayCart?page.action=addlocation&locationid=" + locationId+ "&TimeStamp="+ new Date(), "", function(data){
		if(data.code != "0")
			$.showAlert("Holiday Cart", data.message);
		showCart();
	});
}

function removeLocationFromCart(locationId){
	$.getJSON("/HolidayCart?page.action=removelocation&locationid=" + locationId+ "&TimeStamp="+ new Date(), "", function(data){
		if(data.code != "0") 
			$.showAlert("Holiday Cart", data.message);
		showCart();
	});
}





/* Special code for focus/blur to work with jquery live */
// Courtesy : http://stackoverflow.com/questions/1199293/simulating-focus-and-blur-in-jquery-live-method
(function(){

    var special = jQuery.event.special,
        uid1 = 'D' + (+new Date()),
        uid2 = 'D' + (+new Date() + 1);

    jQuery.event.special.focus = {
        setup: function() {
            var _self = this,
                handler = function(e) {
                    e = jQuery.event.fix(e);
                    e.type = 'focus';
                    if (_self === document) {
                        jQuery.event.handle.call(_self, e);
                    }
                };

            jQuery(this).data(uid1, handler);

            if (_self === document) {
                /* Must be live() */
                if (_self.addEventListener) {
                    _self.addEventListener('focus', handler, true);
                } else {
                    _self.attachEvent('onfocusin', handler);
                }
            } else {
                return false;
            }

        },
        teardown: function() {
            var handler = jQuery(this).data(uid1);
            if (this === document) {
                if (this.removeEventListener) {
                    this.removeEventListener('focus', handler, true);
                } else {
                    this.detachEvent('onfocusin', handler);
                }
            }
        }
    };

    jQuery.event.special.blur = {
        setup: function() {
            var _self = this,
                handler = function(e) {
                    e = jQuery.event.fix(e);
                    e.type = 'blur';
                    if (_self === document) {
                        jQuery.event.handle.call(_self, e);
                    }
                };

            jQuery(this).data(uid2, handler);

            if (_self === document) {
                /* Must be live() */
                if (_self.addEventListener) {
                    _self.addEventListener('blur', handler, true);
                } else {
                    _self.attachEvent('onfocusout', handler);
                }
            } else {
                return false;
            }

        },
        teardown: function() {
            var handler = jQuery(this).data(uid2);
            if (this === document) {
                if (this.removeEventListener) {
                    this.removeEventListener('blur', handler, true);
                } else {
                    this.detachEvent('onfocusout', handler);
                }
            }
        }
    };

})();
function getIndex(input) {
    alert(input);
    var index = -1, i = 0, found = false;
    while (i < input.form.length && index == -1)
    if (input.form[i] == input)index = i;
    else i++;
    return index;
}
 var showImage=0;
function resizeOpenCart() 
{
	$("#hiddenDiv").height($('.hiddenMidContentDiv').height()+15);
}
function ShowCart()
{
		if(showImage++==0)
			{
		    	$("#greenImageForHideShow").attr({src : "/images/green_dropdown2.png"});
		    	$("#hiddenDiv").show('medium',function () {
		    				//$("#hiddenDiv").height($('.hiddenMidContentDiv').height()+15);
		    	resizeOpenCart();
		    	$('#hiddenDivRightLineID').addClass('hiddenDivRightLine'); 
		    	$('.hiddenDivRightLine').css('backgroundImage','url(/images/Horizontal_shadow_bg2.png)');
		    	$('.hiddenDivLeftLine').css('backgroundImage','url(/images/Horizontal_shadow_bg.png)');
		    	});
		    	}
				else
					{
					    $("#hiddenDiv").hide('medium');
    					$("#greenImageForHideShow").attr({src : "/images/green_dropdown.png"});
    					
    					$('.hiddenDivRightLine').css('backgroundImage','');
		    			$('.hiddenDivLeftLine').css('backgroundImage','');
					}
					showImage=showImage%2;
		}
