/////////////////////////////////////////////////////////////////////////////////////////////////////////
// Browser information object
var BrowserDetect={init:function(){this.browser=this.searchString(this.dataBrowser)||"An unknown browser";this.version=this.searchVersion(navigator.userAgent)||this.searchVersion(navigator.appVersion)||"an unknown version";this.OS=this.searchString(this.dataOS)||"an unknown OS";},searchString:function(data){for(var i=0;i<data.length;i++){var dataString=data[i].string;var dataProp=data[i].prop;this.versionSearchString=data[i].versionSearch||data[i].identity;if(dataString){if(dataString.indexOf(data[i].subString)!=-1)
return data[i].identity;}
else if(dataProp)
return data[i].identity;}},searchVersion:function(dataString){var index=dataString.indexOf(this.versionSearchString);if(index==-1)return;return parseFloat(dataString.substring(index+this.versionSearchString.length+1));},dataBrowser:[{string:navigator.userAgent,subString:"Chrome",identity:"Chrome"},{string:navigator.userAgent,subString:"OmniWeb",versionSearch:"OmniWeb/",identity:"OmniWeb"},{string:navigator.vendor,subString:"Apple",identity:"Safari",versionSearch:"Version"},{prop:window.opera,identity:"Opera"},{string:navigator.vendor,subString:"iCab",identity:"iCab"},{string:navigator.vendor,subString:"KDE",identity:"Konqueror"},{string:navigator.userAgent,subString:"Firefox",identity:"Firefox"},{string:navigator.vendor,subString:"Camino",identity:"Camino"},{string:navigator.userAgent,subString:"Netscape",identity:"Netscape"},{string:navigator.userAgent,subString:"MSIE",identity:"Explorer",versionSearch:"MSIE"},{string:navigator.userAgent,subString:"Gecko",identity:"Mozilla",versionSearch:"rv"},{string:navigator.userAgent,subString:"Mozilla",identity:"Netscape",versionSearch:"Mozilla"}],dataOS:[{string:navigator.platform,subString:"Win",identity:"Windows"},{string:navigator.platform,subString:"Mac",identity:"Mac"},{string:navigator.userAgent,subString:"iPhone",identity:"iPhone/iPod"},{string:navigator.platform,subString:"Linux",identity:"Linux"}]};
BrowserDetect.init();

var ajaxWaitingImage = '<img src="/images/ajax-loader.gif" width="43" height="11" />';
var the_helper_cookie;

function isDefined( variable ) {
    return (typeof(variable) == "undefined")?  false: true;
}
function timedRedirection(url, second) {
	var time = second * 1000;
	var t = setTimeout("location.href='" + url + "';", time);
}

function showHelper() {
	$("#collapse").show();
	$("#expand").hide();
	setCookie("the_helper_cookie", "show"); 
}

function hideHelper() {
	$("#collapse").hide();
	$("#expand").show();
	setCookie("the_helper_cookie", "hide");
}

function limitChars(textid, limit, infodiv) {
	var text = $('#'+textid).val(); 
	var textlength = text.length;
	if(textlength > limit) {
		$('#' + infodiv).html('You cannot write more then '+limit+' characters!');
		$('#'+textid).val(text.substr(0,limit));
		return false;
	} else {
		$('#' + infodiv).html('You have '+ (limit - textlength) +' characters left.');
		return true;
	}
}
function limitCharacter(text, limit, infodiv, id) {
	

	var textlength = text.length;
	if(textlength > limit) {
		$('#' + infodiv).html('0');
		$('#twitter #comment-textarea-0').val( text.substr(0,limit) );
		return false;
	} else {
		$('#' + infodiv).html(''+ (limit - textlength) +'');
		return true;
	}
}
function limitChar(text, limit) {
	return text.substr(0,limit);
}

function limitWord(string, limit){
	var str = "";
	var output = string.split(" ");
	for(var i=0; i<limit; i++){
		if( isDefined(output[i]) )
		str += output[i] + " ";
	}
	return trim(str);
}
function toggle(id) {
	var current = $("#" + id).css("display"); 
 	if( current == "block" ) {
  		$("#" + id).css("display", "none");
 	} else {
  		$("#" + id).css("display", "block");
 	}
}

/**
*  Javascript trim, ltrim, rtrim
*  http://www.webtoolkit.info/
**/
function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}



function addslashes( str ) {
    // Escapes single quote, double quotes and backslash characters in a string with backslashes  
    // 
    // version: 907.119
    // discuss at: http://phpjs.org/functions/addslashes
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +   improved by: marrtins
    // +   improved by: Nate
    // +   improved by: Onno Marsman
    // +   input by: Denny Wardhana
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: addslashes("kevin's birthday");
    // *     returns 1: 'kevin\'s birthday'
 
    return (str+'').replace(/([\\"'])/g, "\\$1").replace(/\u0000/g, "\\0");
}

function setCookie(c_name,value,expiredays) {
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}
function getCookie(c_name) {
	if (document.cookie.length>0) {
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1) { 
			c_start=c_start + c_name.length+1; 
			c_end=document.cookie.indexOf(";",c_start);
			
			if (c_end==-1) 	c_end=document.cookie.length;
			
			return unescape(document.cookie.substring(c_start,c_end));
		} 
	}
	return "";
}
function isEmail(string) {
//	return true;
	var emailfilter = /^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i;
	var result = emailfilter.test(string);
	return result;
}               

function isProper(string) {
   if (!string) return false;
   var iChars = "!\"$%^&*()+=`':;~#/?.>,<|\\/";
   
   for (var i = 0; i < string.length; i++) {
	  if (iChars.indexOf(string.charAt(i)) != -1)
		 return false;
   }
   return true;
} 

function ucfirst( str ) {
    str += '';
    var f = str.charAt(0).toUpperCase();
    return f + str.substr(1);
}

function openPopupUsingUrl(url) {
	$.fn.colorbox({href:url, iframe:true, width:900, height:500, open:true, opacity:0.8, transition:'elastic'});
}

function getForm(name) {
	var ajaxUrl = '/form/' + name;
	$.get(ajaxUrl, function(data) {
		return data;
	});		
}

function scrollToTop (speed) {
	if (!speed) speed = "slow";
	$("html, body").animate({scrollTop:"0px"},speed);
	//$(window).animate({scrollTop:"0px"},speed);
}

function loadGoogleMapScript(){
  	var script = document.createElement("script");
  	script.type = "text/javascript";
  	script.src = "http://maps.google.com/maps?file=api&v=2.x&key=" + GOOGLE_MAP_API + "&async=2";
	document.body.appendChild(script);

	var script2 = document.createElement("script");
  	script2.type = "text/javascript";
  	script2.src = "http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/1.1/src/markermanager_packed.js";
	document.body.appendChild(script2);	
}

function substr (f_string, f_start, f_length) {
    // Returns part of a string  
    // 
    // version: 908.406
    // discuss at: http://phpjs.org/functions/substr
    // +     original by: Martijn Wieringa
    // +     bugfixed by: T.Wild
    // +      tweaked by: Onno Marsman
    // *       example 1: substr('abcdef', 0, -1);
    // *       returns 1: 'abcde'
    // *       example 2: substr(2, 0, -6);
    // *       returns 2: ''
    f_string += '';

    if (f_start < 0) {
        f_start += f_string.length;
    }

    if (f_length == undefined) {
        f_length = f_string.length;
    } else if (f_length < 0){
        f_length += f_string.length;
    } else {
        f_length += f_start;
    }

    if (f_length < f_start) {
        f_length = f_start;
    }

    return f_string.substring(f_start, f_length);
}
function searchArray(array, string, wholeStringMode){
	if( isDefined(wholeStringMode) && wholeStringMode==true){
		for(var i=0; i<array.length; i++){
			if(array[i]==string) return true;	
		}
		return false;
	}else{
		str = array.toString();
		if(str.indexOf(string)!=-1) return true;
		else return false;
	}
}

function stripslashes (str) {
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +      fixed by: Mick@el
    // +   improved by: marrtins
    // +   bugfixed by: Onno Marsman
    // +   improved by: rezna
    // +   input by: Rick Waldron
    // +   reimplemented by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: stripslashes('Kevin\'s code');
    // *     returns 1: "Kevin's code"
    // *     example 2: stripslashes('Kevin\\\'s code');
    // *     returns 2: "Kevin\'s code"
    return (str+'').replace(/\\(.?)/g, function (s, n1) {
        switch (n1) {
            case '\\':
                return '\\';
            case '0':
                return '\0';
            case '':
                return '';
            default:
                return n1;
        }
    });
}

function renderDate(prefixId, destinationId){
	var strdate = "";
	
	if( $("#" + prefixId + "dd").val() != "" && $("#" + prefixId + "mm").val() != "" && $("#" + prefixId + "yyyy").val() != "" )
	strdate = $("#" + prefixId + "dd").val() + "/" + $("#" + prefixId + "mm").val() + "/" + $("#" + prefixId + "yyyy").val();
	
	$("#" + destinationId ).val(strdate);
}

function renderOptionDate(prefixId, destinationId){
	var d = $("#" + destinationId).val();
	dArray = d.split("/");
	$("#" + prefixId + "dd").val( dArray[0] );
	$("#" + prefixId + "mm").val( dArray[1] );
	$("#" + prefixId + "yyyy").val( dArray[2] );
	
}
function renderDateFromDb(prefixId, dateStr){
	var d = dateStr;
	dArray = d.split("-");
	$("#" + prefixId + "dd").val( dArray[2] );
	$("#" + prefixId + "mm").val( dArray[1] );
	$("#" + prefixId + "yyyy").val( dArray[0] );
}

function getJoinedCommunity( containerId, selectedValue ) {
	if( !isDefined(selectedValue) ) selectedValue = "";
	$.get("/json-data/joined-community.json", function(data) {
		response = eval("(" + data + ")");
		var output = "";
		output += "<option value=''>Please select</option>";			
		for( var i=0; i<response.data.length; i++) {
			if( typeof(response.data[i].id) != "undefined") {
				output += "<option ";
				output += "value='" + response.data[i].community_id + "'";
				if( selectedValue == response.data[i].community_id ) output += " selected='selected'";
				output += ">";
				output += ucfirst( response.data[i].community );
				output += "</option>";
			}
		}
		$("#" + containerId).html( output );
	});
}


function getOwnedBusiness(containerId, selectedValue) {
	if( !isDefined(selectedValue) ) selectedValue = "";
	$.get("/json-data/my-business.json", function(data) {
		response = eval("(" + data + ")");
		var output = "";
		output += "<option value=''>Please select</option>";			
		for( var i=0; i<response.data.length; i++) {
			if( typeof(response.data[i].id) != "undefined") {
				output += "<option ";
				output += "value='" + response.data[i].id + "'";
				if( selectedValue == response.data[i].id ) output += " selected='selected'";
				output += ">";
				output += ucfirst( response.data[i].title );
				output += "</option>";
			}
		}
		$("#" + containerId).html( output );
	});
}
function redirectUrlFromDropDown(id){
	var val = $("#" + id).val();
	$.each($("#" + id + ">option"), function(){
		if( isDefined($(this).attr("url")) ){
			if( $(this).val() == val) location.href = $(this).attr("url");
		}
	});
}

function generateDropDownCountry( noNextButton, id ){
	$.get('/json-data/list-country.json', function(data){
		if( isDefined(id) ) var output = "<select id='" + id + "'>";
		else var output = "<select id='country'>";
		
		output += "<option></option>"
		countryJson = eval("(" + data + ")");
		for(var i=0; i<countryJson.length; i++){
			if( countryJson[i].id == "253" )
				output += "<option value='" + countryJson[i].id + "' selected='selected'>" + countryJson[i].country + "</option>";
			else
				output += "<option value='" + countryJson[i].id + "'>" + countryJson[i].country + "</option>";
		}
		output += '</select>';
		if( !isDefined(noNextButton) || noNextButton!=true)
		output += '<br /><input onclick="displayCommunity( $(\'#country\').val() );" value="Next" class="next-button" type="button" />';
		$("#country-select").html( output );
		showPanel(1);
	});
}
function ucwords (str) {
    // Uppercase the first character of every word in a string  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/ucwords
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Waldo Malqui Silva
    // +   bugfixed by: Onno Marsman
    // *     example 1: ucwords('kevin van zonneveld');
    // *     returns 1: 'Kevin Van Zonneveld'
    // *     example 2: ucwords('HELLO WORLD');
    // *     returns 2: 'HELLO WORLD'
    return (str+'').replace(/^(.)|\s(.)/g, function ( $1 ) { return $1.toUpperCase( ); } );
}


$("#map-toggler").click(function() {
	$("#maps").toggle();
	$("#map-toggler span").toggle();
});

function array_search (needle, haystack, argStrict) {
    // Searches the array for a given value and returns the corresponding key if successful  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/array_search
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: array_search('zonneveld', {firstname: 'kevin', middle: 'van', surname: 'zonneveld'});
    // *     returns 1: 'surname'

    var strict = !!argStrict;
    var key = '';

    for (key in haystack) {
        if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
            return key;
        }
    }

    return false;
}

function dash( input ){
	input = input.toLowerCase();
	input = input.replace(/ /, "-");
	return input;	
}

function debug( text ){
	try{
		console.log(text);
	}catch(e){
		alert(text);	
	}
}

function setSize() {
	w = $(window).width();
	h = $(window).height();
	
	$('#bgImage').css("width",10*w+'px'); // made the width of bgImage bigger than it should be.
	if (h>600) { $('#black-bg').css("height",h+'px'); }

	//console.log(w+','+h);
	
	r = w/h;
	if (r > ratio) {
		slideWidth = w;
		slideHeight = w/ratio;
	} else {
		slideHeight = h;
		slideWidth = h*ratio;
	}
		
	$("#container img").attr("width",slideWidth);
	$("#container img").attr("height",slideHeight);
		
	$('#container').css("margin-left",-slideWidth/2);
	$('#container').css("margin-top",-slideHeight/2);
		
	$('#bgImage').css("margin-left",-(page-1)*slideWidth);
	
}


function changeBackground(file){
	if(!isDefined(file) && getCookie("background")!=""){
		$("#loading").toggle();
		$image = $("<img />");
		$image.attr("src", "/images/profile/" + getCookie("background"));
		$image.css("height", $(window).height());
		$image.css("width", $(window).width());		
		$('#bgImage').text($image);
		var html = "<img src='/images/profile/" + getCookie("background") + "' />";
		$('#bgImage').html(html);			
		$("#loading").toggle();
	}else{
		$("#loading").toggle();
		$image = $("<img />");
		$image.attr("src", "/images/profile/" + file);
		$image.css("height", $(window).height());
		$image.css("width", $(window).width());		
		$('#bgImage').html($image);
		$("#loading").toggle();
		setCookie("background", file);
	}
}
function changeImageOnGallery( src, label ){
	$("#main-gallery-image").attr("src", "/images/loading-heart.gif");

	setTimeout(function(){
		$("#main-gallery-image").attr("src", src);
		$("#main-gallery-label").html(label);	
	},1000);
}
function addslashes (str) {
    // Escapes single quote, double quotes and backslash characters in a string with backslashes  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/addslashes
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +   improved by: marrtins
    // +   improved by: Nate
    // +   improved by: Onno Marsman
    // +   input by: Denny Wardhana
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: addslashes("kevin's birthday");
    // *     returns 1: 'kevin\'s birthday'
 
    return (str+'').replace(/([\\"'])/g, "\\$1").replace(/\u0000/g, "\\0");
}

function createImageBlock( data, size ){
	var output = "";
	
	if( size == 20 )	
	output += '<div class="align-left pointer" onclick="changeImageOnGallery(\''+data.image+'?crop(300x300)\', \'' + addslashes(data.label) + '\');">';
	else
	output += '<div class="align-left">';
	
		output += '<input type="hidden" value="' + data.id + '" name="ids[]" />';
		output += '<img src="' + data.image + '?crop(' + size + 'x' + size + ')" width="'+size+'" height="'+size+'" style="margin-right:3px; margin-bottom:3px;" />';
	output += '</div>';
	return output;
}
function initGallery( id ){
	var url = '/json-data/business-gallery.json?id=' + id;
	$.get(url, function(data){
		json = eval("(" + data + ")");
		data = json.data;
		var output = "";
		if( data.length>0 ){
			// show big image
			output += '<div style="height:300px; width:300px;">';
			//output += '<div class="img-round-mask-big"></div>';
			output += '<img src="' + data[0].image + '?crop(300x300)" id="main-gallery-image" /><br />';
			output += '</div>';
			output += '<div class="bg-cream round">';
				output += '<div class="tt-up"></div>';
				output += '<div class="overflow padding15">';
					output += '<div style="padding-top:0px; padding-bottom:5px;" id="main-gallery-label">';				
						output += data[0].label;
					output += '</div>';					
					output += '<div class="clear"></div>';
				
					for(var i=0; i<data.length; i++){
						if( isDefined(data[i].image)){
							output += createImageBlock(data[i], 20);						
						}
					}
				output += '</div>';
			output += '</div>';
			$("#images").html(output);
		}else{
			output += '<div class="img-round-mask-big"></div>';
			output += '<img src="/images/default_business_big.png?crop(300x300)" width="300" height="300" /><br />';
			$("#images").html(output);
		}
	});	
}
function attachRolloverForAvatar(){
	$(".avatar").mousemove(function(e){
		$rollover = $(this).find(".tooltip");
		$rollover.css("left", e.pageX);
		$rollover.css("top", e.pageY-35);				
	});
	$(".avatar").hover(
		function(e){
			$rollover = $(this).find(".tooltip");
			$rollover.css("left", e.pageX);
			$rollover.css("top", e.pageY-35);				
			$rollover.show();
		},
		function(){
			$rollover = $(this).find(".tooltip");	
			$rollover.hide();
		}
	);
}


function setTopArrow() {
	/* calculate the position of cream top arrow */
	var w1 = $("#action-box-trigger-actived .back").width();
	var w2 = $("#action-box-trigger-actived .current-trigger").width();
	/* 20px(container padding-left) + 8px (a margin-left) + w1 + 30px (space dash space) + w2 - w2/2 - 20/2 (half arrow width) = 48 + w1 + w2/2 */
	var arrow_margin_left =  (48 + w1 + w2/2) + 'px';
	$('#action-box-popup .tt-up-big').css('margin-left',arrow_margin_left);
}


function showMsg(msg, color) {
	
	$(" .form-tips").fadeOut();
	//$info.hide();
	$info.removeClass("bg-grey bg-"+memberColor);
	$info.addClass("bg-"+color);
	$info.html('<div class="tt-left"></div>' + msg);		
	$info.fadeIn();
}
function isRFC822ValidEmail(sEmail) {

  var sQtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]';
  var sDtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]';
  var sAtom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+';
  var sQuotedPair = '\\x5c[\\x00-\\x7f]';
  var sDomainLiteral = '\\x5b(' + sDtext + '|' + sQuotedPair + ')*\\x5d';
  var sQuotedString = '\\x22(' + sQtext + '|' + sQuotedPair + ')*\\x22';
  var sDomain_ref = sAtom;
  var sSubDomain = '(' + sDomain_ref + '|' + sDomainLiteral + ')';
  var sWord = '(' + sAtom + '|' + sQuotedString + ')';
  var sDomain = sSubDomain + '(\\x2e' + sSubDomain + ')*';
  var sLocalPart = sWord + '(\\x2e' + sWord + ')*';
  var sAddrSpec = sLocalPart + '\\x40' + sDomain; // complete RFC822 email address spec
  var sValidEmail = '^' + sAddrSpec + '$'; // as whole string
  
  var reValidEmail = new RegExp(sValidEmail);
  
  if (reValidEmail.test(sEmail)) {
    return true;
  }
  
  return false;
}


function validationForm (obj, e) {
	
	var i=0;
	$info = $("#info-" + $(obj).attr("name"));
	//if ( $(obj).attr("validation").length<1) alert( "#info-" + $(obj).attr("name") );
	var value = $(obj).val();
	var rules = $(obj).attr("validation").split("},{");
	var objType = $(obj).attr("type");
	
	while(isDefined(rules[i])) {
		var text = rules[i];		
		text = rtrim(ltrim(text, "{"), "}");			
		rule = text.split("]:[");
		regexp = rule[0].substr(1); /* value: info | empty | email */
		message = rule[1].substr(0, rule[1].length-1);

		if (e == 'focus') {
			if( regexp == "info" ) {
				showMsg(message,'grey');
			}
		} else if (e == 'blur') {			
			if( regexp == "empty" ) {
				if(objType=="checkbox"){
					if( $(obj).attr("checked") == false ){
						showMsg(message, memberColor);
						$(obj).attr("errorState", "1");
					}else{
						$(obj).attr("errorState", "0");
						$info.hide();
						$(".form-tips").fadeIn();
					}
				}else{			
					if(value == "" || isDefined(value)==false) {
						showMsg(message, memberColor);
						$(obj).attr("errorState", "1");
					}else{
						$(obj).attr("errorState", "0");
						$info.hide();
						$(".form-tips").fadeIn();
					}
				}
			} else if( regexp == "mismatchPassword" ){
				var inputId = $(obj).attr("id");
				inputId = inputId.substring(0, inputId.length-1);	
				if( value != $("#" + inputId).val() ){
					showMsg(message, memberColor);
					$(obj).attr("errorState", "1");
				}else{
					$(obj).attr("errorState", "0");
					$info.hide();
					$(".form-tips").fadeIn();
				}
			} else if( regexp == "email" ) {
				if(value !="" && isRFC822ValidEmail(value)==false) {
					showMsg(message,memberColor);
					$(obj).attr("errorState", "1");
				}else{
					$(obj).attr("errorState", "0");
					$info.hide();
					$(".form-tips").fadeIn();
				}
			} else {
				$info.hide();
				$(".form-tips").fadeIn();
			}
		}
		i++;
		if( window.formError == true ){
			//$(".form-tips").fadeIn();			
		}	
		
	}
}

function registrationFormIsError(){
	$("input, select, textarea").each(function(){
		if( isDefined( $(this).attr("validation") ) ){
			$(this).trigger('blur');
		}
	});
	window.formError = false;
	$("input, select, textarea").each(function(){
		if( $(this).attr("errorState") == "1" ){
			window.formError = true;
		}else{
			$(".form-tips").fadeIn();			
		}
	});

	if( window.formError ){
		$info = $('<div id="info-box-for-button">');
		//$info.html("Please check any error(s) before submitting the form."); // put the message on the container
		$info.html(""); // put the message on the container
		$info.fadeIn(); // show the infobox
		$info.attr("class", "info-box-error align-left");
		if( $("form #info-box-for-button").length == 0 ) $("form").append($info);
		else $("form #info-box-for-button").fadeIn();
		return true;
	}else{
		$("form #info-box-for-button").fadeOut();
		return false;	
	}	
}

function formIsError(){
	$("#action-box-form-container input, #action-box-form-container select, #action-box-form-container textarea").each(function(){
		if( isDefined( $(this).attr("validation") ) ){
			$(this).trigger('blur');
		}
	});
	window.formError = false;
	$("#action-box-form-container input, #action-box-form-container select, #action-box-form-container textarea").each(function(){
		if( $(this).attr("errorState") == "1" ){
			window.formError = true;
			resetLockedButton();
		}else{
			$(".form-tips").fadeIn();			
		}
	});

	if( window.formError ){
		$info = $('<div id="info-box-for-button">');
		$info.html(""); // put the message on the container
		//$info.html("Please check any error(s) before submitting the form."); // put the message on the container		
		$info.fadeIn(); // show the infobox
		$info.attr("class", "info-box-error align-left");
		if( $("form #info-box-for-button").length == 0 ) $("form").append($info);
		else $("form #info-box-for-button").fadeIn();
		return true;
	}else{
		$("form #info-box-for-button").fadeOut();
		return false;	
	}
}

function createMediumItem( data, mode ){
	var output = '';
	var id = data.id;
	var image = data.image + "?crop(140x140)";
	var name = data.title;
	var location = ucfirst( data.community.region_name ) + " - " + ucfirst( data.community.community );
	var url = data.url;
	var color = data.color;
	output += '<div class="avatar140 avatar align-left" id="item-' + id + '"><a href="'+url+'">';
	output += '		<div class="img-round-mid">';
	output += '			<div class="img-round-mask-mid"></div>';
	output += '      	<img src="' + image + '"></div>';
	output += '    </a>';
	output += '    <div class="color-bar round bg-' + color + '">';
	output += '      <div class="tt-up"></div>';
	output += '    <div class="color-bar-inner">' + name + '</div>';
	output += '      </div>';
	output += '  </div>			';
	return output;
}

function createSmallItem( data, mode ){
	var output = '';
	var id = data.id;
	var image = data.image + "?crop(48x48)";
	var name = data.title;
	var location = ucfirst( data.community.region_name ) + " - " + ucfirst( data.community.community );
	var url = data.url;
	var color = data.color;
	
	return data.avatar;
}

function getFlashMovie(movieName) {
	var isIE = navigator.appName.indexOf("Microsoft") != -1;
	return (isIE) ? window[movieName] : document[movieName];
}

function addMarkerToMap(flash, str) {
	getFlashMovie(flash).sendToActionscript(str);
}

function replacer(key, value) {
	if (typeof value === 'number' && !isFinite(value)) {
		return String(value);
	}
	return value;
}

function highlightMarker(flash, id){
	//alert( flash + " " + str);
	getFlashMovie(flash).sendToActionscript_2(id);
}

function createPromotionEventList(data, color){
	var output = "";
	//output += '<h3 class="margin-top-20  font-14">' + data.start_date + '</h3>';
	var tmp = data.start_date;
	tmp = tmp.split(" ");
	day = tmp[0];
	month = tmp[1].toUpperCase();
	output += '<div class="overflow">';
		output += '<div class="align-left">';
			//output += '<img src="/images/assets/feed-action/feed_event_'+ color+'.png?resize(48x48)" />';						
			if(data.object_type == "event" )
				output += '<div style="width:48px; height:48px; background-image: url(\'/images/assets/event/event_listing_'+ color+'.png?resize(48x48)\'); background-repeat:no-repeat; font-size:24px; font-weight:bold; padding-left:7px; padding-top:5px; color:white;">' + day + '<div class="font-12" style="margin-top:-2px;">' + month + '</div></div>';				
			else if( data.object_type == "promotion" )
				output += '<img src="/images/assets/promotion/promotion_listing_'+ color+'.png?resize(48x48)" />';
		output += '</div>';
		output += '<div class="align-left bg-cream round" style="width:400px; margin-bottom:10px; margin-left:-7px;">';
			output += '<div class="tt-left"></div>';		
			output += '<div class="padding5">';
				output += '<strong><a href="' + data.link + '">' + data.title + '</a></strong>';
				output += '<div style="margin-top:3px;">Date: ' + data.start_date + ' - ' + data.end_date + '</div>';
				if( isDefined(data.business) )
					output += '<div>Community: ' + ucwords( data.business.community.community ) + '</div>';				
				else
					output += '<div>Community: ' + ucwords( data.community.community ) + '</div>';
			output += '</div>';			
		output += '</div>';
	output += '</div>';
	output += '<div class="clear"></div>';
	return output;
}


function createNotice(data){
	var output = "";
	output += '<div class="notices round bg-cream" style="height:140px;">';
		output += '<img class="notice-clip" src="/images/notices.png" />';
		output += '<div class="padding10">';
			//output += '<strong><a onclick="getNoticeDetail(' + data.id + ')">' + data.title + '</a></strong>';
			output += '<strong><a href="' + data.link + '">' + data.title + '</a></strong>';			
			output += '<div>' + limitWord(data.description, 15) + '</div>';				
		output += '</div>';
	output += '</div>';
	return output;
}

function showConfirmationBox( message, color, timeout ){
	var output = "";
	if( isDefined(timeout) ) id = "timed-confirmation-box";
	else id = "fixed-confirmation-box";
	
	if( !isDefined(color) || color=="" ) color = window.localColor;
	
	output += '<div id="' + id + '" class="round hidden bg-' + color + '">';
		output += '<div class="padding10">' + message + '</div>';
	output += '</div>';
	
	$("#content h3:first").before(output);
	$("#" + id).fadeIn();
	if( isDefined(timeout) ){
		setTimeout(function(){
			$("#timed-confirmation-box").remove();
		}, timeout);
	}
	return output;
}

function showConfirmationBoxForInbox( message, color, timeout, container ){
	var output = "";
	if( isDefined(timeout) ) id = "timed-confirmation-box";
	else id = "fixed-confirmation-box";
	
	if( !isDefined(color) || color=="" ) color = window.localColor;
	
	output += '<div style="margin:10px;" id="' + id + '" class="round hidden bg-' + color + '">';
		output += '<div class="padding10">' + message + '</div>';
	output += '</div>';
	
	$(container).before(output);
	$("#" + id).fadeIn();
	if( isDefined(timeout) ){
		setTimeout(function(){
			$("#timed-confirmation-box").remove();
		}, timeout);
	}
	return output;
}


function processFavorite(id){
	if(confirm("Are you sure about this?")){
		$.get('/json-data/process-favorite.json', {"businessId":id}, function(data){
			response = eval("(" + data + ")");
//			alert(response.message);
//			ActionBox.prototype.close( response, true );
			showConfirmationBox( response.message, "", "3000");
			return false;
		});
	}else{

	}
}		

function showSummaryBlock(id){
	if( id == "summary-community" ){
		$("#summary-favorite-container").hide();				
		$("#summary-community-container").fadeIn();
	}else{
		$("#summary-community-container").hide();
		$("#summary-favorite-container").fadeIn();				
	}
	$(".summary-btn-trigger").removeClass("active");
	$("#" + id).addClass("active");
	
}


function createSummaryBlockList( data ){
	var output = "";
	var color = "";
	type = data.object_type;
	if(type == "general"){
		type = "notice";
		size = "10x19";
	}else if( type == "promotion" || type == "event" ){
		size = "18x18"			
	}else{
		size = "19x10";
	}
	if( data.business_id != "" && data.business_id != "0" ){
		color = data.business.color;
		label = "" + ucwords(data.business.title);
	}
	if( data.community_id != "" && data.community_id != "0" ){
		color = data.community.color;
		label = "" + ucwords(data.community.community);
	}
		
	var vTitle = (data.title.length>28)?data.title.substr(0, 28) + "...":data.title;
	output += '<div class="overflow right-listing" style="border-bottom:1px dotted #333; padding-top:3px; padding-bottom:3px;">';
		output += '<div class="align-left" style="width:15px;">';					
			output += '<img class="align-left" src="/images/assets/feed-action/feed_' + type + '_' + color + '.png?resize(' + size + ')" />';
		output += '</div>';
		output += '<div class="align-left padding10' + color + '" style="margin-left:10px; width:220px;">';					
			output += '<a href="' + data.link + '" class="' + color + ' font-14">' + vTitle + '</a>';
			output += '<div style="margin-top:-5px;"><a href="' + data.link + '" class="font-8 light-grey non-bold uppercase">' + label + '</a></div>';
		output += '</div>';
	output += '</div>';
	output += '<div class="clear"></div>';
	return output;
}
function approveFriendRequest(memberId){
	$.post("/json-data/approve-friend-request.json", {"id":memberId}, function(data){
		response = eval("(" + data + ")");
		$("#approval-container").html(response.message);
		//ActionBox.prototype.close( response, false, function(){ $("#other").html(""); } );
		return false;
	});
}
function approveTeamMember(businessId){
	$.post("/json-data/approve-team-member-request.json", {"id":businessId}, function(data){
		response = eval("(" + data + ")");
		$("#approval-container").html(response.message);
		// ActionBox.prototype.close( response, false, function(){ $("#other").html(""); } );
		return false;
	});
}
function deleteMessage(id){
	cb.create('Are you sure you want to delete this message - by doing this, you will not be able to get it back! ','/json-data/delete-message.json?id=' + id );
	$("#item-" + id).hide();
}

function showPanel(number){
//	alert("changing to: " + number);
	$("#loading").show();
	$(".steps").hide();
	$("#step" + number).show();
	$("#loading").hide();
	
}

function showPanelFavourite(number){
	$("#loading").show();
	$(".stepFavourite").hide();
	$("#stepFavourite" + number).fadeIn(100, function(){
		$("#loading").hide();
	});
}


/* This script and many more are available free online at
The JavaScript Source!! http://javascript.internet.com
Created by: John G. Wang | http://www.csua.berkeley.edu/~jgwang/ */

function checkCapsLock( e, divId ) {
	var myKeyCode=0;
	var myShiftKey=false;
	var myMsg='Caps Lock is On.\n\nTo prevent entering your password incorrectly,\nyou should press Caps Lock to turn it off.';

	// Internet Explorer 4+
	if ( document.all ) {
		myKeyCode=e.keyCode;
		myShiftKey=e.shiftKey;

	// Netscape 4
	} else if ( document.layers ) {
		myKeyCode=e.which;
		myShiftKey=( myKeyCode == 16 ) ? true : false;

	// Netscape 6
	} else if ( document.getElementById ) {
		myKeyCode=e.which;
		myShiftKey=( myKeyCode == 16 ) ? true : false;

	}

	// Upper case letters are seen without depressing the Shift key, therefore Caps Lock is on
	if ( ( myKeyCode >= 65 && myKeyCode <= 90 ) && !myShiftKey ) {
		$("#" + divId).show();
	// Lower case letters are seen while depressing the Shift key, therefore Caps Lock is on
	} else if ( ( myKeyCode >= 97 && myKeyCode <= 122 ) && myShiftKey ) {
		$("#" + divId).show();
	}else{
		$("#" + divId).hide();	
	}
}

function addslashes (str) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +   improved by: marrtins
    // +   improved by: Nate
    // +   improved by: Onno Marsman
    // +   input by: Denny Wardhana
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: addslashes("kevin's birthday");
    // *     returns 1: 'kevin\'s birthday'
 
    return (str+'').replace(/([\\"'])/g, "\\$1").replace(/\u0000/g, "\\0");
}
function str_replace (search, replace, subject, count) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
    // +   improved by: Philip Peterson
    // +   improved by: Simon Willison (http://simonwillison.net)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   bugfixed by: Anton Ongson
    // +      input by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    tweaked by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   input by: Oleg Eremeev
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Oleg Eremeev
    // %          note 1: The count parameter must be passed as a string in order
    // %          note 1:  to find a global variable in which the result will be given
    // *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
    // *     returns 1: 'Kevin.van.Zonneveld'
    // *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
    // *     returns 2: 'hemmo, mars'

    var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
            f = [].concat(search),
            r = [].concat(replace),
            s = subject,
            ra = r instanceof Array, sa = s instanceof Array;
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }

    for (i=0, sl=s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j=0, fl=f.length; j < fl; j++) {
            temp = s[i]+'';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length-s[i].length)/f[j].length;}
        }
    }
    return sa ? s : s[0];
}
function linkify(text){
    if (text) {
        text = text.replace(
            /((https?\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi,
            function(url){
                var full_url = url;
                if (!full_url.match('^https?:\/\/')) {
                    full_url = 'http://' + full_url;
                }
                return '<a href="' + full_url + '" target="_blank">' + url + '</a>';
            }
        );
    }
    return text;
}


jQuery.fn.lockSubmit = function(options) {

	//Default text to change submit button too
	var settings = jQuery.extend({
		submitText: null,
		onAddCSS: null,
		onClickCSS: null
	}, options);

	//add CSS to this button
	if(settings.onAddCSS) {	this.addClass(settings.onAddCSS); }

	return this.click(function(e) {		

		//Hide current submit and insert a dummy submit which is disabled. The reason for doing this and not just disabling the normal submit, is that in some browsers the disabled submit will stop the form being submited at all.

		targetselect = jQuery(this);

		targetselect.hide();
		
		//new buttons value
		if(settings.submitText) { var newValue = settings.submitText; } else { var newValue = jQuery(this).val(); }

		//insert hidden field with name and value of submit
		targetselect.after("<input id='dummySubmit' disabled='disabled' type='submit' name='"+jQuery(this).attr("name")+"DUMMY' value='"+newValue+"'>");

		//add onClick CSS
		if(settings.onClickCSS) {
			jQuery("#dummySubmit").addClass(settings.onClickCSS);
		}

		return true;
	});

};

jQuery.fn.lockSubmitReset = function() {
	this.show();
	jQuery("#dummySubmit").remove();
};

function resetLockedButton(){
	$("#action-box-form-container-content .disabled-after-click").lockSubmitReset();
}

function removeLastLineOnRightListing(){
	$(".arrow-box ").each(function(){
		if( $(this).find(".right-listing").length > 0 )
			$(this).find(".right-listing:last").css({"margin-bottom":"-1px", "border-bottom":"0px"});
		else
			$(this).parent(".right-listing-container").hide();
	});	
}

function translateAll(){
	try{
		google.setOnLoadCallback(translateAll);
	}catch(e){  }
	$("#loading").show();

	// offer on the fly translation
	$(".translate").each(function(){
		var object = $(this);
		var text = object.text();
		try{
			google.language.detect(text, function(result) {
				if( !result.error && result.language!="en") {
					//var object = object;
					text = text.replace('<br>','<br />');
					try{
						google.language.translate(text, result.language, "en", function(result) {
							if (result.translation) {
								window.translateCount++;
								originalText = text;
								text = result.translation;
								text = text.replace('\n','<br />');
								object.attr('name', result.translation);
								output = text;
								object.attr("name", '<div style="width:300px;"><strong>Google translation:</strong><br />' + output + '.</div>');
								object.tipTip({maxWidth: "auto", edgeOffset: 2});
							}
						});
					}catch(e){}
				}
			});
		}catch(e){}
	});	
	$("#loading").hide();
	//attachStyle();
}

function fbLogout(){
	try{
		FB.Connect.logout(function(){location.href=HTTP_SERVER});
	}catch(err){
		
	}
}

function processFavourite( id, color ){
	

	
	$("#indicator-for-" + id).fadeOut(300);
	$.post('/json-data/process-favorite.json', {"memberId":window.loggedMember.id, "businessId":id}, function(data){
		response = eval("(" + data + ")");
		
		
		$("#indicator-for-" + id).attr("onmouseout", "");
		$("#indicator-for-" + id).attr("onmouseover", "");

		if( response.message.search('added') == -1 ){
			// remove
			$("#indicator-for-" + id).attr("name", "Add");						
			$("#indicator-for-" + id).attr("src", "/images/assets/feed-action/feed_heartadd_grey.png");						
		//	$("#indicator-for-" + id).attr("src", "/images/assets/feed-action/feed_heartadd_" + color + ".png");				
		
		}else{
			// add
			$("#indicator-for-" + id).attr("name", "Remove");						
			$("#indicator-for-" + id).attr("src", "/images/assets/feed-action/feed_heart_" + color + ".png");				
		}
		
		if( color != response.data.color ){
			var newColor = response.data.color;
			
			if( newColor == "orange" || newColor == "yellow" ){
				$("#list-item-container-" + id ).removeClass("bg-cream").addClass("bg-" + newColor);
				$("#list-item-title-" + id ).removeClass(color).addClass("darkgrey");
				$("#list-item-f-" + id ).attr("src", '/images/assets/title/title_person_darkgrey.png?resize(10)');
				if( response.message.search('added') == -1 ){
					// remove
					$("#indicator-for-" + id).attr("src", "/images/assets/feed-action/feed_heart_grey.png");				
				}else{
					// added
					//$("#indicator-for-" + id).attr("src", "/images/assets/indicator/tick_darkgrey.png?resize(10)");
					$("#indicator-for-" + id).attr("src", "/images/assets/feed-action/feed_heartadd_grey.png");
					
				}
				$("#indicator-for-" + id).attr("src", "/images/assets/feed-action/feed_colour_fave_grey.png");
				
				
				$("#list-item-creator-" + id ).removeClass(color).removeClass("red").removeClass("turqouise").removeClass("blue").removeClass("green").removeClass("pink").removeClass("brown").removeClass("purple").removeClass("orange").removeClass("yellow").removeClass("xxx").addClass("darkgrey");
				$("#list-item-category-" + id ).removeClass('light-grey').addClass("darkgrey");
				$("#list-item-community-" + id ).removeClass('light-grey').addClass("darkgrey");	
				$("#list-item-c-" + id ).removeClass('light-grey').addClass("darkgrey");	
				$("#list-item-d-" + id ).removeClass('light-grey').addClass("darkgrey");	
				$("#list-item-meta-" + id ).removeClass('light-grey').addClass("darkgrey");						
			}else{
			
				$("#list-item-container-" + id ).removeClass("bg-cream").addClass("bg-" + newColor);
				$("#list-item-title-" + id ).removeClass(color).addClass("white");
				$("#list-item-f-" + id ).attr("src", '/images/assets/title/title_person_white.png?resize(10)');
				if( response.message.search('added') == -1 ){
					// remove
					$("#indicator-for-" + id).attr("src", "/images/assets/feed-action/feed_heartadd_grey.png");				
				}else{
					// added
					$("#indicator-for-" + id).attr("src", "/images/assets/feed-action/feed_colour_fave_white.png");
				}
				$("#indicator-for-" + id).attr("src", "/images/assets/feed-action/feed_colour_fave_white.png");
				
				$("#list-item-creator-" + id ).removeClass(color).removeClass("red").removeClass("turqouise").removeClass("blue").removeClass("green").removeClass("pink").removeClass("brown").removeClass("purple").removeClass("orange").removeClass("yellow").removeClass("xxx").addClass("white");
				$("#list-item-category-" + id ).removeClass('light-grey').addClass("white");
				$("#list-item-community-" + id ).removeClass('light-grey').addClass("white");	
				$("#list-item-c-" + id ).removeClass('light-grey').addClass("white");	
				$("#list-item-d-" + id ).removeClass('light-grey').addClass("white");	
				$("#list-item-meta-" + id ).removeClass('light-grey').addClass("white");		
			}
		
		// if member didn't change the color
		}
		
		$("#indicator-for-" + id).fadeIn(300);
		
		attachStyle();
		return false;
	});	
}
function activateAccount(){
//	alert( window.loggedMember.id );	
}