
/**
 * Process redirect to NMI
 * @param event
 * @return false to block default event
 */
 function processNMIForm(event){
    	mm = jQuery('#expirationMonth_hidden').val();
        if (mm < 10) 
            mm = "0" + mm;
        yy = jQuery('#expirationYear_hidden').val();
        yy = yy.substr(yy.length - 2);
        jQuery('#expirationDate').val(mm + yy);
        jQuery("#credentials").submit();
        return false;
}

 /**
  * jQuery extension to handle ajax requests
  */
(function($) {
	
	var captchaFragment;
	var errorContainer;
	/**
	 * Finds all AJAX forms/link and attach events
	 */
	$(document).ready(function(){
		$("body").ajaxComplete(function(){
			$(this).attachAjaxLogic();
		    $('body').createWidgets();
		    $("*[onRefresh!='']").each(function(){
		    	eval($(this).attr("onRefresh"));
		    });
		    
		});
	    $(this).attachAjaxLogic();
	});

   
	/**
	 * process add to basket
	 */
	function processAddToBasket(data)
	{
		popup.showPopup("selectProductPopup",'c-c');
	}
	
	/**
	 * process add to basket pre-processor event
	 */
	function processBeforeAddToBasket(offerPage, offerItem){
		var json = "[";
		for (var i = 0; i < YAHOO.results.roomOffers[offerItem].length; i++) {
			var room = YAHOO.results.roomOffers[offerItem][i];
			if (room != undefined) {
				json += room.currentOfferIndex + ",";
			}
		}
		// especially for IE
		json = json.substring(0, json.length - 1);
		json += "]";
		
		return '&multiRoomJSON=' + json;
	}

	/**
	 * Update payment methods
	 */
	function updatePaymentPage(data){
		 $(".gptsAjaxContainer").easySwitch();
	}
	
	/**
	 * Validate payment
	 */
	function preparePaymentValidation(ajaxForm){
		$(ajaxForm).attr('onComplite','processPaymentResponse');
		if($("input[name=newUser]",$(ajaxForm)).length == 0)
			$(ajaxForm).append("<input type='hidden' name='newUser' value='none'/>");
		else
    	   $("input[name=newUser]",$(ajaxForm)).val("none");
	}
	
	/**
	 * Post-process event processor
	 */
	function processPaymentResponse(data){
		submitRedirectForm(data);
		showCaptcha(data);
		updatePaymentPage();
	}
	
	/**
	 * Show Captcha
	 */
	function showCaptcha(){
		if(!captchaFragment)
			captchaFragment = $("#captcha>div");
		$("#captchaFragment").append(captchaFragment);
	}
	
	/**
	 * Handle redirect to PSP 
	 */
	function submitRedirectForm(data){
		var url = $('#paymentForm').attr("action");
		if(url && url.indexOf("event_id=failure") == -1)
		{
		  if($('#paymentForm').attr("method").toUpperCase() == "POST"){
		    $('#paymentForm').submit();
		  }
		  else
		    window.location.replace($('#paymentForm').attr("action"));
		}
		else
			$("#paymentFailure").append(errorContainer?errorContainer:$("#errorContainer>div"));
		if($('a#bookingSplash').length == 1)
		  window.location.replace($('a#bookingSplash').attr("href"));
	}
	
	
	/**
	 * Remove script from HTML
	 */
	rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi;
	rhead = /<head\b[^<]*(?:(?!<\/head>)<[^<]*)*<\/head>/gi
	
	/**
	 * Trim string function
	 */
	String.prototype.trim = function() {
		a = this.replace(/^\s+/, '');
		return a.replace(/\s+$/, '');
		};
	
	/**
	 * Attach AJAX logic to ajax components
	 */
	$.fn.attachAjaxLogic = function(){
	   //Forms	
	   $("form[ajax=true]").attachSubmitLogic();
	   //Command links
	   $("a[ajax=true]").each(function(){$(this).transformAjaxLink()});
	   //Info modal panels
	   $(".infoService").initServiecInfoPopup();
	   
	}
	
	
	
	/**
	 * Ajax Comand link submition
	 */
	$.fn.transformAjaxLink = function(){
		$(this).click(function(event){
		   event.stopImmediatePropagation();	
		   onComplite = $(this).attr("onComplite");	
		   onBeforeSubmit = $(this).attr("onBeforeSubmit");
		   href = $(this).attr("href");
		   
		   reRenderList = $(this).attr("reRender");
           if(reRenderList && reRenderList!="")
           	  reRenderList = reRenderList.split(','); 
           
		   if(onBeforeSubmit && onBeforeSubmit!='')
			   eval("href+=" + onBeforeSubmit);
		   $.get(href,function(data, textStatus, jqXHR){
			   if(reRenderList && reRenderList.length > 0)
		       {
		    	   tmp = $("<div>").append(data.replace(rscript, ""));
		    	   for(var index = 0; index < reRenderList.length; index ++)
		    	   {
		    		   $(reRenderList[index].trim()).html(tmp.find(reRenderList[index].trim()).html());
		    		   //TODO:Add event attachment
		    	   }
		       } 
			   
			  if(onComplite && onComplite!='')
		         eval(onComplite +"(data,textStatus,jqXHR);");
		     
		  });
		  return false;
		})
	}
	
	/**
	 * Ajax Form submition
	 * 
	 * reRender Form attribute may contains class or id or any CSS selector
	 * onComplite Form attribute may contains reference to JS function
	 */
	$.fn.attachSubmitLogic = function(){
		
		
		$(".action",$(this)).click(function(event){
			event.stopImmediatePropagation();
			ajaxForm = $(this).parents("form[ajax=true]:eq(0)")
			if(typeof $(this).attr('eventId') !== 'undefined' && $(this).attr('eventId')  !== false)
			   $(this).parents("form[ajax=true]:eq(0)").find("input[name=_eventId]").val($(this).attr('eventId'));
			if(typeof $(this).attr('beforeSubmit') !== 'undefined' && $(this).attr('beforeSubmit')  !== false)
				eval($(this).attr('beforeSubmit')+"(ajaxForm)");
			
			$(ajaxForm).submit();
			return false;
		});
		
		$(this).submit(function(event){
			url = $(this).attr("action");
			container = $(this).attr("container");
			reRenderList = $(this).attr("reRenderList");
			unbind = $(this).attr("unbind");
            if(reRenderList && reRenderList!="")
            	reRenderList = reRenderList.split(','); 
			onComplite = $(this).attr("onComplite");
			status = $(this).attr("status");
			if((status && status!="") || $.browser.msie)
			{
				$(container).empty();
				$(container).append("<div class='loading_p'></div>");
			}
			
			selectorPath = $(this).attr("selectorPath");
			$.post(url, $(this).serialize()
					,function(data,textStatus,xhr){
				      if((status && status!="") || $.browser.msie )
				         $('.loading_p',$(container)).remove();
				       tmp = $("<div>").append(data.replace(rscript, ""));
				       if(selectorPath)
				       {
				    	   $((unbind?"":container) + selectorPath,tmp).each(function(){
				    		   $(container).append($(this));  
				    	   }) 
				       }
				       if(reRenderList && reRenderList.length > 0)
				       {
				    	   for(var index = 0; index < reRenderList.length; index ++)
				    	   {
				    		   $(reRenderList[index].trim()).html(tmp.find(reRenderList[index].trim()).html());
				    		   $("form[ajax=true]",$(reRenderList[index].trim())).attachSubmitLogic();
				    	   }
				       }
				       if(onComplite && onComplite!='')
				       {
				         eval(onComplite +"(data,textStatus,xhr);");
				       }
				     //TODO:Add event attachment
				     }
			);
			event.stopImmediatePropagation();
			
			return false;
		});
		
	};
	
	
	
})(jQuery);
