/* ******************* common functions ******************** */

	//	get the offsetLeft position for an object
	function get_offset_left(obj){
		var x = obj.offsetLeft;
		
		if(obj.offsetParent != null) x += get_offset_left(obj.offsetParent);
		
		return x;
	}
	
	//	get the offsetTop position for an object
	function get_offset_top(obj){
		var y = obj.offsetTop;
		
		if(obj.offsetParent != null) y += get_offset_top(obj.offsetParent);
		
		return y;
	}

	//	grab element by id, and return as object
	function get_element(id){
		return document.getElementById(id);
	}
	
	//	add target attribute to (external) links by checking rel attribute
	function add_target(parent_element, rel_value, target_value){
		if (target_value) {
			$(parent_element).getElements('a[rel=' + rel_value + ']').setProperty("target", target_value);
		} else {
			if(document.addEventListener) //firefox
			{   
				  document.addEventListener("DOMContentLoaded", function(){
					  	$(parent_element).getElements('a[rel=' + rel_value + ']').each(function(item){
						item.target = item.href.replace("/", "");
					});			  
				  }, false);
			}
			else //IE6 & above
			{
				  document.attachEvent("onreadystatechange",function(){
					  $(parent_element).getElements('a[rel=' + rel_value + ']').each(function(item){
						item.target = item.href.replace("/", "");
					});				  
				  });
			}			
		}
	}

	//	element opacity level
	function set_opactity(obj,opacity){
		if(window.ie){
			obj.style.filter = "alpha(opacity=" + opacity + ")";
		} else{
			obj.style.opacity = (opacity/100);
		}
	}
	
	
	
/* ******************** event handlers ********************* */
	
	function add_event(elem, event_type, handler){
		if(document.addEvent){
			elem.addEvent(event_type, handler);
		}
		else{
			if(!elem.eventHandlers) elem.eventHandlers = [];
			if(!elem.eventHandlers[event_type]){
				elem.eventHandlers[event_type] = [];
				if(elem['on' + event_type]) elem.eventHandlers[event_type].push(elem['on' + event_type]);
				elem['on' + event_type] = handle_event;
			}
			elem.eventHandlers[event_type].push(handler);
		}
	}
	
	function remove_event(elem, event_type, handler){
		if(document.removeEvent){
			elem.removeEvent(event_type, handler);
		}
		else{
			var handlers = elem.eventHandlers[event_type];
			for (var i in handlers) if(handlers[i] == handler) delete handlers[i];
		}
	}
	
	function handle_event(e){
		var return_value = true;
		
		if(!e) e = fix_event(event);
	
		var handlers = this.eventHandlers[e.type]
	
		for(var i in handlers){
			this.$$handle_event = handlers[i];
			return_value = !((return_value && this.$$handle_event(e)) === false);
		}
		
		return return_value;
	}
	
	function fix_event(e){
		//add W3C standard event methods
		e.prevent_default = fix_event.prevent_default;
		e.stop_propagation = fix_event.stop_propagation;
		return event;
	};
	
	fix_event.prevent_default = function(){
		this.returnValue = false;
	};
	
	fix_event.stop_propagation = function(){
		this.cancelBubble = true;
	};



/* **************** show / hide drop-downs ***************** */

	//	store active dd element
	var active_select = null;
	
	function show_selector_dropdown(trigger, pseudo_select){
		trigger.menu = document.getElementById(pseudo_select);
		
		if(active_select && active_select != trigger){
			active_select.menu.style.display = "none";
			active_select = null;
		}
	
		if(trigger.menu.style.display != "block"){
			trigger.menu.style.display = "block";
			active_select = trigger;
			add_event(document, 'mouseup', hide_selector_dropdown);
		} else {
			trigger.menu.style.display = "none";
			active_select = null;
			remove_event(document, 'mouseup', hide_selector_dropdown);
		}
	}

	function hide_selector_dropdown(e){
		var trigger = e.srcElement ? e.srcElement : e.target;
		
		if (active_select.menu == trigger) {
			return;
		} else {
			while(trigger != active_select && trigger.tagName != "BODY"){
				trigger = trigger.parentNode;
			}
			if(trigger != active_select){
				active_select.menu.style.display = "none";
				active_select = null;
				remove_event(document, 'mouseup', hide_selector_dropdown);
			}
		}
	}



/* ************************* popups ************************ */

	var search_input_default_text = "Keyword";
	var popup_container = null;
	var block_layer = null;

	//	setup the banner "my community" and "send to a friend" links. setup search field
	function init_banner_setup() {
		
		$('development_selector_link').onclick = function(){
			show_selector_dropdown(this, 'development_selector_dropdown');
			
			//	set the height of the development selector drop down if items count less than 6
			var development_selector_dropdown_height = 0;
			var li_collection = $('development_selector_dropdown').getElementsByTagName("li");
			if (li_collection.length <= 6) {
				for (var i = 0; i < li_collection.length; i++) {
					development_selector_dropdown_height += li_collection[i].offsetHeight;	
				}
				$('development_selector_dropdown').setStyle("height", development_selector_dropdown_height + "px");
			}
			return false;
		}
		
		if ($('utility_links')) {
			$('utility_links').getElement('a[class=print]').addEvent("click", function(){
				window.print();
			});
		
			$('utility_links').getElement('a[class=send]').addEvent("click", function(event){
				new Event(event).stop();
				open_iframe('send_to_a_friend', this.href);
			});
		}
		
		if ($('search')) {
			var search_input = $('search').getElement('input[class=search_input]');
			search_input.onfocus = function(){
				if (this.value == search_input_default_text){
					this.value = "";
				}
			}
			search_input.onblur = function(){
				if (this.value == ""){
					this.value = search_input_default_text;
				}
			}
		}
		
		if ($('search_results_form')) {
			var search_input = $('search_results_form').getElement('input[class=search_input]');
			search_input.onfocus = function(){
				if (this.value == search_input_default_text){
					this.value = "";
				}
			}
			search_input.onblur = function(){
				if (this.value == ""){
					this.value = search_input_default_text;
				}
			}
		}
		
		//	set external links for banner
		add_target("banner", "external", "wwwNakheelCom");
		
		//	set external links for content area
		add_target("content", "external");
	}

	//	setup the gallery links to show popup when clicked
	function init_gallery_setup() {
		$('content').getElements('a[class=gallery]').addEvent("click", function(event){
			new Event(event).stop();
			open_iframe('gallery_image', this.href);
		});
	}

	//	setup the news article carousel images to show popup when clicked
	function init_news_article_setup(path) {		
		$('photos_list_inner').getElements('a').addEvent("click", function(event){
			new Event(event).stop();
			open_iframe('news_article_image', path+'/news-article-image.jsp?image=' + this.href);
		});
	}
	
	function open_iframe(type, url){
		//	create the element if id doesn't exist.
		if (popup_container == null) {
			popup_container = document.createElement('iframe');
			popup_container.name = 'popup_frame';
			popup_container.id = 'popup_frame';
			popup_container.className = 'popup';
			popup_container.style.top = "0";
			popup_container.allowTransparency = "true";
			popup_container.frameBorder = 0;
			document.body.appendChild(popup_container);
		}

		popup_container.src = url;
		toggle_block_layer();
		
		popup_container.style.height = document.getElementById('block_layer').style.height;
		//	visibility set in position_iframe()
		//	popup_container.style.visibility = 'visible';
	}
	
	//	check the scroll top of the parent window and move the popup so that's it's always in view. runs on dom ready
	function position_iframe() {
		var parent_iframe = parent.document.getElementById("popup_frame");
		var offset = 45;
		if (parent_iframe) {
			var top = parent.window.getScrollTop();			
			$('popup_iframe').style.top = (top > 0) ? parseInt(offset + top) + "px" : offset + "px";
			parent_iframe.style.visibility = "visible";
		}
	}
	
	function hide_iframe(){
		document.getElementById('popup_frame').style.visibility = 'hidden';
		document.getElementById('popup_frame').src = "";
		toggle_block_layer();
		return false;
	}

	function toggle_block_layer() {
		if (block_layer == null) {
			block_layer = document.createElement("div");
			block_layer.id = "block_layer";
			set_opactity(block_layer, 40);
			document.body.appendChild(block_layer);
		}
		if (block_layer.style.display != "block") {
			//	hide select elements in IE6 as they appear on top of everything
			if (window.ie6) {
				$(document).getElements('select').setStyle("visibility", "hidden");
			}
			$('block_layer').setStyles({
			   height: window.getScrollHeight() + "px",
			   display: "block"
			});
		} else {
			block_layer.style.display = "none";
			if (window.ie6) {
				$(document).getElements('select').setStyle("visibility", "visible");
			}
		}
	}
	
	
/* *********************** carousels *********************** */
		
	var carousels = new Array();
	var carousel_speed = 10;
	var carousel_increment_division = 10;
	
	function init_carousel(id, linked_id){
		
		carousels.push(id);
		if (linked_id) {
			carousels.push(linked_id);
		}
		
		for (var i = 0; i < carousels.length; i++){
			var scroller = $(carousels[i]);
			$(scroller.id + "_inner").className = "carousel_list_inner";
			
			var img_collection = 0;
			
			//	if there is a linked carousel, build the images to be inserted
			if (linked_id && scroller.id != linked_id) {
				
				//	collect anchors from the non-linked carousel
				var img_collection = scroller.getElementsByTagName("A");
				if (img_collection.length == 0) {
					return;
				}
				
				//	create image and inserted into linked carousel based on the non-linked anchor HREF
				for (var j = 0; j < img_collection.length; j++){
					var img = img_collection[j];
					
					var img_new = document.createElement("IMG");
					img_new.src = img.href;
					img_new.id = "img_" + j;
					if (img.childNodes[0].alt) {
						img_new.alt = img.childNodes[0].alt;
					}
					
					document.getElementById(linked_id + "_inner").appendChild(img_new);
				}
			}
			
			//	get the total number of images in carousel
			img_collection = (scroller.getElementsByTagName("A").length != 0) ? scroller.getElementsByTagName("A") : scroller.getElementsByTagName("IMG");
			
			//	configure scroller
			scroller.config = {
				//	total number of images in carousel
				img: img_collection,
				//	number of visible images in carousel at 1 time
				num_visible: 0,
				//	scrolling animation increment size
				increment: parseInt(img_collection[0].offsetWidth / carousel_increment_division),
				//	current image being scrolled
				current: 1,
				//	image margin width
				img_margin: 0
			}
			
			//	update the image margin width and number visible
			scroller.config.img_margin = scroller.config.img[1].offsetLeft - scroller.config.img[0].offsetWidth;
			scroller.config.num_visible = Math.ceil(scroller.offsetWidth / (scroller.config.img[0].offsetWidth + scroller.config.img_margin));
			
			//	the total width of the inner scroller (all images and margins combined)
			var scroller_inner_width = 0;
			
			for (var j = 0; j < scroller.config.img.length; j++) {
				var img = scroller.config.img[j];
				img.position = j + 1;
	
				scroller_inner_width += img.offsetWidth + scroller.config.img_margin;
				
				if (linked_id && scroller.id != linked_id) {
				
					img.linked_id = linked_id;
					img.onclick = function(){
						
						var linked_scroller = $(this.linked_id);
						var linked_scroller_inner = $(linked_scroller.id + "_inner");
						
						if (linked_scroller.anim == null) {
							
							var img = linked_scroller.config.img[this.position - 1];
							
							//	get current and next images
							var img_current = linked_scroller.config.img[linked_scroller.config.current - 1];
							var img_next = linked_scroller.config.img[img.position - 1];
							
							linked_scroller_inner.scroll_to = parseInt(linked_scroller_inner.offsetLeft - (img_next.offsetLeft - img_current.offsetLeft));
							
							//	same position
							if (img_next.offsetLeft == img_current.offsetLeft) {
								return false;
								
							//	higher position
							} else if (img_next.offsetLeft > img_current.offsetLeft) {
								linked_scroller.config.increment = parseInt((img_next.offsetLeft - img_current.offsetLeft) / carousel_increment_division);
								linked_scroller.anim = true;
								scroll_anim(linked_scroller.id);
								
							//	lower position
							} else if (img_next.offsetLeft < img_current.offsetLeft) {
								linked_scroller.config.increment = parseInt((img_current.offsetLeft - img_next.offsetLeft) / carousel_increment_division);
								linked_scroller.anim = true;
								scroll_anim(linked_scroller.id);
							}
		
							//	adjust the current image number
							linked_scroller.config.current = img.position;
						}
						return false;
					}
				}
			}
			
			$(scroller.id).style.height = scroller.config.img[0].offsetHeight + "px";
			$(scroller.id).style.overflow = "hidden";
			$(scroller.id + "_inner").style.width = scroller_inner_width + "px";
			if (scroller.config.img.length > scroller.config.num_visible) {
			//	left button - set to disabled on init
			var btn_left = $(scroller.id + "_left");
			btn_left.scroller_id = scroller.id;
			btn_left.className += " disabled";
			btn_left.onclick = function(){
			
				var scroller = $(this.scroller_id);
				var scroller_inner = $(scroller.id + "_inner");
				
				//	check that scroller isn't already running and that button's not disabled	
				if ((scroller.anim == null) && this.className.match("disabled") == null) {
					//	get the animation end position
					scroller_inner.scroll_to = parseInt(scroller_inner.offsetLeft + scroller.config.img[scroller.config.current - 1].offsetWidth + scroller.config.img_margin);
					scroller.anim = true;
					scroll_anim(scroller.id);

					//	adjust the current image number
					scroller.config.current -= 1;
				}
				return false;
			}
			btn_left.style.visibility = "visible";
			
			//	right button
			var btn_right = $(scroller.id + "_right");
			btn_right.scroller_id = scroller.id;
			btn_right.onclick = function(){
				
				var scroller = $(this.scroller_id);
				var scroller_inner = $(scroller.id + "_inner");
				
				//	check that scroller isn't already running and that button's not disabled
				if ((scroller.anim == null) && this.className.match("disabled") == null) {
					//	get the animation end position
					scroller_inner.scroll_to = parseInt(scroller_inner.offsetLeft - scroller.config.img[scroller.config.current - 1].offsetWidth - scroller.config.img_margin);
					scroller.anim = true;
					scroll_anim(scroller.id);
					
					//	adjust the current image number
					scroller.config.current += 1;
				}
				return false;
			}
			
			btn_right.style.visibility = "visible";
			
			if (scroller.id == linked_id) {
				scroller_info_update(scroller);
			}
			}
	}
	}
	var fx_scroll = null;
	
	function scroll_anim(id){
		var scroller = $(id);
		var scroller_inner = $(scroller.id + "_inner");
		
		//	var fx_scroll = new Fx.Style(scroller_inner, 'left', {
		fx_scroll = new Fx.Style(scroller_inner, 'left', {
			transition: Fx.Transitions.Quart.easeOut,
			duration: 350,
			onComplete: function() { 
				clear_scroller_anim(scroller.id);
			}
		});

		fx_scroll.start(scroller_inner.offsetLeft, scroller_inner.scroll_to);
	}
	
	//	clear scroller animation
	function clear_scroller_anim(id) {
		var scroller = $(id);
		scroller.anim = null;
		scroller.config.increment = parseInt(scroller.config.img[0].offsetWidth / carousel_increment_division);
		end_scroller(scroller.id);
	}
	
	//	check position to disable buttons
	function end_scroller(id) {
		var scroller = $(id);
		var btn_left = $(scroller.id + "_left");
		var btn_right = $(scroller.id + "_right");
		
		if (scroller.config.current == 1) {
			btn_left.addClass("disabled");
			btn_right.removeClass("disabled");
		} else if (scroller.config.current == parseInt((scroller.config.img.length + 1) - scroller.config.num_visible)) {
			btn_left.removeClass("disabled");
			btn_right.addClass("disabled");
		} else {
			btn_left.removeClass("disabled");
			btn_right.removeClass("disabled");
		}
		
		scroller_info_update(scroller)
	}
	
	//	update description (uses the alt tag text of image) and image counter
	function scroller_info_update(scroller) {
		if ($(scroller.id + "_description")) {
			var img = scroller.config.img[scroller.config.current - 1];
			if (img.tagName == "A") {
				img = img.childNodes[0];
			}
			if (img.tagName == "IMG" && img.getAttribute("alt") != null) {
				$(scroller.id + "_description").innerHTML = img.getAttribute("alt");	
			}
		}
		if ($(scroller.id + "_total_images")) {
			$(scroller.id + "_total_images").innerHTML = scroller.config.current + "/" + scroller.config.img.length;
		}
	}
	
	function stop_carousels() {
		for (var i=0; i < carousels.length; i++) {
			clear_scroller_anim(carousels[i])
		}
	}
	
	
	
/* ********************* form styles *********************** */

	/*  
		Title: Form Styling
		Dependancies: global.js
		Date: 2 May 2008
		Author: Jeremy FitzPatrick (jfitzpat@digitas.com)
		
		About:  Adds styling to 'unstylable' form elements input[type=style] and select by 
				hiding the corresponding form element and adding stylable elements in its place.
	*/

	var W3CDOM = (document.createElement && document.getElementsByTagName);
	
	function initFileUploads(path) {
		if (!W3CDOM) return;
		var fakeFileUpload = document.createElement('div');
		fakeFileUpload.className = 'fakefile';
		dummy_input = document.createElement('input');
		dummy_input.type = "text";
		fakeFileUpload.appendChild(dummy_input);
		fakeFileUpload.innerHTML = fakeFileUpload.innerHTML + '<img src="' + basePath + path+'button_select.gif" />'
		var x = document.getElementsByTagName('input');
		for (var i=0;i<x.length;i++) {
			if (x[i].type != 'file') continue;
			if (x[i].parentNode.className.indexOf('file_upload') != -1) {
				x[i].className = 'file hidden';
				var clone = fakeFileUpload.cloneNode(true);
				x[i].parentNode.appendChild(clone);
				x[i].relatedElement = clone.getElementsByTagName('input')[0];
				x[i].onchange = x[i].onmouseout = function(){
					this.relatedElement.value = this.value;
				}
			}
		}
	}
	
	function init_selects(form) {
		var select_elements = document.forms[form].getElementsByTagName('select');
		for (var i=0; i<select_elements.length; i++){
			var select_element = select_elements[i];
			// create 'text box'
			var pseudo_select = document.createElement('div');
			pseudo_select.id = select_element.name + "_pseudo";
			pseudo_select.className = "form_select";
			
			pseudo_select.onclick = function(){
				show_selector_dropdown(this, this.id + "_list");
			}
			select_element.parentNode.appendChild(pseudo_select);
			
			var pseudo_select_list = document.createElement('ul');
			pseudo_select_list.className = "form_select";
			pseudo_select_list.id = select_element.name + "_pseudo_list";
			pseudo_select_list.style.left = get_offset_left(select_element);
			pseudo_select_list.style.top = get_offset_top(select_element);
			
			select_elements[i].style.display = 'none';
			
			var items = select_elements[i].getElementsByTagName('option');
			for (var j=0; j<items.length; j++){
				var list_item = document.createElement('li');
				list_item.innerHTML = '<a href="#">' + items[j].innerHTML + '</a>';
				list_item.value = j;
				
				list_item.onclick = function(){
					var pseudo_select_name = this.parentNode.id.toString().replace('_list', '');
					document.getElementById(pseudo_select_name).innerHTML = this.childNodes[0].innerHTML;
					show_selector_dropdown(this, this.parentNode.id);
					active_select = null;
					// set selected
					document.forms[form].elements[pseudo_select_name.replace("_pseudo", "")].options[this.value].selected = true;
					return false;
				}
				
				if (j==0){
					pseudo_select.innerHTML = items[j].innerHTML;
				}
	
				pseudo_select_list.appendChild(list_item);
			}
			select_element.parentNode.appendChild(pseudo_select_list);
		}
	}
	
	

/* ********************** ajax tabs ************************ */

	var tabs = null;
	
	function ajax_tabs(){
		if (get_element("tabs")) {
			tabs = get_element("tabs").getElementsByTagName("A");
		
			for (var i = 0; i < tabs.length; i++){
				
				tabs[i].onclick = function(e){
					
					if (this.className == "select") {
						return false;
					}
		
					e = new Event(e).stop();
					
					parent_accordian_li = null;
					
					//	remove and set the selected class
					for (var j = 0; j < tabs.length; j++){
						tabs[j].className = "";
					}
					
					this.className = "select";
					
					var id = 0;
					id = this.parentNode.id.replace("tab-", "");
					
					var date = new Date();
					var timestamp = date.getTime();
					 
					var url = basePath + "proxy.php?community=" + id + "&time=" + timestamp + "&time=" + timestamp;
					new Ajax(url, {
						method: 'get',
						onComplete: function(response) {
							$('tab_content').innerHTML = response;
							init_accordion();
						}
					}).request();
				}
			}
		}
	}