var	obj_image_index		= {};
/* 
 * Cross-browser event handling, by Scott Andrew
 */
function addEvent(element, eventType, lamdaFunction, useCapture) {
    if (element.addEventListener) {
        element.addEventListener(eventType, lamdaFunction, useCapture);
        return true;
    } else if (element.attachEvent) {
        var r = element.attachEvent('on' + eventType, lamdaFunction);
        return r;
    } else {
        return false;
    }
}

/* 
 * Kills an event's propagation and default action
 */
function knackerEvent(eventObject) {
    if (eventObject && eventObject.stopPropagation) {
        eventObject.stopPropagation();
    }
    if (window.event && window.event.cancelBubble ) {
        window.event.cancelBubble = true;
    }
    
    if (eventObject && eventObject.preventDefault) {
        eventObject.preventDefault();
    }
    if (window.event) {
        window.event.returnValue = false;
    }
}

// Save listing
function save_listing(link, val_ref, address) 
{
	link.firstChild.nodeValue = 'Adding...';

	$.post (
		'/account/save-listing',
		{ val_ref: val_ref, address: address},
		function(resp) {
			link.firstChild.nodeValue = 'Added to My Zoodle! Click to view.';
			link.href = '/account/my-property-listings';
			link.onclick = null;
			link.className += link.className ? ' added' : 'added';
		}
	);

	return false;
}

/* 
 * Safari doesn't support canceling events in the standard way, so we must
 * hard-code a return of false for it to work.
 */
function cancelEventSafari() {
    return false;        
}

/* 
 * function used in the agent-of-vendor
 * pull the info of agent from hidden field to the name, email and number fied
 */
function loadAgent(){
	var radioSelection = document.vendorAgent.agent_vendor;
	for (i=0; i<radioSelection.length; i++){
		if(radioSelection[i].checked == true && radioSelection[i].value == 1){		
			document.getElementById('sender_name').value = document.getElementById('agent_name').value;
			document.getElementById('sender_email').value = document.getElementById('agent_email').value;
			document.getElementById('sender_phone').value = document.getElementById('agent_phone').value;
		}
		else if(radioSelection[i].checked == true && radioSelection[i].value == 2){
			document.getElementById('sender_name').value = '';
			document.getElementById('sender_email').value = '';
			document.getElementById('sender_phone').value = '';
		}
	}
	
}
/* 
 * Cross-browser style extraction, from the JavaScript & DHTML Cookbook
 * <http://www.oreillynet.com/pub/a/javascript/excerpt/JSDHTMLCkbk_chap5/index5.html>
 */
function getElementStyle(elementID, CssStyleProperty) {
    var element = document.getElementById(elementID);
    if (element.currentStyle) {
        return element.currentStyle[toCamelCase(CssStyleProperty)];
    } else if (window.getComputedStyle) {
        var compStyle = window.getComputedStyle(element, '');
        return compStyle.getPropertyValue(CssStyleProperty);
    } else {
        return '';
    }
}

/* 
 * CamelCases CSS property names. Useful in conjunction with 'getElementStyle()'
 * From <http://dhtmlkitchen.com/learn/js/setstyle/index4.jsp>
 */
function toCamelCase(CssProperty) {
    var stringArray = CssProperty.toLowerCase().split('-');
    if (stringArray.length == 1) {
        return stringArray[0];
    }
    var ret = (CssProperty.indexOf("-") == 0)
              ? stringArray[0].charAt(0).toUpperCase() + stringArray[0].substring(1)
              : stringArray[0];
    for (var i = 1; i < stringArray.length; i++) {
        var s = stringArray[i];
        ret += s.charAt(0).toUpperCase() + s.substring(1);
    }
    return ret;
}

/*
 * Disables all 'test' links, that point to the href '#', by Ross Shannon
 */
function disableTestLinks() {
  var pageLinks = document.getElementsByTagName('a');
  for (var i=0; i<pageLinks.length; i++) {
    if (pageLinks[i].href.match(/[^#]#$/)) {
      addEvent(pageLinks[i], 'click', knackerEvent, false);
    }
  }
}

/* 
 * Cookie functions
 */
function createCookie(name, value, days) {
    var expires = '';
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        var expires = '; expires=' + date.toGMTString();
    }
    document.cookie = name + '=' + value + expires + '; path=/';
}

function readCookie(name) {
    var cookieCrumbs = document.cookie.split(';');
    var nameToFind = name + '=';
    for (var i = 0; i < cookieCrumbs.length; i++) {
        var crumb = cookieCrumbs[i];
        while (crumb.charAt(0) == ' ') {
            crumb = crumb.substring(1, crumb.length); /* delete spaces */
        }
        if (crumb.indexOf(nameToFind) == 0) {
            return crumb.substring(nameToFind.length, crumb.length);
        }
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, '', -1);
}

/**
 * Add in_array function to Array prototype
 */
Array.prototype.in_array = function(p_val) {
	for(var i = 0, l = this.length; i < l; i++) {
		if(this[i] == p_val) {
			return true;
		}
	}
	return false;
}

function my_price(){
		$("#price-div > #min_price").attr("disabled","disabled");
	$("#price-div > #max_price").attr("disabled","disabled");
	$("#min_price_input").removeAttr("disabled");
	$("#max_price_input").removeAttr("disabled");
	$("#my_price_div").show();
	$("#normal_dropdown_div").hide();
}

function normal_dropdown(){
	$("#min_price_input").val("0");
	$("#max_price_input").val("0");
	$("#min_price_input").attr("disabled","disabled");
	$("#max_price_input").attr("disabled","disabled");
	$("#price-div > #min_price").removeAttr("disabled");
	$("#price-div > #max_price").removeAttr("disabled");
	$("#my_price_div").hide();
	$("#normal_dropdown_div").show();
}

function check_term(){
	if($("#term_condition:checked").val() == 1){
		return true;
	}
	else{
		alert('Terms and Conditions must be checked before you can register');
	}
	return false;
}

/**
 * Popups
 */
$(document).ready(function()
{
	//Popup windows, just add popup class to any link (replaces the old target=_blank)
	$('a.popup').bind('click',function(){
		window.open(this.href);
		return false;
	});
	//my price input
	if($("#ownPrice")){
	    $("#ownPrice").click(my_price);
	}
	if($("#normal_dropdown")){
	    $("#normal_dropdown").click(normal_dropdown);
	}
	
	$("#line_chart > ul").tabs();
	$("#basic_bar_chart > ul").tabs();
});

/**
 * Load Event 
 */
function addLoadEvent(func) 
{
	var oldonload = window.onload;
	
	if(typeof window.onload != 'function') {
		window.onload = func;
	} 
	else {
		window.onload = function() {
			if(oldonload) oldonload();
			func();
		}
	}
}

/**
 * Append stylesheet
 */
function appendStylesheet(href, media) 
{
	var link = document.createElement('link');
	
	link.setAttribute('rel', 'stylesheet');
	link.setAttribute('type', 'text/css');
	link.setAttribute('href', href);
	link.setAttribute('media', media);

	document.getElementsByTagName('head')[0].appendChild(link);
}

/**
 * Loader animation 
 */
function init_loader(target)
{
	$(target).append('<div class="loader"><img src="/images/loader-white.gif" width="32" height="32" alt="loading" /><br />Loading</div>');
}

function kill_loader(target)
{
	$('.loader', target).remove();
}

/**
 * Redirects
 */ 
function redirect (url) 
{
	location.href = url;
	return false;
}

function confirm_redirect (url, message) 
{
	if(confirm(message)) redirect(url);
	return false;
}

/**
 * Initialize standard tabs
 *
 * There is a workaround in this where dynamic
 * content loaded by javascript will have issues
 * loading if the div is hidden with display: none. 
 * To get around this the content divs are set to 
 * height: 0px; so they are initially hidden by css. 
 * They are then faded out (which has no effect 
 * on the content) and then set to height: 100%. 
 * This seems to solve any issues
 */
function initialize_tab_menu()
{	
	if($('.anchors').length) {
		// Hide non active
		$('.anchors li:not(.on) a').each(function(){
			$($(this).attr('href')).fadeOut(function(){$(this).css({height: '100%'})});
		});
		// Display active
		$($('.anchors li.on a').attr('href')).css({height: '100%'});
		// Add click handlers
		$('.anchors a').each(function(){
			if($(this).attr('class') != 'no-click') {
				$(this).click(function() {
					$($('a', $('.anchors .on').removeClass()).attr('href')).hide();
					$($(this).attr('href')).show();
					$(this).parent().addClass('on');
					return false;
				});
			}
		});
	}
}

function chart_test(site_url, question_sequence, question_area, question_txt, question_area_txt, question_type, chart_type, relation_id, chart_id){
	var rnd982g = Math.random();
	document.getElementById('charts'+chart_id).SetVariable ( "update_url", site_url+'/community/report-chart?relation_id='+relation_id+'&format=xml&chart='+chart_type+'&uniq='+rnd982g+'&question_sequence='+question_sequence+'&question_area='+question_area+'&question_type='+question_type+'&chart_type='+chart_type+'&question_txt='+question_txt+'&chart_id='+chart_id);
}
function load_bar_chart(site_url, question_type, chart_type, relation_id, chart_id){
	var rnd982g = Math.random();
	document.getElementById('charts'+chart_id).SetVariable ( "update_url", site_url+'/community/report-chart?relation_id='+relation_id+'&format=xml&chart='+chart_type+'&question_type='+question_type+'&chart_type='+chart_type+'&uniq='+rnd982g);
}

