/*
Define a few base functions and vars
*/
var Dom = YAHOO.util.Dom;
var Event = YAHOO.util.Event;

// For IE, document.getElementsByName is not implemented properly.
if (navigator.userAgent.indexOf('IE') !== -1) {
	document.getElementsByName = function(str){
		str = new String(str);
		var myMatches = new Array();
		var allEls = document.getElementsByTagName("*"), l = allEls.length;
		for (var i = 0; i < l; i++)
			if (allEls[i].name == str || allEls[i].getAttribute("name") == str)
				myMatches[myMatches.length] = allEls[i];
		return myMatches;
	}
}

var couponTermsContentStart = "<html>"+
"<head>"+
"	<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"\/>"+
"	<title>Coupons - finda<\/title>"+
"	<link rel=\"stylesheet\" href=\"/css/style.css?20080717\" media=\"all\" type=\"text/css\"\/>"+
"	<link rel=\"stylesheet\" href=\"/css/form.css?20080717\" media=\"screen\" type=\"text/css\"\/>"+
"	<link rel=\"stylesheet\" href=\"/css/print.css?20080717\" type=\"text/css\" media=\"print\"\/>"+
"<\/head>"+
"<body id=\"coupon-terms\" width=\"500\"><p><a href='#' class=\"close-win\" onclick='window.close()'>Close window x<\/a><\/p>"+
"<h1>Coupon Terms &amp; Conditions</h1>";

var couponTermsContentEnd = "<\/body>"+
"<\/html>";

// shortcut getElementById();
function $(id) {
	return Dom.get(id);
}


function openCouponTermsWindow (type,term_id) {
	var term = Dom.get(term_id).value;
	if(type == 'term_url') {
		var regexUrl = /^http[s]*\:\/\//i;
		if(!term.match(regexUrl)) {
			term = "http://" + term;
		}
		window.open(term,'new_window','menubar=no,toolbar=no,resizable=1,width=800,height=600,location=no');
	} else if(type == 'term_content') {
		new_window= window.open ('','new_window','directories=no,location=no,menubar=no,resizable=yes,status=no,toolbar=no,scrollbars=yes,width=500,height=600');
		new_window.document.write(couponTermsContentStart + term + couponTermsContentEnd);
	}
}


// toggle two functions
function toggle(el,event,f1,f2,context){
	var state=false;

	function handleEvent (e) {
		state = !state;
		if (state) {
			f1(context);
		} else {
			f2(context);
		}
		//could add conditional here
		YAHOO.util.Event.stopEvent(e);
	}

	Event.addListener(el,event,handleEvent);
}

/* todo replace with yui */
function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

/**
 * if footers normal-flow-position is above viewport then move it, else keep in flow
 */
function setFooter() {
	var footer = $('footer');

	Dom.setStyle(footer,'position','static');

	var viewHeight = YAHOO.util.Dom.getViewportHeight();
	var footerHeight = parseInt(Dom.getStyle(footer,'height'),10);
	if (Dom.getY(footer)+footerHeight < viewHeight) {
		Dom.setStyle(footer,'position','relative');
		//seems to need an offset of 2 to prevent the vertical scrollbar appearing
		Dom.setY(footer,viewHeight-footerHeight-2);
	}
}

function updateurl(item){
	value = Dom.get(item).value;
	Dom.get(item).value = value.replace(/^http(s)*:\/\//, '');
}

/**
  * enable scrolling elements on Listing Images page
  */
function scrollElement(elem, increment) {
	var scrollAnim = new YAHOO.util.Scroll(elem, { scroll: { by: [increment] } }, 0.8, YAHOO.util.Easing.easeOut);
	scrollAnim.animate();
}

function getElementHeight(el) {
	return Dom.getStyle(el,"height");
}


function hideAlert() {
	Dom.setStyle("feedback-alert-element","overflow","hidden");
	var altertAnimClose = new YAHOO.util.Anim("feedback-alert-element",{ height: { to: 0 } },0.2,YAHOO.util.Easing.easeOut);
	altertAnimClose.onComplete.subscribe(function(){Dom.setStyle("feedback-alert-element","display","none");});
	altertAnimClose.animate();
}
function dayValidation(){
	var selMonth = Dom.get("selMonth");
	var selDay = Dom.get("selDay");
	var selYear = Dom.get("selYear");
	var month = parseInt(selMonth.options[selMonth.selectedIndex].value);
	var year = parseInt(selYear.options[selYear.selectedIndex].value);
	var firstday = new Date(year, month, 1);
	var firsttime = firstday.getTime();
	var lasttime = firsttime - 3600*1000*24;
	var lastday = new Date();
	lastday.setTime(lasttime);
	last = lastday.getDate();
	dayHtml = '';
	/*for(i=1; i<=last; i++){
		dayHtml += '<option value="'+i+'">'+i+'</option>';

	}*/
	selDay.innerHTML = "";
	for(i=1; i<=last; i++){
		opt = document.createElement("option");
		opt_txt = document.createTextNode(i);
		opt.appendChild(opt_txt);
		opt.setAttribute("value", i);
		selDay.appendChild(opt);
	}
	selDay.disabled = false;

}

/**
 * list of createFormChange objects
 */
globalFormChangeList = [];

/**
 * used with getElementsBy
 */
function isFormInput(el){
	return (el.tagName==='INPUT') || (el.tagName==='SELECT') || (el.tagName==='TEXTAREA');
}

/**
 * requires json model data to process client side validation of forms.
 * some validation still needs to be done server-side, eg duplicated email or something.
 * or that could be assisted with ajax?
 */
function createFormValidator () {

}

function createHighlighter (el) {
	var o = {};
	var attributesIn = { backgroundColor: { from:'#fff', to: '#f7f1d2' } };
	var attributesOut = { backgroundColor: { to: '#fff' } };
	var animIn = new YAHOO.util.ColorAnim(el, attributesIn, 0.4, YAHOO.util.Easing.easeOut);
	var animOut = new YAHOO.util.ColorAnim(el, attributesOut, 0.4, YAHOO.util.Easing.easeOut);
	o.execute = function () {
		animIn.animate();
	};
	//hook up the color anims to bounce the color
	animIn.onComplete.subscribe(function(){animOut.animate();});
	return o;
}

/**
 * replace el.focus() with our own?
 * to avoid the browser scrolling the element into what it thinks is a nice position, use a hash that doesnt match an id?
 * then the browser will do nothing and we can scroll as we want
 * except that it wouldnt work at all in no-script
 */
function focusElement(el){
	if (!el.highlighter) {
		el.highlighter = createHighlighter(el);
	}
	el.focus();
	el.highlighter.execute();
}

//set cursor for map
function setMapCursor (item) {
	if (navigator.userAgent.indexOf('IE')!==-1) {
		YAHOO.util.Event.on(item,"mousedown",function(){Dom.setStyle(item,'cursor','/images/closedhand.bmp');});
		YAHOO.util.Event.on(item,"mouseup",  function(){Dom.setStyle(item,'cursor','/images/openhand.bmp');});
	} else {
		YAHOO.util.Event.on(item,"mousedown",function(){Dom.setStyle(item,'cursor','-moz-grabbing');});
		YAHOO.util.Event.on(item,"mouseup",  function(){Dom.setStyle(item,'cursor','');});
	}
}

/**
 * improve the feedback section
 * eg when a user click a link (eg "password is required") focus and highlight that input element
 */
function createEnhancedFeedback () {
	var o = {};
	//matches url like "some/page#form_element" or "some/page#form_element_array[]"
	var regexHash = /^.+#([\w]+(\[[0-9]+\])*)$/;
	var form;

	/**
	 * return the target element from the link hash eg "/page#password" -> password object
	 * use form.input so it uses the name instead of the id.
	 * reduces need to have matching names+ids, allows multiple forms with same fields without duplicate ids
	 */
	function getElementFromLink (link) {
		var matches = regexHash.exec(link.href);
		var name = matches[1];
		if (form) {
			//a match to a form element name is best, as that's what's actually submitted
			return form.elements[name];
		} else {
			//else see if there's an id
			return YAHOO.util.Dom.get(name);
		}
	}

	function callbackClick (e) {
		var el = getElementFromLink(this);
		//shouldnt happen. typical is if el.id<>name eg "trading_name" + "trading-name"
		if (!el) {
			return;
		}
		//focus and highlight
		focusElement(el);
		//detect if browser can do scrolling
		if (window.scrollTo) {
			YAHOO.util.Event.stopEvent(e);
			var y = YAHOO.util.Dom.getY(el);
			var top = YAHOO.util.Dom.getDocumentScrollTop();
			var height = YAHOO.util.Dom.getViewportHeight();
			//if not in view then scroll
			//should adjust for not-all-in-view, eg for a large text-area
			if ( (y<top) || (y>top+height) ) {
				window.scrollTo(0,y-50);
			}
			//focus after scroll
			el.focus();
		}
	}
	function linkHasHash (el) {
		return regexHash.test(el.href);
	}
	/**
	 * setup the given link and its parent LI
	 */
	function initFeedbackItem(el) {
		YAHOO.util.Event.on(el,'click',callbackClick);
		var target = getElementFromLink(el);
		var item = YAHOO.util.Dom.getAncestorByTagName(target,'li');
		if (item) {
			YAHOO.util.Dom.addClass(item,'error');
		}
	}
	function init () {
		//see if there is a feedback area
		//if there are multiple forms, possible there is more than one? should use a class rather than an id..
		var feedback = YAHOO.util.Dom.get('feedback-alert-element');
		if (!feedback) {
			return;
		}
		form = YAHOO.util.Dom.getAncestorByTagName(feedback,'form');
		//get child links and add click event
		YAHOO.util.Dom.getElementsBy(linkHasHash,'a',feedback,initFeedbackItem);

	}

	init();
	return o;
}

/**
 * object that detects changes made to form contents
 * could poll inputs to detect change if unable to subscribe to events?
 * ok to run for every form on page, as it doesnt actually do anything?
 */
function createFormChange ( form ) {
	var o = {};
	function getInputs () {
		//only inputs with name attributes?
		return YAHOO.util.Dom.getElementsBy(isFormInput,null,form);
	}
	//return an array of the changed inputs. could be public.
	function getChanged () {
		//ideally return a hash of the values, but nothing native in jscript
		var inputs = getInputs();
		var input;
		var i;
		var a = [];
		for (i=0;i<inputs.length;i++) {
			input = inputs[i];
			if (input.value != input.originalValue) {
				a.push(input);
			}
		}

		return a;
	}
	/**
	 * called when an input is modified
	 */
	function callbackFormChange(e){
		//alert('change');
	}
	//store the original value of the input, makes it easy to compare for changes
	function init (){
		//http://www.quirksmode.org/js/events_compinfo.html#forms
		//YAHOO.util.Event.addListener(form,'change',callbackFormChange);
		var inputs = getInputs();
		var input;
		var i;
		for (i=0;i<inputs.length;i++) {
			input = inputs[i];
			input.originalValue = input.value;
		}
	}
	//public. boolean, true if any inputs have changed
	o.hasChanged = function () {
		var list = getChanged();
		return list.length>0;
	};
	//setup
	init();
	//add to the list of objects
	globalFormChangeList.push(o);
	return o;
}

/**
 * hooks into all links on a page.
 * if a link is clicked, and there are any unsaved changes to forms,
 * then a dialog is shown asking to save changes
 * could auto-run this on each page. only certain forms though, eg not a login dialog?
 */
function createUnsavedChanges () {
	var o = {};
	function dataHasChanged() {
		//globalFormChangeList
		var i;
		var change;
		for (i=0;i<globalFormChangeList.length;i++) {
			change = globalFormChangeList[i];
			if (change.hasChanged() ) {
				return true;
			}
		}
		return false;
	}
	/**
	 *
	 */
	function callbackClick(e){
		//ignore links that have other event handlers.
		//do this now rather that at page-ready as other javascript that adds events may not have run yet.
		var regex;
		var events = YAHOO.util.Event.getListeners(this);
		if ((events) && (events.length>1)) {
			return;
		}
		//ignore links with onclick handlers
		if (this.onclick) {
			return;
		}
		//ignore links that have embedded javascript
		regex = /^javascript/;
		if (regex.test(this.href)) {
			return;
		}
		//ignore links that are just bookmarks
		regex = /^#/;
		if (regex.test(this.href)) {
			return;
		}
		//if no changes then continue as normal
		if (!dataHasChanged()) {
			return;
		}
		if (confirm("Are you sure you want to navigate away from this page? \r\nPress OK to continue, or Cancel to stay on the current page.")==true) {
			return;
		}
		//
		YAHOO.util.Event.stopEvent(e);
	}
	/**
	 * add an event handler for each link on the page
	 */
	function hookLinks(){
		var links = YAHOO.util.Dom.getElementsBy(function(){return true;},'A');
		var i;
		var link;
		for (i=0;i<links.length;i++) {
			link = links[i];
			YAHOO.util.Event.on(link,'click',callbackClick,link);
		}
	}
	//init
	hookLinks();
	return o;
}

/**
 * when page is loaded, if doc.hash is a form input, then focus it
 * todo check ie with hash but no string eg "page#"
 */
function highlightDocumentHash () {
	var hash = document.location.hash;
	if (hash==''){
		return;
	}
	var regex = /#(\w+(\[[0-9]+\])*)/;
	var matches = regex.exec(hash);
	//or do is not array?
	if ((matches == false) || (matches == null)) {
		return;
	}
	var name = matches[1];
	var el = YAHOO.util.Dom.get(name);
	if (!el){
		return;
	}
	//if el is not visible then we cant do anything
	//already focused and scrolled by browser, just need to highlight
	try {
		el.focus();
	} catch(e) {
		//do nothing
	}
	var item = YAHOO.util.Dom.getAncestorByTagName(el,'li');
	if (item) {
		YAHOO.util.Dom.addClass(item,'error');
	}
}

/**
 * this class manages hiding any unused LI items.
 * for example, intead of showing 9 empty image upload boxes, it will show 2 + a 'click to add more' link
 */
function createAddAnotherItemList (list,clickEl,minCount) {
	var o = {};
	var items = [];

	function callbackClicked (e) {
		YAHOO.util.Event.stopEvent(e);
		//pop an item and add to list
		var item = items.pop();
		list.appendChild(item);

		//if items is empty then hide the click element
		if (items.length == 0) {
			YAHOO.util.Dom.addClass(clickEl,'hide');
		}
	}

	//take the list of ul and remove all but <count> from the dom.
	function init () {
		var item;
		var i;
		var inputList;
		//specifically get LI's , children also includes text nodes of spaces
		var children = YAHOO.util.Dom.getChildrenBy(list,function(el){ return el.tagName=="LI" } );
		//hide any li with can-hide in the class. this is so li's with data in them arent hidden
		//or look inside the li for an input element and check its value
		for (i=children.length-1;i>=minCount;i--) {
			item = children.pop();
			inputList = YAHOO.util.Dom.getChildrenBy(list,function(el){ return (el.tagName=="INPUT") && (el.value!='') } );
			if (inputList.length==0) {
				list.removeChild(item);
				items.push(item);
			}
		}
		YAHOO.util.Event.addListener(clickEl,'click',callbackClicked);
	}

	init();

	//no real reason to return this right now. maybe add an active? or have remainingCount as a property?
	return o;
}

/**
 * this function runs on *every page*.
 * only stuff that should be run on every page is allowed here.
 */
function globalReady () {

	// for each form on the page with the "saved-changes" class, create a change handler
	//really, this should probably apply to all forms. then listeners can decide what they do.
	YAHOO.util.Dom.getElementsByClassName('saved-changes','form',null,createFormChange);

	// if a page is navigated away from, check the form change handlers for unsaved changes, display a warning dialog
	createUnsavedChanges();

	createEnhancedFeedback();

	// run the homepage carousel and category stuff
        // commented out as not needed
	//homePageinit();

	//if the url has a hash then focus and highlight the element.
	//eg on the finda accounts page, the suggested update points to a specific input
	highlightDocumentHash();

}

pageReadyEvent.subscribe(globalReady);

//footer position should also be recalced on a timer to allow for page layout changes eg elements inserted

//safari/mac has an odd/high-value footer.y,
//may change this to a setInterval so footer position is recalced regularly, eg in case dom elements are changed by javascript

//pageReadyEvent.subscribe(findaReady);


// addthis configurations
/*
var addthis_share_config = {
	services_compact : 'bebo,bitly,blogger,buzz,digg,facebook,friendster,linkedin,myspace,slashdot,stumbleupon,twitter,wordpress',
	services_expanded : ''
}
var addthis_bookmark_config = {
	services_compact : 'favorites,print,aim,ask,delicious,designbump,google,igoogle,live,myaol,yahoobkm',
	services_expanded : ''
}*/
var addthis_email_config = {
	services_compact : 'mailto,email,aolmail,gmail,hotmail,yahoomail, bebo,bitly,blogger,buzz,digg,facebook,friendster,linkedin,myspace,slashdot,stumbleupon,twitter,wordpress, favorites,print,aim,ask,delicious,designbump,google,igoogle,live,myaol,yahoobkm',
	services_expanded : ''
}







//function initAutocompleteAddress(sourceId, resultsId){
//	var oAutoCompleteDSInfo = new YAHOO.widget.DS_XHR('/address_proxy.php', ['results', 'full_address']);
//	oAutoCompleteDSInfo.scriptQueryParam = "address";
//	oAutoCompleteDSInfo.scriptQueryAppend = "countitem=1&counttype=available";
//
//	var oSearchAutoComp = new YAHOO.widget.AutoComplete(sourceId
//			, resultsId
//			, oAutoCompleteDSInfo);
//	oSearchAutoComp.autoHighlight = false;
//	oSearchAutoComp.animVert = false;
//	oSearchAutoComp.queryDelay = 0;
//	oSearchAutoComp.minQueryLength = 3;
//	oSearchAutoComp.maxResultsDisplayed	= 11;
//	oSearchAutoComp.formatResult = onFormatAddressResult;
//    oSearchAutoComp.itemSelectEvent.subscribe(setGPSCoordinate);
//}

function initAutocompleteAddress(sourceId, resultsId){
    $("#"+sourceId).autocomplete({
        source: function(request,response){
            $.ajax({
                url:"/address_proxy.php?countitem=1&counttype=available&address="+request.term,
                success: function (data) {
                    response($.map(data.results, function(item){
                        return {
                            label: item.full_address,
                            value: item.full_address,
                            data: item
                        }
                    }))
                }

            })
        },
        minLength: 3,
        focus: function(event, ui){
            $('#map_directions_input_lat').val(ui.item.data.lat);
            $('#map_directions_input_lng').val(ui.item.data.lng);
        }
    });
//    var search_in_progress = false;
//    $('#'+sourceId).autocomplete({
//						ajax: "/address_proxy.php?countitem=1&counttype=available&caller=jqueryautocomplete",
//						match: function(typed) {
//                            return true;
//						},
//                        insertText: function(str) {
//                            $('#map_directions_input_lat').val(str.lat);
//                            $('#map_directions_input_lng').val(str.lng);
//                            return str.full_address;
//                        },
//                        template: function(str)
//                        {
//                            return '<li>'+str.full_address+'</li>';//
//                        }
//					});
}

function setGPSCoordinate(sType, aArgs)
{
    var oData = aArgs[2][1];
    //since some the business listing address come from terralink and might not match google map
    //so we are using GPS coordinates to get the directions
    //setting the lat and lng of the address for getting the directions
    $('#map_directions_input_lat').val(oData.lat);
    $('#map_directions_input_lng').val(oData.lng);

}

function onFormatAddressResult(aResultItem, sQuery) {
	var sResult = aResultItem[0];
	var oData = aResultItem[1];
	var sContent;

	if (isObjectShowMore(oData)) {
		if (oData.totalResultsAvailable===0) {
			sContent='No Matches';
		} else {
			if (oData.countType=='showmore') {
				sContent = "Show All Results (" + oData.totalResultsAvailable +")";
			} else if (oData.countType=='available') {
				sContent = "Total Results Available (" + oData.totalResultsAvailable +")";
			} else {
				sContent = "Unknown countType";
			}
		}
		sContent = '<span class="searchSuggestionsCountHint">'+sContent+'</span>';
	} else if (sResult) {
		sContent = sResult;
	} else {
		sContent = "";
	}
	return sContent;
}

function isObjectShowMore(oItem){
	return (typeof oItem.totalResultsAvailable != "undefined");
}


function init_map_directions(){


	// map driving directions
	$('#map_directions_button_to').click(function(){
		if($('#map_directions_field_from').css('display')!='none'){
			$('#map_directions_field_from').slideUp('slow');
		}
		if($('#map_directions_field_to').css('display')=='none'){
			$('#map_directions_field_to').slideDown('slow');
			$('#map_directions_input_to').get(0).focus();
		}else{
			$('#map_directions_field_to').slideUp('slow');
		}
	});
	$('#map_directions_button_from').click(function(){
		if($('#map_directions_field_to').css('display')!='none'){
			$('#map_directions_field_to').slideUp('slow');
		}
		if($('#map_directions_field_from').css('display')=='none'){
			$('#map_directions_field_from').slideDown('slow');
			$('#map_directions_input_from').get(0).focus();
		}else{
			$('#map_directions_field_from').slideUp('slow');
		}
	});

	$('#map_directions_submit_from').click(function(){
		var newUrl = $('#map_directions_url').val()+'?origin='+oBusiness.full_address+'&destination='+$('#map_directions_input_from').val()+'&lat='+$('#map_directions_input_lat').val()+'&lng='+$('#map_directions_input_lng').val()+'&direction=to';
		window.location = newUrl;
	});
	$('#map_directions_submit_to').click(function(){
		var newUrl = $('#map_directions_url').val()+'?origin='+$('#map_directions_input_to').val()+'&destination='+oBusiness.full_address+'&lat='+$('#map_directions_input_lat').val()+'&lng='+$('#map_directions_input_lng').val()+'&direction=from';
		window.location = newUrl;
	});

}




var homepage_articles = {
	data : Array(),
	current_index : 0,
	cms_url : '',
	homepage_articles_image_click_handler : false,

	init : function (data, url){
		this.data = data;
		this.cms_url = url;
		$('#homepage_articles_increment_button img').click(function(){homepage_articles.increment();});
		$('#homepage_articles_decrement_button img').click(function(){homepage_articles.decrement();});
	},

	increment : function(){
		var new_index = this.current_index + 1;
		// increments to first in list if list is finished
		if(new_index >= this.data.length){
			new_index = 0;
		}
		this.current_index = new_index;
		this.render();
	},

	decrement : function(){
		var new_index = this.current_index - 1;
		// decrements to last in list
		if(new_index < 0){
			new_index = this.data.length-1;
		}
		this.current_index = new_index;
		this.render();
	},

	render : function(){
		// title
		$('#homepage_articles_panel .head a').each(function(){
			$(this).attr('href', '/articles/'+homepage_articles.data[homepage_articles.current_index].nid+'/'+homepage_articles.data[homepage_articles.current_index].url_friendly+'/');
			$(this).html(homepage_articles.data[homepage_articles.current_index].field_homepage_title[0].value);
		});

		// description
		var url = '/articles/'+homepage_articles.data[homepage_articles.current_index].nid+'/'+homepage_articles.data[homepage_articles.current_index].url_friendly+'/';

		var morelink = ' ...<a href="'+url+'">more</a>';
		$('#homepage_articles_panel .txt').html(homepage_articles.data[homepage_articles.current_index].field_homepage_description[0].value+morelink);

		// background-image
		$('#homepage_articles_image').css('background-image', 'url('+homepage_articles.cms_url+homepage_articles.data[homepage_articles.current_index].field_homepage_background[0].filepath+')');

		if(this.homepage_articles_image_click_handler){
			$('#homepage_articles_image').unbind('click', this.homepage_articles_image_click_handler);
		}
		this.homepage_articles_image_click_handler = $('#homepage_articles_image').bind('click', function(){window.location=url;});

		var selected_led = (((homepage_articles.current_index)%6));

		var count = 0;
		$('#homepage_articles_navigation li.homepage_articles_iteration_led img').each(function(){
            $(this).bind('click', {index:count}, homepage_articles.show_frame);

			if(count===selected_led){
				$(this).attr('src', $(this).attr('src').replace('-normal', '-hover'));
			}else{
				$(this).attr('src', $(this).attr('src').replace('-hover', '-normal'));
			}
			count++;
		});
	},

	show_frame : function(event){
        var num = event.data.index;
		homepage_articles.current_index = num*1;
		homepage_articles.render();
	},

	click_through : function(num){
		var index = (Math.floor(homepage_articles.current_index/6)*6+num*1)*1;
		if(typeof homepage_articles.data[index] === 'undefined') return;
		var article_id = homepage_articles.data[index].nid;
        var url_friendly = homepage_articles.data[index].url_friendly;
		window.location = '/articles/'+article_id+'/'+url_friendly+'/';
	}



}


var show_all_flags_timeout = false;

// hiding google map flags when hovering a lsiting detail
function hide_other_flags(id){
	var marker;
	if(typeof markertools ==='undefined' || typeof googlemap === 'undefined') return;
	if(show_all_flags_timeout!==false){
		clearTimeout(show_all_flags_timeout);
		show_all_flags_timeout = false;
	}
	if(oSearchResult.length && oSearchResult[id*1]){
		for(var i=0; i<markertools._all_markers.length; i++){
			marker = markertools._all_markers[i];
			if(marker!==null && typeof marker.isHidden === 'function'){
				if(i*1!==id*1){
					// hide the marker
					marker.hide();
				}else{
					if(marker.isHidden()){
						marker.show();
					}
				}
			}
		}
	}
}

// showing all google map flags when un-hovering lsiting detail
function show_all_flags(){

	var show_all_flags_do = function(){
		var marker;
		if(typeof markertools ==='undefined' || typeof googlemap === 'undefined') return;
		for(var i=0; i<markertools._all_markers.length; i++){
			marker = markertools._all_markers[i];
			if(marker!==null && typeof marker.isHidden === 'function'){
				if(marker.isHidden()){
					marker.show();
				}
			}
		}
	}

	show_all_flags_timeout = setTimeout(show_all_flags_do, 500);

}

/**
 * Register events to hide other flags when a listing result is hovered
 */
function register_hide_other_flags(){
	var count;

	// search results
	count = 0;
	$('#resultspane .results li.has_coords').each(function(){
		var i = count*1;
		$(this).hover(function(){
			hide_other_flags(i);
		}, function(){
			show_all_flags();
		});
		count++;
	});

	// view large map
	count = 0;
	$('#extra .results li.has_coords').each(function(){
		var i = count*1;
		$(this).hover(function(){
			hide_other_flags(i);
		}, function(){
			show_all_flags();
		});
		count++;
	});
}

