﻿/**
 * 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       InputTextOnFocusHandler(), InputTextOnBlurHandler()         This function shows/hides caption texts in a textbox, used for Search, Newsletter etc. Call it onblur/onfocus event of the text box.
	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
	15  CreateBookmarkLink()
	*/
	
// <summary>
// Global function calls,
// </summary>
var lang = "en";
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();
  AutoFit();
 });
}

// <summary>
//  This function to attach non-ie css selectors to the html elements
// </summary>
function AssignCSSSelectors()
{

 $("li:first-child").addClass("FirstChild");
 $("li:last-child").addClass("LastChild");
 $("td:last").addClass("LastChild");
 $("tr:first").addClass("FirstChild");
}

// Fixing Cufon Font >


// <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() 
{
  if (window.location.href.toLowerCase().indexOf("hotelinfo")>0){  // exiting if in the sitefinity edit mode
  return false;
  }
 $("a[rel='external']").attr("target","_blank");
 $("a[href='#']").click(function(){
  return false;
 });
}
//Cufon Font replacement
function FixFonts()
{
Cufon.replace('h2', {fontFamily: 'AvantGardeMedium'});
Cufon.replace('h3', {fontFamily: 'AvantGardeMedium'});
Cufon.replace('h2.TopHead2', {fontFamily: 'AvantGardeExtraLight'});
}
// <summary>
//  Setting the dropdown Navigation
// </summary>

function InitializeMenu(ParentId){

    $("#"+ParentId +" li").hover(
        function(){ $("ul", this).fadeIn("fast"); }, 
        function() { } 
    );
    if (document.all) {
			
        $("#"+ParentId +" li").hoverClass ("Active");
    }
}

$.fn.hoverClass = function(c) {
    return this.each(function(){
        $(this).hover( 
            function() { $(this).addClass(c);  },
            function() { $(this).removeClass(c); }
        );
    });

}


//Add To favourite function
 function CreateBookmarkLink() {
  title = document.title; 
  url = this.location.href;

 if (window.sidebar) { // Mozilla Firefox Bookmark
  window.sidebar.addPanel(title, url,"");
 } else if( window.external ) { // IE Favorite
  window.external.AddFavorite( url, title); }
 else if(window.opera && window.print) { // Opera Hotlist
  return true; }
} 

// <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();
}

// <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>
//  Swf Fild upload controls, Needs its support js plugins, swf file, and aspx file to run.. UAE expo is an example for this implementation
// </summary>
var swfu;
function FileUpload(){
	swfu = new SWFUpload({
		// Backend Settings
		upload_url: "/uploader/upload.aspx?id=" + MarkerDatabaseId,
		post_params : {
			"ASPSESSID" : "<%=Session.SessionID %>"
		},
		// File Upload Settings
		file_size_limit : "2 MB",
		file_types : "*.jpg",
		file_types_description : "JPG Images",
		file_upload_limit : "0",    // Zero means unlimited

		// Event Handler Settings - these functions as defined in Handlers.js
		//  The handlers are not part of SWFUpload but are part of my website and control how
		//  my website reacts to the SWFUpload events.
		file_queue_error_handler : fileQueueError,
		file_dialog_complete_handler : fileDialogComplete,
		upload_progress_handler : uploadProgress,
		upload_error_handler : uploadError,
		upload_success_handler : uploadSuccess,
		upload_complete_handler : uploadComplete,

		// Button settings
		button_image_url : "images/XPButtonNoText_160x22.png",
		button_placeholder_id : "spanButtonPlaceholder",
		button_width: 160,
		button_height: 22,
		button_text : '<span class="button">Select Images <span class="buttonSmall">(2 MB Max)</span></span>',
		button_text_style : '.button { font-family: Helvetica, Arial, sans-serif; font-size: 14pt; } .buttonSmall { font-size: 10pt; }',
		button_text_top_padding: 1,
		button_text_left_padding: 5,

		// Flash Settings
		flash_url : "/uploader/swfupload.swf",	// Relative to this file

		custom_settings : {
			upload_target : "divFileProgressContainer"
		},

		// Debug Settings
		debug: 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 Date = new Date();
		 Date.setTime(Date.getTime()+(days*24*60*60*1000));
		 var Expires = "; expires="+Date.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();
}
});
}

//To optimising 1024 screen
function AutoFit()
{
	if ($(window).width()<1100)
	{
 $("html").css({overflowX:"hidden"})
		//$("#Wrap3").css({ width:"1000px", overflow:"hidden"})
		//$("#Wrap4").css({ width:"1000px", overflow:"hidden"})
	//	$(".Wrap5").css({ width:"960px", overflow:"hidden",padding:"0px 0px 0px 40px"})
	//	$("#FooterWrap2").css({ width:"1000px"})          
 }
	if ($("#Wrap1").height()< $(window).height()){
	 var NewContentHeight =  $(window).height() - $("#Wrap1").height();
  $("#Content").height($("#Content").height() + NewContentHeight);
	}
}

function MediaSpace(){
//if ($("#s5").find("img").length<=1)
//{
//$("#output").hide();
//}
$('#s5').cycle({
    fx:     'fade',
    timeout: 4000,
    before:  onBefore,
    after:   onAfter,
    next:   '#next2',
    prev:   '#prev2'
      });
}

function onBefore() {
    //$('#output').html("Scrolling image:<br />" + this.src);
   //window.console.log(  $(this).parent().children().index(this) );
   // $('#output').fadeOut(500); 
}
function onAfter(){
//if (this.alt !="" ){
//alert('boo');
    //$('#output').html('<h5>' + this.alt + '</h5>');
   // $('#output').fadeIn(500); 
   // }
   var n = $(".MediaRight img").length;
     var index = $(".MediaRight img").index(this);
     var count=index+1;
      $(".nav span").html("Image"+count+"/"+n);
      if (window.location.href.toLowerCase().indexOf("/ar/")>0){
    	 $(".nav span").html("صورة"+count+"/"+n);
      }
      
      

     
  //alert(index);
}

// <summary>
//  setting the google map functionalities for branch network
// </summary>

// <summary>
//  setting the google map functionalities for branch network
// </summary>
function googleMapInitialize(strContact)
{
 if (window.location.href.toLowerCase().indexOf("cmspagemode=edit")>0){
 return false;
 }
 if (GBrowserIsCompatible()) {
  //$("#GoogleMap").css({display: "block"});
  var map = new GMap2(document.getElementById("GoogleMap"));
  var point;
  if (strContact =="RakCam")
    {
    
  map.setCenter(new GLatLng(25.79,55.950623 ), 12);
  point = new GLatLng(25.79,55.950623);
    
	var raktext =(window.location.href.toLowerCase().indexOf("/en/")> 0 ? "<div class='GooglemapLogo'><p><strong>RAK CAM</strong> <br /></p></div>" : "<div class='GooglemapLogo'><p><strong>مركز أبحاث رأس الخيمة</strong><br /></p></div>");
	map.openInfoWindow(map.getCenter(), raktext);
  //map.openInfoWindow(map.getCenter(),"<div class='GooglemapLogo'><p><strong>RAK CAM <br /></p></div>");
    }  
    var bottomRight = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(10,10));
    map.addControl(new GMapTypeControl(),bottomRight);
  map.setMapType(G_HYBRID_MAP);
  var bottomLeft = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(10,10));
  map.addControl(new GLargeMapControl3D,bottomLeft);
  map.addOverlay(new GMarker(point));

 }
}

// <summary>
//  setting the google map functionalities for branch network
// </summary>
function handleBranches()
{
 if (window.location.href.toLowerCase().indexOf("branchnetwork")<0){
 return false;
 }
 $("body").unload(GUnload());
 
 $("#Branches").children().each(function(){
 $(this).find("a").click(function(){
  $("#Branches").find("a").css({fontWeight: "normal"});
  $(this).css({fontWeight: "bold"});
  var branch = $(this).html();
  if (branch =="Deira Branch")
  {
   googleMapInitialize("deira");
  }
 });
 });
 
 $("document").ready(function(){
  $("#Branches a:first").trigger("click");
 });
}

//LightBox Function

function SetLightBox()
{
 $('.SlideShow a').lightBox();
}

