$(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>');
 
 //----------------------------------------------------------------
 
 //----------------------------------------------------------------
 // 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_ar_ae.jpg');
 }
 
 $('.Navigation2 li:first-child a').attr('href','/home/Default_ar_ae.aspx');
 
 //----------------------------------------------------------------
 // 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: '7px', paddingBottom: '0'}, 200 );
 });
 
 $('#Navigation1 li').hover(function() {
    $(this).find('img').stop();
    $(this).find('img').hide().css({right:'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({right: '-170px'}, 5000,function(){
      $(this).animate({right:'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({right:'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({right:'-281px'},{duration:1500,easing:'easeOutQuad'});
   $('#Show').animate({right:'1px'},{duration:2000,easing:'easeOutQuad'});
   return false;
 });
 
 $('#Show').bind('click',function(){
   $(this).animate({right:'-20px'},{duration:300,easing:'easeInQuad'});
   $('#Content').animate({right:'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();
 
 // 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;
	}
 
 $(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({right:'1px'},{duration:3000,easing:'easeOutQuad'}); 
   },1000); 
  }
 });
 
 var ChangeLang = function()
 {
 $("#Locale li a")
 .bind("click",function(){
   if(location.href.indexOf("#")>=0)
    {
     Deeplink=location.href.split("#")[1].replace("ar_ae","en_gb");
     location.href=HostAddress+Deeplink;
    }
   else
   	 location.href=location.href.replace("ar_ae","en_gb");
  return false;	
  });
 }
 ChangeLang();
 
 if($('#Shortcuts'))
 {
  $('#Shortcuts').find('li:last-child a').attr('href','/contact/Default_ar_ae.aspx'); 
 }
 
});