

var palm = {
	asset_prefix : "",
    init :  function () {
		palm.tools.setAssetPath();
		palm.tools.sendToFriend.init();
		window.addEvent('domready', function() {
            palm.tools.tabNav.buildTabs('navigation_tabs');
			palm.tools.homeTabs.init();
			palm.tools.externalLinks();
			palm.tools.search.attachToForm();
        });
    },
    tools : { 
		setAssetPath: function() {
			/*  Function: Switch asset path CDN/non-CDN
			 *  Version: 0.1
			 *
			 *  Description:
			 *      Sets URL prefix for static assets to use, based on the 
			 *      URL of the calling page. This switches between 
			 *      palmjumeirah.ae in the live environment and the calling page
			 *		URL otherwise.
			 *
			 *	Todo:
			 *      Replace with better method when available.
			*/
			switch(location.host){
				case "palmjumeirah.ae":
				case "www.palmjumeirah.ae":
				palm.asset_prefix = "http://serv.assets.palmjumeirah.ae/";
				break;
				default:
					palm.asset_prefix = "http://"+location.host+"/";
				break;
			}
		},
        /*  Function: Primary Navigation Tabs
         *  Version: 0.1
         *
         *  Description:
         *      Home tab navigation displays a three tiered navigation
         *      using mootools slide to animate the opening and closing
         *      of secondary level navigaion.
        
        */
        tabNav : {
            currentTab  : false,
            openedTab   : "",
            buildTabs        : function(target) {
                if (!$(target)) return false; // Error trap
                this.nav = $(target);
                this.nav.addClass('js_on');
                this.open = false;
                this.heightMax = this.nav.getStyle('height');
                this.heightMin = parseInt(this.nav.getFirst('li').getStyle('height'), 10);
                this.activeClass = 'active';
                var tabClass = 'current_tab';
                this.hideDelay = 400;
                
                this.nav.setStyle('height', palm.tools.tabNav.heightMin);
                this.level1 = this.nav.getChildren('li');
                this.level1_links = this.level1.getFirst('a');
                this.level2 = $$('li.sub_level');
                
                this.slider = new Fx.Tween(palm.tools.tabNav.nav, 'height');
                this.slider.addEvent('complete', function() {
                        if(!palm.tools.tabNav.open) {
                            palm.tools.tabNav.removeClass(palm.tools.tabNav.level1, palm.tools.tabNav.activeClass);
                            if (palm.tools.tabNav.currentTab !== false) palm.tools.tabNav.level1[palm.tools.tabNav.currentTab].addClass(tabClass);
                        }
                    });
            
                var tabHeight = 0;
                var innerTabHeight = 0;
                
                // Prevent IE 7/6 # Flash title bug
                $each(this.level1_links, function(link) {
                        link.addEvent('click', function(e) {
                            this.href = 'javascript:void(0);';
                        });
                });
                
                for (var i=0, count = this.level1.length; i < count; i++) {
                    this.level1[i].addEvent('click', function(e) {
                        //Default height of tabs collapsed
                        tabHeight = 35;
                        if (!palm.tools.tabNav.open && !palm.tools.tabNav.checkClass(palm.tools.tabNav.level1 ,palm.tools.tabNav.activeClass)) { // No tabs open
                            palm.tools.tabNav.open = true;
                            palm.tools.tabNav.removeClass(palm.tools.tabNav.level1, tabClass);
                            this.addClass(palm.tools.tabNav.activeClass);
                            tabHeight = parseInt(this.getFirst("ul").offsetHeight, 10) + 35;
                            palm.tools.tabNav.slider.pause();
                            palm.tools.tabNav.slider.start('height', tabHeight);
                        } else if (!palm.tools.tabNav.open && palm.tools.tabNav.checkClass(palm.tools.tabNav.level1 ,palm.tools.tabNav.activeClass)) {
                            palm.tools.tabNav.open = true;
                            palm.tools.tabNav.removeClass(palm.tools.tabNav.level1, palm.tools.tabNav.activeClass);
                            this.addClass(palm.tools.tabNav.activeClass);
                            tabHeight = parseInt(this.getFirst("ul").offsetHeight, 10) + 35;
                            palm.tools.tabNav.slider.pause();
                            palm.tools.tabNav.slider.start('height', tabHeight);
                        } else if (palm.tools.tabNav.open && !this.hasClass(palm.tools.tabNav.activeClass)) {
                            palm.tools.tabNav.removeClass(palm.tools.tabNav.level1, palm.tools.tabNav.activeClass);
                            this.addClass(palm.tools.tabNav.activeClass);
                            tabHeight = parseInt($(this.id).getFirst("ul").offsetHeight, 10) + 35;
                            palm.tools.tabNav.slider.pause();
                            palm.tools.tabNav.slider.start('height', tabHeight);
                        } else {
                            palm.tools.tabNav.open = false;
                            palm.tools.tabNav.slider.pause();
                            palm.tools.tabNav.slider.start('height', this.getStyle('height'));
                            this.removeClass(palm.tools.tabNav.activeClass);
                        }
                    });  
                }
                
                // Add on mouse in/out for sub level links
                $each(this.level2, function(link) {
                    link.addEvent('mouseenter', function() {
                        this.addClass(palm.tools.tabNav.activeClass);
                        //Calculate the total height of inner div to determine if expansion is necessary
                        innerTabHeight = 50;
                        $each(this.getElements("li"), function(el) {
                            
                            innerTabHeight += parseInt(el.offsetHeight, 10);
                        });
                        //Inner div is higher than outer div, so expand
                        if(innerTabHeight > tabHeight) {
                            palm.tools.tabNav.slider.pause();
                            palm.tools.tabNav.slider.start('height', innerTabHeight);
                        }
                    });
                   link.addEvent('mouseleave', function() {
                       this.removeClass(palm.tools.tabNav.activeClass);
                       //Inner div is higher than outer div, so contract
                       if(innerTabHeight > tabHeight) {
                            palm.tools.tabNav.slider.pause();
                            palm.tools.tabNav.slider.start('height', tabHeight);
                        }
                    });
                });
                // Add states based on URL
                palm.tools.tabNav.navLocation(this.nav);
                
                return true;
            },
            
            removeClass : function(target, classname) {
                $each(target, function(tabs) {
                    tabs.removeClass(classname);
                });
            },
            
            checkClass : function(target, classname) {
               for ( var i = 0, count = target.length; i < count; i++ ) {
                    if (target[i].hasClass(classname)) return true;
                }
                return false;
            },
            
            hideNav : function() {
                // Check to see if the cursor is still outside of navigation
                if(!palm.tools.tabNav.open) {
                    palm.tools.tabNav.slider.start('height', palm.tools.tabNav.heightMin);
                }
                
            },
        
            /*  Function: extractPage and navLocation
                Description:
                    Takes the current location URL, strips out the text following
                    the last back-slash, and search for that text in an Anchor
                    tag's href attribute. If a match is found a class is applied
                    to it and its parent LI tags.
                Note: 
                    * Case sensitive
                    * careful of .htaccess mod_rewrite's
            */
        
            extractPage : function(target) {
                if(!target || typeof(target) !== 'string') return false;
                var page = target.slice(target.lastIndexOf('/')+1, target.length);  
                if (page.length <= 0 ) return false;
                return page;
            },
            
            navLocation : function(target) {
               
                if (!target || !palm.tools.tabNav.extractPage(location.href)) return false;
                
                var targetUrl = palm.tools.tabNav.extractPage(location.href);
                var currentClass = 'current_page';
                var subClass = 'sub_level';
                var insideClass = 'inside_sub_level';
                var tabClass = 'current_tab';
                var links = target.getElements('a');
                var linkUrl;
                
                for ( var i = 0, count = links.length; i < count; i++ ) {
                    linkUrl = palm.tools.tabNav.extractPage(links[i].href);
                    if ( linkUrl == targetUrl ) {
                        //setupDynamicNextButtonIfPresent(links[i]);
                        links[i].addClass(currentClass);
                        $each(links[i].getParents('li'), function(li, index, object) {
                            if ( li.hasClass(subClass) ) {
                                li.removeClass(subClass);
                                li.addClass(insideClass);
                            }
                            if(index == object.length -1) {
                                li.addClass(tabClass);
                            }
                        });
                        $each(links[i].getParents('li').getChildren('a'), function(a)  {
                            a[0].addClass(currentClass);
                        });
                        break;
                    }
                    if (count-1 == i ) return false; // url not found in navigation
                }
            
                $each(target.getChildren('li'), function(li, index) {
                    if (li.hasClass(tabClass)) {
                        palm.tools.tabNav.currentTab = index;
                    }
                });
                
                return true;
            }
        
        },
		homeTabs: {
			//record the index of the current shown page;
			init: function(){
				if($('tab_1') && $('tab_2') && $('tab_3')) {
					$('tab_1').addEvent("click",function(){
						palm.tools.homeTabs.showTab(1);
					});
					$('tab_2').addEvent("click",function(){
						palm.tools.homeTabs.showTab(2);
					});
					$('tab_3').addEvent("click",function(){
						palm.tools.homeTabs.showTab(3);
					});
					$$('#tab_1 a').addEvent("click",function(){
						palm.tools.homeTabs.showTab(1);
						return false;
					});
					$$('#tab_2 a').addEvent("click",function(){
						palm.tools.homeTabs.showTab(2);
						return false;
					});
					$$('#tab_3 a').addEvent("click",function(){
						palm.tools.homeTabs.showTab(3);
						return false;
					});
				}
			},
			showTab: function(elementId){
				var objDivs = $$("#left_part div");
				var j = 1;
				for(var i=0; i<=objDivs.length-1; i++){
					if(objDivs[i].id.indexOf("page_")!=-1)
						objDivs[i].style.display = ("page_"+elementId == objDivs[i].id) ? "" : "none";
					if(objDivs[i].id.indexOf("tab_")!=-1){
						objDivs[i].style.background = ("tab_"+elementId == objDivs[i].id) ? "url(images/home/tag_"+j+".gif) no-repeat" : "url(images/home/tag_"+j+".gif) no-repeat 0 -24px";
						j++;
					}
					
				}			
			}
		},
        /*  Function: External Links
         *  Version: 0.1
         *
         *  Description:
         *      Adds target="_blank" to all links tagged with rel="external"        
        */
		externalLinks: function(){
			$$("a[rel='external']").each(function(el){
				el.set({
					"title": el.title+' [opens in a new window]',
					"target": "_blank"
				});
			});
		},
        /*  Function: Property Search functions
         *  Version: 0.1
         *
         *  Description:
         *      Various cookie-related functions for Property Search form
        */
		search: {
			/* Function to save search options to browser cookies */
			attachToForm: function(){
				if($('searchForm')){
					$('searchForm').addEvent("submit", function(){
						palm.tools.search.saveSearchCritiral(this);
						this.submit();
						return false;
					});
				}
			},
			getExpDate: function(days, hours, minutes) {
				this.expDate = new Date( );
				if (typeof days == "number" && typeof hours == "number" && 
					typeof hours == "number") {
					this.expDate.setDate(this.expDate.getDate( ) + parseInt(days));
					this.expDate.setHours(this.expDate.getHours( ) + parseInt(hours));
					this.expDate.setMinutes(this.expDate.getMinutes( ) + parseInt(minutes));
					return this.expDate.toGMTString( );
				}
			},
			getCookieVal: function(offset) {
				this.endstr = document.cookie.indexOf (";", offset);
				if (this.endstr == -1) {
					this.endstr = document.cookie.length;
				}
				return unescape(document.cookie.substring(offset, this.endstr));
			},
			getCookie: function(name) {
				this.arg = name + "=";
				this.alen = this.arg.length;
				this.clen = document.cookie.length;
				var i = 0;
				while (i < this.clen) {
					var j = i + this.alen;
					if (document.cookie.substring(i, j) == this.arg) {
						return this.getCookieVal(j);
					}
					i = document.cookie.indexOf(" ", i) + 1;
					if (i == 0) break; 
				}
				return "";
			},
			setCookie: function(name, value, expires, path, domain, secure) {
				document.cookie = name + "=" + escape (value) +
					((expires) ? "; expires=" + expires : "") +
					((path) ? "; path=" + path : "") +
					((domain) ? "; domain=" + domain : "") +
					((secure) ? "; secure" : "");
			},
			deleteCookie: function(name,path,domain) {
				if (this.getCookie(name)) {
					document.cookie = name + "=" +
						((path) ? "; path=" + path : "") +
						((domain) ? "; domain=" + domain : "") +
						"; expires=Thu, 01-Jan-70 00:00:01 GMT";
				}
			},
			saveSearchCritiral: function(theForm){
				this.setCookie("type",theForm.type.options[theForm.type.selectedIndex].value);
				this.setCookie("beds",theForm.beds.options[theForm.beds.selectedIndex].value);
				this.setCookie("orderBy",theForm.orderBy.value);
			}
		},
		sendToFriend: {
			/*
			 *  Requires shadowbox.js to be loaded.
			*/
			init: function(){
				/* Error trap */
				if(typeof Shadowbox != "undefined"){
					Shadowbox.loadSkin('', palm.asset_prefix);

					window.addEvent("domready",function(){
						if($('send_to_friend')){
							Shadowbox.init();
						}
						if($('send_to_friend_form')){
							palm.tools.sendToFriend.initSendToFriendForm();
						}
						$$('.close_popup').each(function(el){
							el.addEvent("click",function(){
								parent.Shadowbox.close();
							});
						});
						$$('.send_btn').each(function(el) {
							el.addEvent("click",function(){
								palm.tools.sendToFriend.sendEmailAndShowResult($(document.body).getElement("form[name='form1']"));
							});
						});
						$$('.edit_btn').each(function(el) {
							el.addEvent("click",function(){
								palm.tools.sendToFriend.showEditForm($(document.body).getElement("form[name='form1']"));
							});
						});
					});
				}
			},
			showEditForm: function(theForm){
				theForm.action="send-to-friend.php";
				theForm.submit();
			},
			sendEmailAndShowResult: function(theForm){
				theForm.action="send-to-friend.php?action=sendEmail";
				theForm.submit();
			},
			initSendToFriendForm: function(){
				var myName = new LiveValidation('myName', {onlyOnSubmit: true });
				var myEmail = new LiveValidation('myEmail', {onlyOnSubmit: true });
				var friendName = new LiveValidation('friendName', {onlyOnSubmit: true });
				var friendEmail = new LiveValidation('friendEmail', {onlyOnSubmit: true });
				myName.add(Validate.Presence);
				myEmail.add(Validate.Presence);
				myEmail.add(Validate.Email);
				friendName.add(Validate.Presence);
				friendEmail.add(Validate.Presence);
				friendEmail.add(Validate.Email);
			}
		},
		urlEncode: function(s) {
			/* Replaces url-unfriendly characters with encoded entities */
			s = encodeURIComponent(s);
			return s.replace(/~/g,'%7E').replace(/%20/g,'+');
		}
	}
};

palm.init();

