﻿/**
 * Copyright (c) 2009, Omnia FZ LLC
 * All rights reserved.
 * 
 * @author Subin Kurian, subin.kurian@omnia.ae
 * @version 0.1.x
 *  Javascript library
 */
	
	/* Index
	
	No     Function                                                                                          Purpose
	====================================================================================================================================================================================================
	1        AssignCSSSelectors()                                                                  This function dynamically attaches FirstChild,LastChild  css classes to elements in IE 6. 
	2       AssignLinks()							                                                                This function will attach "target='_blank' to all links which has "rel='external' tag. Fix to aviod w3c validation error for target "_blank"
	3       search()                                                                                       This function shows/hides caption texts in a textbox, used for Search, Newsletter etc. call it as  $("#SearchText").search();  #SearchText =  id of the textbox
	4       InitializeMenu(ParentId)                                                              Initialize Drop down navigation , Accepts Parent id of the Navigation list. 
	5       OnUpdating(ElementID),OnUpdated(ElementId)                         Displaying loading animation for a process. Just to call it with the client if of the div where you want to show the loading animation, (Requires Jquery Block UI plugin)
	6       Rollout(Image), Rollover(Image)																			 Changes Image on hover, Just to give hover effect to image links
	7       Scroll()																																			Scroll the content up/down on keyboard shotcuts, Needs Scroll,Shortcut jquery plugins
	8       FileUpload()                                                                                     A flash based file upload function, requires its handlers, swf files, aspx files.
	9       Accordion ()                                                                                    *Need to find a best accordion script and create a function *
	10  	 NumericFilter ()                                                                              This function doesn't allow user to fill alphanumeric charecters in a textbox.	
	11     AjaxRequest(TargetURL,TargetDivId)                                          This is a generic ajax call function which gets the data as html format and appened to the target div
	12     CreateCookie(Name,Value,Days), ReadCookie(Name),                Cookie Functions, Creates, reads and delete cookies
	         EraseCookie(Name)
   13    SendToFriendPopup(),AddRecipient(),ClosePopup()                    These functions are used to create send to friend popup 
	14    AjxSendToFriend()                                                                           Posting send to friend data for processing. Ajax call function
	*/
	
// <summary>
// Global function calls,
// </summary>
var AppPath="/";
function ExecuteHandler(){
 if (window.location.href.toLowerCase().indexOf("cmspagemode=edit")>0){  // exiting if in the sitefinity edit mode
  return false;
 }
 $(document).ready(function(){
	 AssignCSSSelectors();
	 AssignLinks();
  InitializeMenu("Navigation");
		$(".SearchText").search();
		FixFonts();
		FixLayouts();
		//OnUpdating("FormContainer");
  ToggleImageOnHover();
 });
}

// <summary>
//  This function to attach non-ie css selectors to the html elements
// </summary>
function AssignCSSSelectors()
{
if(jQuery.browser.msie){
 $("li:first-child").addClass("FirstChild");
 $("li:last-child").addClass("LastChild");
 $("td:last").addClass("LastChild");
 $("tr:first").addClass("FirstChild");
}
}

// <summary>
//  These functions handle events generated by an Input Text box
// </summary>
$.fn.search = function() {
	return this.focus(function() {
		if( this.value == this.defaultValue ) {
			this.value = "";
		}
	}).blur(function() {
		if( !this.value.length ) {
			this.value = this.defaultValue;
		}
	});	
};


// <summary>
//  This function to assign target blank to the external link. html target blank is not a standard w3c validated code. insted of using target="_blank" we use rel="external" and replace the rel with javascript.
// </summary>
function AssignLinks() 
{
 $("a[rel='external']").attr("target","_blank");
 $("a[href='#']").click(function(){
  return false;
 });
}
// <summary>
//  Setting the dropdown Navigation
// </summary>

function InitializeMenu(ParentId){
	$("#"+ParentId +" li").hover(
		function(){ 
		 $(this).addClass("Active");
			if (!$(this).hasClass("Highlight")){
				
				if ($(this).find("img").length>0){ //if the navigation is image links
				 ImgSrc = $(this).find("img").attr("src").replace(".gif","Active.gif");
				 $(this).find("img").attr("src",ImgSrc);
				}
		}
		if ($(this).children("ul").length > 0 ){
			$("ul", this).fadeIn("fast");  
		}
		if (Language =="en"){
			$("#Navigation").children().each(function(){
	   Cufon.replace($(this).find("a:first"),{hover: true});
	  });
		}
		//$("#NavShadow").animate({left: LeftPos},{queue:false,duration:700,easing: "easeInQuart"});
	},
	function(){
	 $(this).removeClass("Active");
		if (!$(this).hasClass("Highlight")){
			
			if ($(this).find("img").length>0){ //if the navigation is image links
 			ImgSrc = $(this).find("img").attr("src").replace("Active.gif",".gif");
	 		$(this).find("img").attr("src",ImgSrc);
			}
		}
	});
}
 
	
// <summary>
//  Update panel loading animation functions
// </summary>
function OnUpdating(elementId){
	$.extend($.blockUI.defaults.overlayCSS, { backgroundColor: '#ffffff' });
 $('.' + elementId).block('<img src="/Images/Generic/Bigrotation.gif" border="0" />',{ background: 'transparent', border: '0' });
}
	
function OnUpdated(elementId){
 $('.' + elementId).unblock();
}

var Language = "en";
function FixFonts(){
 if (window.location.href.toLowerCase().indexOf("/ar/")>0){
	Language ="ar";
	return false;
	
	} 
	
	$("#Navigation").children().each(function(){
		Cufon.replace($(this).find("a:first"),{hover: true});
	});
	Cufon.replace('.Synopsis h2,p.heading1,.heading,div.Image1 .heading,h6,h5,ul.font_1 li a',{hover: true});
	Cufon.replace('#Copy h2',{hover: true});
	//Cufon.replace('#font_1 li span',{hover: true});	
}

// <summary>
//  Rollover and rollout effects on  gif images, need to crop images as "*.gif", *Active.gif" 
// </summary>

function Rollover(ImageObject){
	try{
		var RolloverImage = ImageObject.src;
		RolloverImage = RolloverImage.replace(".gif","Active.gif")
		ImageObject.src = RolloverImage;
	}
	catch (ExceptionObject){
	}
}

function Rollout(ImageObject){
	try{
		var RolloutImage = ImageObject.src;
		RolloutImage = RolloutImage.replace("Active.gif",".gif")
 	ImageObject.src = RolloutImage;
	}
	catch (ExceptionObject){
	}
}


// <summary>
//  Scroll the page by using up/down arrows
// </summary>
function Scroll() {
 var start = 0;
	shortcut.add("down",function() {
	$.scrollTo( '+=300px', 200 );
	 return false;
 });
 
	shortcut.add("up",function() {
 	$.scrollTo( '-=300px', 200 );
	 return false;
	});
}

// <summary>
// Numeric field filter functions
// </summary>
function NumericFilter(event){
	var keycode;
	if (document.all){
		keycode=event.keyCode;
	}
	else{
		keycode=event.which;
	}
	if((keycode==8) || (keycode==127) || (keycode==9)  || (keycode==0)){
		return(true);
	}
	if ( ((keycode>47)&&(keycode<58)) ){
		return(true);
	}
	else{
		return(false);
	}
}


	// Generic Ajax request by passing a class name of the target div
function AjaxRequest(TargetURL,TargetDivId){
	onUpdating(TargetDiv);
	$.ajax({
		type: "GET",
		url: TargetURL,
		dataType: 'html',
		success: function(htmlResponse) { 
			$("#" + TargetDiv).html(htmlResponse);
			onUpdatedHomeWidget(TargetDiv,TargetDivType);
		},
		timeout: 20000,
		error: function(request,error) 
		{
			$(TargetDivType + TargetDiv).html("<p class='Message'>Sorry, there was a problem while loading the data. Please try again.</p>");
			onUpdatedHomeWidget(TargetDiv,TargetDivType);
		}
	}); 
}

/*Cookie functions */
function CreateCookie(Name,Value,Days) {
	if (Days) {
		var sDate = new Date();
		sDate.setTime(sDate.getTime()+(Days*24*60*60*1000));
		var Expires = "; expires="+sDate.toGMTString();
	}
	else var Expires = "";
	document.cookie = Name+"="+Value+Expires+"; path=/";
}

function ReadCookie(Name) {
	var NameEQ = Name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(NameEQ) == 0) return c.substring(NameEQ.length,c.length);
	}
	return null;
}

function EraseCookie(Name) {
	CreateCookie(Name,"",-1);
}

//<Summary>
//Send  Current URL to a friend function
//</summary>
function SendToFriendPopup(){
try{
  var SendVideoHtml = '<div id="SendToFriendFields"><div id="ClosePopupCont"><a href="#" id="ClosePopup" onclick="ClosePopup();return false;">Close X </a></div><p></p><div class="Error" style="display: none;"></div><table cellpadding="0" cellspacing="0" border="0" class="SenderList">'+
   '<tr>'+
    '<th>Sender Name<em>*</em></th><td><input type="text" id="sender_name" name="sender_name" value="" /></td>' +
    '<th>Sender Email<em>*</em></th><td><input type="text" id="sender_email" name="sender_email" value="" /></td>'+
   '</tr>'+
   '<tr class="Recipient">'+
    '<th>Recipient Name<em>*</em></th><td><input type="text" class="recipient_name" id="recipient_name" value="" /></td>'+
    '<th>Recipient Email<em>*</em></th><td><input type="text" class="recipient_email" id="recipient_email" value="" /></td>'+
   '</tr>'+
  '</table>'+
  '<p class="Add" onclick="AddRecipient()"> + Add Recipient </p>'+
  '<div class="ActionPane">'+
   '<a href="#" onclick="AjxSendToFriend();return false;">Send to friend</a>'+
  '</div></div>'; //Markup for the UI
   $("#Friend").parent().append(SendVideoHtml);  //appending markup to the body
   $("#SendToFriendFields").slideDown(500); //Shows the form
  }
  catch(obj){}
}

//Add more recipient to the list
function AddRecipient(){
 var ReceipientHTML =  "<tr class=\"Recipient\">" + 
  "<th>Recipient Name</th><td><input type=\"text\"  class=\"recipient_name\" value=\"\" /></td>"+
  "<th>Recipient Email</th><td><input type=\"text\"  class=\"recipient_email\" value=\"\" /><a id='RemoveRow' onclick='$(this).parent().parent().remove();return false' href=\"#\" class=\"close\">X</a></td>" + 
 "</tr>";
  $(".SenderList").append(ReceipientHTML);
}

//Closing the send to friend popup
function ClosePopup(){
 $("#SendToFriendFields").slideUp(500);
}

// Send to friend ajax post
function AjxSendToFriend(){
 var isValidForm = true;
 var user = {};
 user.Name = $("#sender_name").val();
 user.Email = $("#sender_email").val();
 if (user.Name == ""){
  //alert("Please fill in your Name");
  isValidForm = false;
   $("#sender_name").addClass("InputError");
 }
 if (user.Email == ""){
  //alert("Please fill in your Email");
  $("#sender_email").addClass("InputError");
  isValidForm = false;
 }
 if (!CheckMail(user.Email)){
  //alert("Please fill in a Valid Email");
  $("#sender_email").addClass("InputError");
  isValidForm = false;
 }
 
 if (!isValidForm) {
  $("#SendToFriendFields .Error").show();
  $("#SendToFriendFields .Error").html("<p>Please fill in all fields marked with an asterisk(*)</p>");
  return false;
 }
  
 $("tr.Recipient").each(function(){
  if ($(this).find(".recipient_name").val() == ""){
   //alert("Please fill in Recipient Name");
   $(this).find(".recipient_name").addClass("InputError");
   isValidForm = false;
  }
  if ($(this).find(".recipient_email").val() == ""){
   //alert("Please fill in Recipient Email");
   $(this).find(".recipient_email").addClass("InputError");
   isValidForm = false;
  }
  
  if (!CheckMail($(this).find(".recipient_email").val())){
   //alert("Please fill in Valid Recipient Email");
   isValidForm = false;
   $(this).find(".recipient_email").addClass("InputError");
  }
 });
 
 // Here we need to allow multiple recipients, at the moment we only use one
 var recipients = [];
 
 $("tr.Recipient").each(function(){
	 recipients.push({ Name: $(this).find(".recipient_name").val(), Email: $(this).find(".recipient_email").val() });
 });
	
 //alert(recipients); 
 var URL_ = '&user='+ user.Name+'&useremail='+ user.Email +'&recipient='+$.toJSON(recipients)+'&personalnote='+ window.location.href;
	 $.extend($.blockUI.defaults.overlayCSS, { backgroundColor: '#111111' });
	 $('#SendToFriendFields').block('<img src="/Images/Generic/Bigrotation.gif" border="0" style="margin:auto;" />',{ background: 'transparent', border: '0' });
 //alert(URL);
 $.ajax({
  type: "get",
  url: URL_,
  success: function(msg){
	 $("#SendToFriendFields").hide();
	 $("#SendToFriendFields table,#SendToFriendFields .ActionPane,#SendToFriendFields .Add").hide();
  $("#SendToFriendFields .Error").hide();
	 $("#SendToFriendFields").css("border","3px solid #117d8a").fadeIn("slow");
  $("#SendToFriendFields p").html("Thank you! the link has been sent successfully.");   
		$('#SendToFriendFields').unblock();
 }
});
}

function FixLayouts(){
 if ( $("#Column2Inner").height()<	$("#Column1").height() ){
	 $("#Column2Inner").height($("#Column1").height()-165);
	}
	if (window.location.href.toLowerCase().indexOf("home")<0){
  if ( $("#Column2Inner").height()<	$("#Column1").height() ){
	  $("#Column2Inner").height($("#Column1").height());
 	}
	
	}
}


function ToggleImageOnHover()
{
	$(".InlineTabs img").hover(function(){
 if ($(this).hasClass("HighlightSection")) return false;
  var NewImage = $(this).attr("src").replace(".gif","Hover.gif");
  $(this).attr("src",NewImage);
 },function(){
  if ($(this).hasClass("HighlightSection")) return false;
  var NewImage = $(this).attr("src").replace("Hover.gif",".gif");
  $(this).attr("src",NewImage);
 });
}

function SwitchLanguage(){
var CurrentURL = window.location.href.toLowerCase();
$("#Switch").click(function(){
var CurrentURL=CurrentURL.replace("en","ar");
alert(CurrentURL);

});
}

function SetLightbox(){
 $('.UaeImages li a').lightBox();
}

function ShowMapLocation(addressType) {
  var InvestADAddress0;
  var InvestADAddress1;
  if (window.location.href.toLowerCase().indexOf("ar/contact/contactinfo.aspx")>0){ 
   InvestADAddress0 = "<div class='Wrap1'><p style='color:#999999;'><strong>أبوظبي الاستثماري- المركز الرئيسي</strong><br />مبنى بنك أبو ظبي الوطني <br /> الخالدية، شارع طارق بن زياد <br />ص.ب. 46309، أبو ظبي، الإمارات العربية المتحدة</p></div>";
   InvestADAddress1 = "<p style='color:#999999;'><strong>أبوظبي الاستثماري-مكتب إدارة الاستثمار</strong><br />أبراج البطين<br />الطابق الخامس مبنى C2<br />البطين<br />أبوظبي- دولة الإمارات العربية المتحدة</p>";
  }
  else{
   InvestADAddress0 = "<div class='Wrap1'><p style='color:#999999;'><strong>Invest AD - Main Office</strong><br />National Bank of Abu Dhabi Building<br />Khalidiya, Tariq Bin Ziad Street,<br />Abu Dhabi, United Arab Emirates</p></div>";
   InvestADAddress1 = "<p style='color:#999999;'><strong>Invest AD - Investment Management <br />Office</strong><br />Floor 5 - Building C2<br />Al Bateen Towers, Al Bateen<br />Abu Dhabi, United Arab Emirates</p>";
  }

  //var point = new GLatLng(24.478751,54.351683);
  
     var point = new GLatLng(addressType == 0 ? 24.478751 : 24.45466 , addressType == 0 ? 54.351683: 54.338679 );
     //var map = new GMap2(document.getElementById("GoogleMap"));
     googleLocationMap.openInfoWindow(point, ((addressType == 0) ? InvestADAddress0 : InvestADAddress1));
  }

  var googleLocationMap;
  
function initiateGoogleMaps() {
    if (GBrowserIsCompatible()) {
      googleLocationMap = new GMap2(document.getElementById("GoogleMap"));
      googleLocationMap.setCenter(new GLatLng(24.469221,54.345589), 13);
      //googleLocationMap.setMapType(G_SATELLITE_MAP);


      //marker      
      var point = new GLatLng(24.478751,54.351683);
      var InvestADLocation = new GMarker(point);
      googleLocationMap.addOverlay(InvestADLocation);
      //info window
     if (window.location.href.toLowerCase().indexOf("ar/contact/contactinfo.aspx")>0){ 
       var InvestADAddress1 ="<div class='Wrap1'><p style='color:#999999;'><strong>أبوظبي الاستثماري- المركز الرئيسي</strong><br />مبنى بنك أبو ظبي الوطني <br /> الخالدية، شارع طارق بن زياد <br />ص.ب. 46309، أبو ظبي، الإمارات العربية المتحدة</p></div>";
       }
       else{
      var InvestADAddress1 = "<div class='Wrap1'><p style='color:#999999;'><strong>Invest AD - Main Office</strong><br />National Bank of Abu Dhabi Building<br />Khalidiya, Tariq Bin Ziad Street,<br />Abu Dhabi, United Arab Emirates</p></div>";
      }
     // googleLocationMap.openInfoWindow(point, InvestADAddress1);
      
      
      
            // event
      GEvent.addListener(InvestADLocation, "click",
      function() {

        googleLocationMap.openInfoWindow(point, InvestADAddress1);

      });
      
      
      
      var point2 = new GLatLng(24.45466,54.338679);
      var InvestADLocation2 = new GMarker(point2);
      googleLocationMap.addOverlay(InvestADLocation2);
      //info window
       if (window.location.href.toLowerCase().indexOf("ar/contact/contactinfo.aspx")>0){ 
       var InvestADAddress2 = "<p style='color:#999999;'><strong>أبوظبي الاستثماري-مكتب إدارة الاستثمار</strong><br />أبراج البطين<br />الطابق الخامس مبنى C2<br />البطين<br />أبوظبي- دولة الإمارات العربية المتحدة</p>";
       }
       else{
      var InvestADAddress2 = "<p style='color:#999999;'><strong>Invest AD - Investment Management <br />Office</strong><br />Floor 5 - Building C2<br />Al Bateen Towers, Al Bateen<br />Abu Dhabi, United Arab Emirates</p>";
      }
      //googleLocationMap.openInfoWindow(point2, InvestADAddress2);

      
      // event
      GEvent.addListener(InvestADLocation2, "click",
      function() {

        googleLocationMap.openInfoWindow(point2, InvestADAddress2);

      });

      //zoom & mape type
      googleLocationMap.addControl(new GSmallMapControl());
      googleLocationMap.addControl(new GMapTypeControl());
    }
  }
  
  
  function AdOverlay(){
   var PageHeight =  $(document).height();
 if (window.location.href.toLowerCase().indexOf("/ar/")>0){
  var BackgroundOverlay='<div class="Overlay" style="height:'+ PageHeight +'px" ><table cellpadding="0" cellspacing="0" height="100%" width="100%"><tr><td width="100%" height="100%" align="center" valign="middle"><img src="/Images/Background/Ramadan_Ar.jpg?dsbds" alt="" height="652" width="1004" /></td></tr></table></div>';
 }
 else{
	  var BackgroundOverlay='<div class="Overlay" style="height:'+ PageHeight +'px" ><table cellpadding="0" cellspacing="0" height="100%" width="100%"><tr><td width="100%" height="100%" align="center" valign="middle"><img src="/Images/Background/Ramadan_En.jpg?asjkdb" alt="" height="652" width="1004" /></td></tr></table></div>';
   }
	  if (ReadCookie("RamadanMsg")=="true"){
	   return false;
	  }
	  $("#Wrap1").hide();
	  $("body").append(BackgroundOverlay);
	  setTimeout ( "FadeOutOverlay()", 5000 );	  
  }
  
  function FadeOutOverlay(){
   CreateCookie("RamadanMsg","true",50);
   $(".Overlay").animate({opacity: 0},{queue:false,duration:2000,complete:function(){
	    $("#Wrap1").show();
	    $(".Overlay").remove();
    }});   
  }