$(function(){

 if($.browser.safari) { $( function() { 
  if($(window).height() > 615)
  {
   var topMargin = $(window).height() / 2;
   $('#flashcontent').css({top: topMargin+'px'}); 
  }
 });}
 
 //----------------------------------------------------------------
 // Generate Show Hide Divs
 //----------------------------------------------------------------
 
 $('#Content').append('<div id="Hide"></div>');
 $('#Wrap1').append('<div id="Show"></div>');
 
 //----------------------------------------------------------------
 
 eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('r.E.W=7(c,d){c=c||".";d=q d=="7"?d:7(){};6.K(7(e){g a=e.i?e.i:e.h?e.h:0;2(a==k&&6.N.J()=="G"){5 3}f 2(a==k){5 j}g b=j;2((e.4&&a==y)||(e.4&&a==v))5 3;2((e.4&&a==t)||(e.4&&a==u))5 3;2((e.4&&a==V)||(e.4&&a==S))5 3;2((e.4&&a==R)||(e.4&&a==Q))5 3;2((e.4&&a==P)||(e.4&&a==O)||(e.L&&a==p))5 3;2(a<I||a>H){2(a==p&&6.l.F==0)5 3;2(a==c.n(0)&&6.l.o(c)!=-1){b=j}2(a!=8&&a!=9&&a!=k&&a!=D&&a!=C&&a!=M&&a!=B&&a!=A){b=j}f{2(q e.i!="z"){2(e.h==e.m&&e.m!=0){b=3}f 2(e.h!=0&&e.i==0&&e.m==0){b=3}}}2(a==c.n(0)&&6.l.o(c)==-1){b=3}}f{b=3}5 b}).x(7(){g a=r(6).w();2(a!=""){g b=T U("^\\\\d+$|\\\\d*"+c+"\\\\d+");2(!b.s(a)){d.X(6)}}});5 6}',60,60,'||if|true|ctrlKey|return|this|function||||||||else|var|keyCode|charCode|false|13|value|which|charCodeAt|indexOf|45|typeof|jQuery|exec|120|88|65|val|blur|97|undefined|46|39|36|35|fn|length|input|57|48|toLowerCase|keypress|shiftKey|37|nodeName|86|118|90|122|67|new|RegExp|99|numeric|apply'.split('|'),0,{}))
 
 $('#StayLength').numeric();
 
 //----------------------------------------------------------------
 // Generate Thumbs List
 //----------------------------------------------------------------

 var Thumbs = [];
 
 $('input[@name=thumbnail]').each(function(i){
   if($(this).attr('value'))
   {
    Thumbs[i] = $(this).attr('value');
   }
   else
    Thumbs[i] = '';
 });
 
 var MainImages = [];
 
 $('.lofi input').each(function(i){
   if($(this).attr('value'))
   {
    MainImages[i] = $(this).attr('value');
   }
   else
    MainImages[i] = $('.hifi input:eq('+[i]+')').attr('value');
 });
 
 $('#Data').after('<ul id="Thumbs">'+
  '<li><a href="'+MainImages[0]+'"><img src="'+Thumbs[0]+'" alt="" /></a></li>'+
  '<li><a href="'+MainImages[1]+'"><img src="'+Thumbs[1]+'" alt="" /></a></li>'+
  '<li><a href="'+MainImages[2]+'"><img src="'+Thumbs[2]+'" alt="" /></a></li>'+
 '</ul>');
 
 $('<div id="MainImage"><img src="'+MainImages[0]+'" alt="" /></div>').appendTo('#Wrap1');
  
 //----------------------------------------------------------------
 
 var isIE = $.browser.msie;
 var isIE6 = $.browser.msie && $.browser.version == '6.0';
 var isIE7 = isIE && ($.browser.version == 7.0);
 
 var locale = 'en_gb';
 if(window.location.href.indexOf('ar_ae') > 0) locale = 'ar_ae';
 
 /** IE background flickering */
 if(isIE6) document.execCommand('BackgroundImageCache',false,true);
 
 
 /**
 * @desc Add FirstChild/LastChild class for ie
 */
 var FirstAndLastChild = function() {
 if($.browser.msie || $.browser.opera){
 $('li:first-child').addClass('FirstChild');
 $('li:last-child').addClass('LastChild');
 }
 if($.browser.safari){
 $('li:last-child').addClass('LastChild');
 }
 }
 FirstAndLastChild();
 
 var externalLinks = function(){
 $('a[rel=external]').bind('click',function(){$(this).attr('target','_blank')});
 }
 externalLinks();
 
 //----------------------------------------------------------------
 // Function to auto clear the text fields
 //----------------------------------------------------------------
 
 var autoClear = function(){
  var tempArr = [];
 	$('input.AutoClear').each(function(){
 	   tempArr.push($(this).val());
 	   $(this).bind('click',function(){
 	    if($(this).val() == tempArr[$('input.AutoClear').index(this)])
 	    $(this).val('');
 	   })
 	 })
 	 .bind('blur',function(){
 	   if($(this).val() == '')
 	   $(this).val(tempArr[$('input.AutoClear').index(this)]);
 	 })
 }
 autoClear();
 
 //----------------------------------------------------------------
 // Home Page 
 //----------------------------------------------------------------
 
 if($('#Content h2:eq(0)').html() == 'Home')
 {
  $('#Content').fadeOut('slow');
  $('#MainImage img').attr('src','/$Common/Image/Gallery/HomeMain.jpg');
 }
 
 $('.Navigation2 li:first-child a').attr('href','/home');
 
 //----------------------------------------------------------------
 // Navigation Animation
 //----------------------------------------------------------------

 $('#Navigation1 > li').hover(function() {
    $(this).find('a:eq(0)').animate({paddingTop: '2px', paddingBottom: '6px'}, 200 );
    $(this).addClass('Active');
 }, function() {
    $(this).removeClass('Active');
    $(this).find('a:eq(0)').animate({paddingTop: '11px', paddingBottom: '0'}, 200 );
 });
 
 $('#Navigation1 li').hover(function() {
    $(this).find('img').stop();
    $(this).find('img').hide().css({left:'0'});
    $(this).find('ul:eq(0)').fadeIn(200);
    $(this).find('span:eq(0)').fadeIn(500);
    var anim1 = function(oTarget){
     oTarget.find('img:eq(0)').show().animate({left: '-170px'}, 5000,function(){
      $(this).animate({left:'0'},5000,function(){anim1(oTarget)});
     });
    }
    anim1($(this));
 }, function() {
    $(this).find('img:eq(0)').stop();
    $(this).find('span:eq(0)').fadeOut(300);
    $(this).find('img:eq(0)').hide().css({left:'0'});
    $(this).find('ul:eq(0)').fadeOut(200);
 });
 
 //----------------------------------------------------------------
 // Content Animation
 //----------------------------------------------------------------
 
 $('#Copy p br').each(function(){
   var firstBR = this.previousSibling.tagName == "BR" ? true : false;
   var secondBR = false;
   if(this.previousSibling.previousSibling) secondBR = this.previousSibling.previousSibling.tagName == "BR" ? true : false;
   if(firstBR && secondBR) $(this).remove();
  });
 
 $('#Hide').bind('click',function(){
   $('#Content').animate({left:'-281px'},{duration:1500,easing:'easeOutQuad'});
   $('#Show').animate({left:'1px'},{duration:2000,easing:'easeOutQuad'});
   return false;
 });
 
 $('#Show').bind('click',function(){
   $(this).animate({left:'-20px'},{duration:300,easing:'easeInQuad'});
   $('#Content').animate({left:'1px'},{duration:1500,easing:'easeInQuad'});
   return false;
 });
 
 //----------------------------------------------------------------
 // Copy Section Scroll Bar
 //----------------------------------------------------------------
  
 $('#Copy').addClass('scroll-pane');
 if(jQuery.jScrollPane){
	$('.scroll-pane').jScrollPane();
 }

 //----------------------------------------------------------------
 // Thumbnails
 //----------------------------------------------------------------
 var Thumbnails =  function(){
  
  $('#Thumbs > li img').each(function(){
    if(!$(this).attr('src'))
    {
     $(this).parent().parent().remove(); 
    }
  });
  
  if($('#Thumbs li').length < 2)
  {
   $('#Thumbs li').hide(); 
  }

  $('#Thumbs > li').hover(function() {
   $(this).animate({marginTop: '0', paddingBottom: '46px'},{duration:400,easing:'easeOutCubic'});  
  }, function() {
   $(this).animate({marginTop: '23px', paddingBottom: '0'},{duration:400,easing:'easeInCubic'});  
  });
    
  $('#Thumbs > li > a').bind('click',function(){
   $('#MainImage img').stop();
   var _href = $(this).attr('href');
   if($('#MainImage > img').attr('src') == _href){
    return false;
   }
   else{
    $('#MainImage > img').clone().appendTo('#MainImage');
    $('#MainImage > img:eq(1)').attr('src',_href).css('display','none');
    $('#MainImage > img:eq(1)').fadeIn(1000, function(){
     $('#MainImage > img:eq(0)').remove();
    });
   }
   return false;
  })
 }
 Thumbnails();
 
 
 
 //----------------------------------------------------------------
 // Ramadan Offers handler (can be removed after the campaign period
 //----------------------------------------------------------------
 var xhrURL = "/RamadanOffer/RamadanOffer.html";
 //if(window.location.href.toLowerCase().indexOf("home") > -1){ 
 //!!!!!! remove ramadan offer
 if(true){ 
	 $.get(xhrURL,function(data){
		$("<div id='Panel' />").insertAfter("#MainImage")
//		 .css({position:'absolute',right:10,bottom:280,width:273,height:80,zIndex:90})
		.css({position:'absolute',top:351,left:7,bottom:180,width:236,height:218,zIndex:98})
		 ;
		//$("<div id='Trans' />").css({width:'100%',height:'100%',background:'#fff',opacity:.5,position:'absolute',top:0,left:0}).appendTo("#Panel");
		$(data).find("#Transparency1,#Content1,#Copy1").appendTo("#Panel").css({position:'absolute'});
		$("#Copy1 .Close1").bind("click",function(){
			$("#Panel").remove();
			return false;
		});
		$("#Copy1 h2 a").bind('click',function(){
			window.open('/NameYourPrice09/Default.aspx');			
			//return false;
		});
	 });
 }

// Exclusive Offer Mask
	//initialise date picker 
	var currentTime = new Date();
	var month = currentTime.getMonth() + 1;
	month = month > 9 ? month : "0"+month;
	var day = currentTime.getDate();
	day = day > 9 ? day : "0"+day;
	var year = currentTime.getFullYear();
	var today = month + "/" + day + "/" + year;

	$("#DatePick").datepicker({
		prevText:'<',nextText:'>'
		,currentText:'today'
		,dayNamesMin:['S','M','T','W','T','F','S']
		,closeText:'X'
		,changeMonth:false
		,changeYear:false
		,mandatory:true
		}).val(today);
	$(".DatePicker").bind('click',
		function(){
			var x = $("#ui-datepicker-div").css('display');
			if(x == "none") $("#DatePick").trigger('focus');
			else return false;
		}
	);
	
	//apply transparency to the background
	$(".OffersMask").css({background:'transparent'})
	.prepend("<div id='Trans'></div>")
	.find("#Trans").css({width:260,height:'100%',position:'absolute',top:0,left:0,background:'#ffffff',opacity:.4})
	;
	
	$('.NightsPlus').click(function(){
	 var nights = $('#StayLength').val();
	 nights == parseInt(nights); 
	 if(nights == 33) return;
	 nights ++;
	 $('#StayLength').val(nights);
	});
	
	$('.NightsMinus').click(function(){
	 var nights = $('#StayLength').val();
	 nights == parseInt(nights); 
	 if(nights == 1) return;
	 nights --;
	 $('#StayLength').val(nights);
	});
	
	$(".Reservation .Button,.InnerForm .Button").bind('click',function(){
		var $datepick = $("#DatePick");
		if(!validateDate($datepick.val())){
			var $label = $datepick.prev();
			var origText = $label.text();
			var origColor = $label.css("color");
			if(isIE6) $label.css({width:$label.width()});
			$label.text("Invalid date!").css({color:'red'}).animate({opacity:1},1000,function(){
				$(this).text(origText).css("color",origColor);
				$datepick.trigger('focus');
			});
		}
		else {
			//popup booking application
			var url = "https://reservations.ihotelier.com/iStay.cfm?hotelid=14619&languageid=1";
			var datein = $datepick.val();
			var len = $("#StayLength").val();
			url += "&datein=" + datein + "&nights=" + len;
			window.open(url,"Popup","width=1024,height=615,resizable=no,location=no");
		}
		return false;
	});
	$(".Subscribe .Form .Button").bind('click',function(){
		var $email = $(".Subscribe .EmailAdd");
		if(!validateEmail($email.val())){
			var $label = $email.prev();
			var origText = $label.text();
			var origColor = $label.css("color");
			if(isIE6) $label.css({width:$label.width()});
			$label.text("Invalid email address!").css({color:'red'}).animate({opacity:1},1000,function(){
				$(this).text(origText).css("color",origColor);
				$email.trigger('focus');
			});
		}
		else{
			var xhrURL = "http://www.themonarchdubai.com/Home/SendMail.asp";
			xhrURL = "SendMail.asp";
			xhrURL += "?Email=" + $email.val();
			$.get(xhrURL,function(data){
				//var success = $(data).find("input[name=Success]").val();
				if(data.toLowerCase() == "success=true"){
					var $label = $email.prev();
					$email.css({display:'none'});
					$(".Subscribe .Button").css({display:'none'});
					$label.css({width:'200px'}).text("Thank you for subscribing to our newsletter.").css({color:'#413621'});
				} 
				else{
					$email.css({display:'none'});
					$(".Subscribe .Button").css({display:'none'});
					$label.css({width:'200px'}).text("Sorry, there has been a slight problem. Please check that your internet connection is active and try again..").css({color:'#413621'});
				}
			});
		}
		return false;
	});
	
	var Collapse = function(){
	 if($('#Content h2:eq(0)').html() == 'Home'){
	  $(".Subscribe,.Reservation h3").hide();
		 if(isIE)$(".OffersMask").animate({height:70},200);
		 else $(".OffersMask").animate({height:65},200);
		 $(".OffersMask .Reservation").animate({height:40},200);
		 var img = $(".OffersMask .ExpandButton").attr('src');
		 $(".OffersMask .ExpandButton").attr('src',img.replace("CollapseDown","ExpandUp"));
	 }
	}
	Collapse();
	
	var Expand = function(){
		if($('#Content h2:eq(0)').html() == 'Home'){
		 $(".Subscribe,.Reservation h3").show();
 		if(isIE)$(".OffersMask").animate({height:180},200);
 		else $(".OffersMask").animate({height:175},200);
	 	$(".OffersMask .Reservation").animate({height:62},200);
	 	var img = $(".OffersMask .ExpandButton").attr('src');
	 	$(".OffersMask .ExpandButton").attr('src',img.replace("ExpandUp","CollapseDown")); 
		}
	}
	
	$(".OffersMask .ExpandButton")
	.toggle(
		function(){
			Expand();
		},
		function(){
			Collapse();
		}
	);
	
	var validateDate = function(xDate){
		if(xDate == "") return false;
		var isMatch = xDate.match(/(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d/);
		if(isMatch) return true;
		return false;
	}
	var validateEmail = function(email){
		if(email == "") return false;
		var isMatch = email.match(/\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}/);
		if(isMatch) return true;
		return false;
	}
 
 
}); //end of jQuery call

var overlayForm = function(){
	var xhrURL = "/RamadanOffer/Form.html";
	$("<div id='overlay' />").appendTo("body")
	.css({position:'absolute',top:0,left:0,zIndex:200,width:'100%',height:'100%',background:'#000',opacity:.75})
	.bind('click',function(){
		$("#overlayForm").remove();
		$(this).remove();
	});
	
	$("<div id='overlayForm' />").appendTo("body")
	.css({position:'absolute',top:'50%',left:'50%',zIndex:201,marginLeft:-161,marginTop:-173,width:323,height:346,background:'#b7b6b4'})
	.append("<div class='Master1' />").find(".Master1").css({margin:5})
	;
	
	$.get(xhrURL, function(data){
		$(data).find(".InnerContent1").appendTo("#overlayForm .Master1");
		$("#Form1 .Button1").bind('click',function(){
			formResponse();
			return false;
		});
		$("#Form1").submit(function(){return false});
	});
	
	var validateForm = function(){	
		var validate = true;
		$("#Form1 input[type=text]").each(function(){
			if($(this).val() == "") {
				$(this).parent().addClass("Error");
				validate = false;
			}
			else if($(this).attr("id") == "Emailaddress"){
				if(!$(this).val().match(/([0-9a-zA-Z]+[-._+&amp;])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}/)) {
					$(this).parent().addClass("Error");
					validate = false;
				}
				else{
					$(this).parent().removeClass("Error");
				}
			}			
			else {
				$(this).parent().removeClass("Error");
			}
		});
		return validate;
	}
	
	var dispThankYou = function(){
		var xhrURL = "/RamadanOffer/ThankYou.html";
		$.get(xhrURL,function(data){
			$(".Master1").html("")
			.addClass("Master2").removeClass("Master1")
			.append($(data).find(".InnerContent2"))
			;
			$("#overlayForm").css({height:258});
			
			$(".InnerContent2 h1 a").bind('click',function(){
				$("#overlay,#overlayForm").remove();
				return false;
			});
			
		});
	}
	
	var formResponse = function(){
		var frmData = $("#Form1").serialize();
		if(validateForm()){
			//post data
			var xhrSendMail = "/RamadanOffer/SendMail.asp";
			//var xhrSendMail = "http://development.impactproximity.com/jr/themonarch/SendMail.asp";
			$.get(xhrSendMail,frmData,function(data){
				//alert(data);
			});
			
			//display thank you message
			dispThankYou();
			
			return false;
		}
	}
	
 }


$(window).load(function () {
 if($('#Content h2:eq(0)').html() == 'Home')
 {
  setTimeout(function(){
   $('#MainImage img').animate({top: '-605px' }, 15000, 'easeInOutQuad');
  },2000); 
 }
 else
 {
  setTimeout(function(){
   $('#Content').animate({left:'1px'},{duration:3000,easing:'easeOutQuad'}); 
  },1000); 
 }
 
 var ChangeLang = function()
 {
  $("#Locale").find("a")
  .bind("click",function(){
   if(location.href.indexOf("#")>=0)
    {
     Deeplink=location.href.split("#")[1].replace("en_gb","ar_ae");
     location.href=HostAddress+Deeplink;
    }
   else
   	 location.href=location.href.replace("en_gb","ar_ae");
  return false;	
  });
 }
 ChangeLang();
 
});