function resizeImage(max_width,selector) {
		$(selector).each(function(){
			var width = $(this).width();
			var height = $(this).height();
			if (width > max_width) {
				//Set variables	for manipulation
				var ratio = (height / width );
				var new_width = max_width;
				var new_height = (new_width * ratio);

				//Shrink the image and add link to full-sized image
				$(this).height(new_height).width(new_width);
			} //ends if statement
		} //ends each function
		);
}

function include(script_filename) {
    var html_doc = document.getElementsByTagName('head').item(0);
    var js = document.createElement('script');
    js.setAttribute('language', 'javascript');
    js.setAttribute('type', 'text/javascript');
    js.setAttribute('src', script_filename);
    html_doc.appendChild(js);
    return false;
}

/* This function is used to change the style class of an element */
function swapClass(obj, newStyle) {
    obj.className = newStyle;
}

function isUndefined(value) {
    var undef;
    return value == undef;
}

function checkAll(theForm) { // check all the checkboxes in the list
  for (var i=0;i<theForm.elements.length;i++) {
    var e = theForm.elements[i];
        var eName = e.name;
        if (eName != 'allbox' &&
            (e.type.indexOf("checkbox") == 0)) {
            e.checked = theForm.allbox.checked;
        }
    }
}

/* Function to clear a form of all it's values */
function clearForm(frmObj) {
    for (var i = 0; i < frmObj.length; i++) {
        var element = frmObj.elements[i];
        if(element.type.indexOf("text") == 0 ||
                element.type.indexOf("password") == 0) {
                    element.value="";
        } else if (element.type.indexOf("radio") == 0) {
            element.checked=false;
        } else if (element.type.indexOf("checkbox") == 0) {
            element.checked = false;
        } else if (element.type.indexOf("select") == 0) {
            for(var j = 0; j < element.length ; j++) {
                element.options[j].selected=false;
            }
            element.options[0].selected=true;
        }
    }
}

/* Function to get a form's values in a string */
function getFormAsString(frmObj) {
    var query = "";
    for (var i = 0; i < frmObj.length; i++) {
        var element = frmObj.elements[i];
        if (element.type.indexOf("checkbox") == 0 ||
            element.type.indexOf("radio") == 0) {
            if (element.checked) {
                query += element.name + '=' + escape(element.value) + "&";
            }
        } else if (element.type.indexOf("select") == 0) {
            for (var j = 0; j < element.length ; j++) {
                if (element.options[j].selected) {
                    query += element.name + '=' + escape(element.value) + "&";
                }
            }
        } else {
            query += element.name + '='
                  + escape(element.value) + "&";
        }
    }
    return query;
}

/* Function to hide form elements that show through
   the search form when it is visible */
function toggleForm(frmObj, iState) // 1 visible, 0 hidden
{
    for(var i = 0; i < frmObj.length; i++) {
        if (frmObj.elements[i].type.indexOf("select") == 0 || frmObj.elements[i].type.indexOf("checkbox") == 0) {
            frmObj.elements[i].style.visibility = iState ? "visible" : "hidden";
        }
    }
}

/* Helper function for re-ordering options in a select */
function opt(txt,val,sel) {
    this.txt=txt;
    this.val=val;
    this.sel=sel;
}

/* Function for re-ordering <option>'s in a <select> */
function move(list,to) {
    var total=list.options.length;
    index = list.selectedIndex;
    if (index == -1) return false;
    if (to == +1 && index == total-1) return false;
    if (to == -1 && index == 0) return false;
    to = index+to;
    var opts = new Array();
    for (i=0; i<total; i++) {
        opts[i]=new opt(list.options[i].text,list.options[i].value,list.options[i].selected);
    }
    tempOpt = opts[to];
    opts[to] = opts[index];
    opts[index] = tempOpt
    list.options.length=0; // clear

    for (i=0;i<opts.length;i++) {
        list.options[i] = new Option(opts[i].txt,opts[i].val);
        list.options[i].selected = opts[i].sel;
    }

    list.focus();
}

/*  This function is to select all options in a multi-valued <select> */
function selectAll(elementId) {
    var element = document.getElementById(elementId);
    len = element.length;
    if (len != 0) {
        for (i = 0; i < len; i++) {
            element.options[i].selected = true;
        }
    }
}

/* This function is used to select a checkbox by passing
 * in the checkbox id
 */
function toggleChoice(elementId) {
    var element = document.getElementById(elementId);
    if (element.checked) {
        element.checked = false;
    } else {
        element.checked = true;
    }
}

/* This function is used to select a radio button by passing
 * in the radio button id and index you want to select
 */
function toggleRadio(elementId, index) {
    var element = document.getElementsByName(elementId)[index];
    element.checked = true;
}

/* This function is used to open a pop-up window */
function openWindow(url, winTitle, winParams) {
    winName = window.open(url, winTitle, winParams);
    winName.focus();
}


/* This function is to open search results in a pop-up window */
function openSearch(url, winTitle) {
    var screenWidth = parseInt(screen.availWidth);
    var screenHeight = parseInt(screen.availHeight);

    var winParams = "width=" + screenWidth + ",height=" + screenHeight;
        winParams += ",left=0,top=0,toolbar,scrollbars,resizable,status=yes";

    openWindow(url, winTitle, winParams);
}

// This function is a generic function to create form elements
function createFormElement(element, type, name, id, value, parent) {
    var e = document.createElement(element);
    e.setAttribute("name", name);
    e.setAttribute("type", type);
    e.setAttribute("id", id);
    e.setAttribute("value", value);
    parent.appendChild(e);
}

function confirmDelete(obj) {
    var msg = "Are you sure you want to delete this " + obj + "?";
    ans = confirm(msg);
    if (ans) {
        return true;
    } else {
        return false;
    }
}

function highlightTableRows(tableId) {
    var previousClass = null;
    var table = document.getElementById(tableId);
    var startRow = 0;
    // workaround for Tapestry not using thead
    if (!table.getElementsByTagName("thead")[0]) {
	    startRow = 1;
    }
    var tbody = table.getElementsByTagName("tbody")[0];
    var rows = tbody.getElementsByTagName("tr");
    // add event handlers so rows light up and are clickable
    for (i=startRow; i < rows.length; i++) {
        rows[i].onmouseover = function() { previousClass=this.className;this.className+=' over' };
        rows[i].onmouseout = function() { this.className=previousClass };
        rows[i].onclick = function() {
            var cell = this.getElementsByTagName("td")[0];
            var link = cell.getElementsByTagName("a")[0];
            if (link.onclick) {
                call = link.getAttribute("onclick");
                if (call.indexOf("return ") == 0) {
                    call = call.substring(7);
                }
                // this will not work for links with onclick handlers that return false
                eval(call);
            } else {
                location.href = link.getAttribute("href");
            }
            this.style.cursor="wait";
            return false;
        }
    }
}

function highlightFormElements() {
    // add input box highlighting
    addFocusHandlers(document.getElementsByTagName("input"));
    addFocusHandlers(document.getElementsByTagName("textarea"));
}

function addFocusHandlers(elements) {
    for (i=0; i < elements.length; i++) {
        if (elements[i].type != "button" && elements[i].type != "submit" &&
            elements[i].type != "reset" && elements[i].type != "checkbox" && elements[i].type != "radio") {
            if (!elements[i].getAttribute('readonly') && !elements[i].getAttribute('disabled')) {
                elements[i].onfocus=function() {this.style.backgroundColor='#ffd';this.select()};
                elements[i].onmouseover=function() {this.style.backgroundColor='#ffd'};
                elements[i].onblur=function() {this.style.backgroundColor='';}
                elements[i].onmouseout=function() {this.style.backgroundColor='';}
            }
        }
    }
}

function radio(clicked){
    var form = clicked.form;
    var checkboxes = form.elements[clicked.name];
    if (!clicked.checked || !checkboxes.length) {
        clicked.parentNode.parentNode.className="";
        return false;
    }

    for (i=0; i<checkboxes.length; i++) {
        if (checkboxes[i] != clicked) {
            checkboxes[i].checked=false;
            checkboxes[i].parentNode.parentNode.className="";
        }
    }

    // highlight the row
    clicked.parentNode.parentNode.className="over";
}


function getY( oElement ) {
	var iReturnValue = 0;
	while( oElement != null ) {
		iReturnValue += oElement.offsetTop;
		oElement = oElement.offsetParent;
	}
	return iReturnValue;
}

function getX( oElement ) {
	var iReturnValue = 0;
	while( oElement != null ) {
		iReturnValue += oElement.offsetLeft
		oElement = oElement.offsetParent;
	}
	return iReturnValue;
}


// Additional function used in combination with Treeview plugin
function addTreeLeaf(element, url, tree) {
	element = $(element).children("ul");

	if ($.trim($(element).html()) == "") {
		$.get(url, {ajax: "true", id: $(element).attr("id")}, function(data) {
			var newBranch = $(data).appendTo(element);
			tree.treeview({
	   			add: newBranch
	 			});
		});
	}
}

// -- Show popup user if it tries to submit anonymously
var PENDING_FORM = null;
var PENDING_FORM_BUTTON = null;

function checkLoginStatus(formSelector, buttonSelector) {
	$(formSelector).submit( function () {
		PENDING_FORM = formSelector;
		PENDING_FORM_BUTTON = buttonSelector;

		jQuery.get(ctx + "/ajax/currentUser.html", { ajax: "true" },
  			function(data) {
	  			data = jQuery.trim(data);
    			if (data == '') {
    				//show login popup
					GB_show("",ctx + "/login.jsp?ajax=true&whileSubmit=true",500,730);
    			} else {
    				$(PENDING_FORM).unbind();
        			$(PENDING_FORM_BUTTON).click();
    			}
  		});

  		return false;
	});
}

/**
 * Checks to see if the user it's logged and
 * the site it's not locked (CP is logged in too).
 */

function isUserLogged() {
	jQuery.get(ctx + "/ajax/currentUser.html", { ajax: "true" }, function(data) {
		if (jQuery.trim(data) == '') {
			return false;
		} else {
			return true;
		}
	});
}





/**
 * Attaches an onclick event, over an element.
 * Checks to see if the user is logged before allowing
 * the onclick event of an element to be triggered.
 * If the user it's not logged in, he will be redirected
 * to the homepage.
 */
function attachLoginCheckEvent(linkSelector, redirectURL) {
	$(linkSelector).each(function () {
		var onclick = $(this).attr('onClick');
		if (onclick) {
			$(this).removeAttr('onClick');
			$(this).unbind('click');
			$(this).click(function() {
				redirectIfNotLogged($(this), redirectURL, onclick);
				return false;
			});
		}
	});
}

/**
 * Checks to see if the user is logged before allowing
 * the onclick event of an element to be triggered.
 * If the user it's not logged in, he will be redirected
 * to the homepage.
 */
function redirectIfNotLogged(element, redirectURL, callback) {
	jQuery.get(ctx + "/ajax/currentUser.html", { ajax: "true" }, function(data) {
		if (jQuery.trim(data) == '') {
			window.location.href = redirectURL;
		} else {
			var anonymous =  function() {};
			eval(callback + "; anonymous();");
		}
	});
}



// Show the document's title on the status bar
window.defaultStatus=document.title;
var GB_ANIMATION = navigator.userAgent.indexOf( "MSIE" ) >= 0; // greybox.js slideDown works bad 2nd time in Firefox
var USER_LOGGED = false;

function writeLen(len, maxlength){
	document.getElementById('spaceleft').value=maxlength-len;
    document.getElementById('space').value=maxlength;
}

/*
	Sorts the <li> elements of a <ul> or <ol> alphabetically
	Each <li> is searched for an <a>, whose contents are considered for sorting
*/
function sortList( idList )
{
	var list = document.getElementById( idList );
	if( !list )
	{
		return false; // No such list
	}
	var items = list.getElementsByTagName( "li" );
	var texts = [];
	for( var i = 0; i < items.length; i++ )
	{
		var item = items[i];
		var link = item.getElementsByTagName( "a" );
		if( link.length != 1 )
		{
			break; // Not all the items contain a link
		}
		texts.push( link[0].innerHTML );
	}
	if( i == items.length )
	{
		texts.sort();
		for( var i = 0; i < items.length; i++ )
		{
			var item = items[i];
			var link = item.getElementsByTagName( "a" );
			link[0].innerHTML = texts[i];
		}
	}

	// Remove the <script> artifact
	for( var parent = list.parentNode; list.nextSibling; )
	{
		parent.removeChild( list.nextSibling );
	}
}

function checkEmail(email){
//     var str=/^([a-zA-Z0-9_\.-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
	var str="^([a-zA-Z0-9_-]+[\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9_-]+[\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$";
     var re=new RegExp(str);
     if(re.test(email)){
       return true;
     }
     return false;
}

function checkUrl(url){
//	var regStr = "((http|https)(:\/\/))?([a-zA-Z0-9]+[.]{1}){2}[a-zA-z0-9]+(\/{1}[a-zA-Z0-9]+)*\/?";
	var regStr = /^((sftp|ftp|http|https):\/\/){0,1}(w{3}\.){0,1}([a-zA-Z0-9]+\.?[a-zA-Z0-9]+)[^(www)]\.([a-zA-Z]{1,3}){1}(\/[a-zA-Z0-9@-_]*)*$/;
	var reg = new RegExp(regStr);
	return reg.test(url);	
}

function sentenceUpperCase(thisvalue)
{
	var reg = /\s{2,}/g;
	var upperSentence = '';
	var str = thisvalue.replace(reg, ' ');

	var a = str.replace(/\b\w+\b/g, function(word)
	{
		return word.substring(0,1).toUpperCase( ) +	word.substring(1).toLowerCase();
	});

	return a;
}


function sentenceUpperCase2(word){
	var wLength = word.length;
	if(wLength > 0){
		var ss = (word.substring(0,1).toUpperCase()) + (word.substring(1,wLength) + " ");
	}
	return ss;
}


$(document).ready(function()
{
	replaceVarText();
	
	// miniport content show full open and close
	$(".lien-more-4").toggle(function()
	{
		$("#miniport_content .description").hide();
		$("#miniport_content .full_text").show();
		$("#miniport_content .text-fade").hide();
		
		$(this).text("Show partial introduction");
	},
	function()
	{
		$("#miniport_content .full_text").hide();
		$("#miniport_content .description").show();
		$("#miniport_content .text-fade").show();
		$(this).text("Show full description");
	});

	$(".btn").hover(function()
	{
		$(this).addClass("btn_hover");
		$(this).removeClass("btn");
	},
	function()
	{
		$(this).addClass("btn");
		$(this).removeClass("btn_hover");
	});
	
	$(".input-btn").hover(function()
			{
				$(this).addClass("input-btn_hover");
				$(this).removeClass("input-btn");
			},
			function()
			{
				$(this).addClass("input-btn");
				$(this).removeClass("input-btn_hover");
			});
	

/** 1.3.5 2010-8-1 begin :*/
	$(".show_a").click(function(){
		var $this = $(this);
		var showId = $this.attr("rel");
		if($this.hasClass("open")){
			$this.removeClass("open");
			$($this.parent().find("img[data='right'][rel='" + showId+ "']")[0]).removeClass('neg');
			$($this.parent().find("img[data='left'][rel='" + showId+ "']")[0]).attr("src", "/images/layout/arrowright.gif");
			$this.parent().find(".subcategories:first").hide();
		}else{
			$this.addClass("open");			
			$($this.parent().find("img[data='right'][rel='" + showId+ "']")[0]).addClass('neg');
			$($this.parent().find("img[data='left'][rel='" + showId+ "']")[0]).attr("src", "/images/layout/arrowdown2.gif");
			$this.parent().find(".subcategories:first").show();
		}
		
		return false;
	});
/** end; */

/** 1.3.4 2010-4-3 begin */
	$('#addupload').click(function()
	{
		if ($(".uploaddiv").find("input[@type='file']").size() < 10)
		{
			var newupload = $(".uploaddiv").find(".clone:first").clone();
			$(newupload).find("input:first").val('');
			$(newupload).find("input:first").bind("change", function(){$(document).checkChange(this);});
			$(newupload).find(".uperror").removeClass("red");
			$(newupload).appendTo(".uploaddiv");
	//		$(".uploaddiv").find(".clone:first").clone().appendTo(".uploaddiv");
			
			bindClearInputFileValue();
		}
		else
		{
			$(this).hide();
		}
	});
	$('#addlink').click(function()
	{
		if ($(".linkdiv").find("input").size() < 10)
		{
			var newlink = $(".linkdiv").find(".clone:first").clone();
			$(newlink).find("input:first").val('www.');
			$(newlink).find("input:first").bind("change", function(){$(document).checkUrlChange(this);});
			$(newlink).find(".urlerror").hide();
			$(newlink).appendTo(".linkdiv");
		}
		else
		{
			$(this).hide();
		}
	});

	$.fn.checkChange = function(e)
	{
		if ($(e).val() == '')
		{
			return false;
		}

		var string = $(e).val();
		var ext = string.split('.');
		if (ext[ext.length-1] != 'pdf')
		{
			$(e).parent().find(".uperror").addClass("red");
		}
		else
		{
			$(e).parent().find(".uperror").removeClass("red");
		}
	};

	$(".uploadPromotionalPdfs").bind("change", function(){$(document).checkChange(this);});

		$(".openpic").click(function()
		{
			var show = $(this).attr("rel");
			$("." + show).show();
		});

		$(".closepic").click(function()
		{
			var show = $(this).attr("rel");
			$("." + show).hide();
		});


	$.fn.checkUrlChange = function(e)
	{
		if ($(e).val() == '')
		{
			return false;
		}

		if (!checkUrl($(e).val()))
		{

			$(e).parent().find(".urlerror").show();
		}
		else
		{
			$(e).parent().find(".urlerror").hide();
		}
	};



	$(".uploadPromotionalLinks").bind("change", function(){$(document).checkUrlChange(this);});
	
	bindClearInputFileValue();
	
/** 1.3.4 2010-4-3 end */
	$("input.numeric").keydown(function(e){
		var flag = e.keyCode >= 48 && e.keyCode <= 57;
		flag |= e.keyCode == 8;
		flag |= (e.keyCode >= 37 && e.keyCode <= 40);
		flag |= e.which >= 48 && e.which <= 57;
		flag |= e.which == 8; 
		flag |= (e.which >= 37 && e.which <= 40);
		
		if(!flag){
			return false;
		}
	});
	
	$("textarea.limited").each(function(){
		var classes = $(this).attr("className").split(" ");
		var maxlength = null;
		for(var i=0; i<classes.length; i++){
			var className = classes[i];
			if(/^limit([0-9]+)$/.test(className)){
				maxlength = className.replace('limit','');
				break;
			}
		}
		if(maxlength != null){
			$(this).attr("rel", maxlength);
		}
	});
	
	$("textarea.limited").keydown(function(e){
		if(e.keycode == 8 || e.which == 8 ||
    		(e.keycode >= 35 && e.keycode <= 40) ||
    		(e.which >= 35 && e.which <= 40) ||
    		(e.keycode == 17 || e.keycode == 18) ||
    		(e.which == 18 || e.which == 17) || 
    		(e.which == 46 || e.which == 46)) return true;
		var maxlength = $(this).attr("rel");
		if(maxlength == null || maxlength == '') return true;
		var res = $(this).val().length+1 <= parseInt(maxlength);
		return res;
	}).blur(function(){
		var val = $(this).val();
		if(val == '') return;
		
		var maxlength = $(this).attr("rel");
		if(maxlength == null || maxlength == '') return;
		
		if(parseInt(maxlength) < val.length){
			$(this).val(val.substring(0, parseInt(maxlength)));
		}
	});
	
	$(document).bind('afterReveal.facebox', function(){
		$("#facebox").find("input.caps").capslock({
			caps_lock_on: notifyCapslockOn,
			caps_lock_off: hideCapslockOnNotification
		});
		$("#facebox").find("#td-plogin").children(".lp_login_label").show();
		$("#facebox").find("#td-plogin").children(".lp_login_error").hide();
	});
	
	checkCabslock();
	
	$("a.to-bookmark").click(function(){
		var $a = $(this);
		var to = $a.attr("href");
		setTimeout("bookmarkClickCallback('"+to+"');", 100);
		return true;
	});
});

function checkCabslock(ref){	
	if($.browser.safari) return; // Safari already indicates caps lock
	if(!ref){
		if($("input.caps").length > 0){
			$("input.caps").capslock({
				caps_lock_on: notifyCapslockOn,
				caps_lock_off: hideCapslockOnNotification
			});
		}
	}else{
		$(ref).capslock({
			caps_lock_on: notifyCapslockOn,
			caps_lock_off: hideCapslockOnNotification
		});
	}
}

function notifyCapslockOn(ref){
	$(".capslock-on").show();
}

function hideCapslockOnNotification(ref){
	$(".capslock-on").hide();		
}

function bindClearInputFileValue(){	
	$(".clearInputFile").unbind("click").bind("click", function(){
		var $a = $(this);
		$a.siblings("input[type=file]").val('');
		return false;
	});
}

var t_str = '';
function scount(str, max)
{
	var i=0,j=0,c=0;
	var t=/[a-zA-Z]+/;
	var bo=false;
	for(i=0,j=i+1;j<=str.length;i=j++)
	{
		if(t.test(str.substring(i,j))&&!bo)
		{
			bo=true;c++;
		}
		else if(!t.test(str.substring(i,j)))
		{
			bo=false;
		}
	}

	if (c < max )
	{
		t_str = str;
	}

	return t_str;
}

function gbcount(event,message,max) {
	var key = event.keyCode ? event.keyCode : event.which;
	//allowed keys are backspace, delete, end, home, left, up, right, down
	if(key == 8 || key == 46 || (key > 34 && key < 41 )) {    
		return true;
	}else{
		message.value = message.value.substr(0,max);
		return (message.value.length <= max);
	}
}


var auto;


function showLatestContent() {
	$.getJSON("/getHeaderNavInfo.html", {type: "json", ifModified: false}, function(data) {
		// total articles
		$('#totalArticles').html(data.totalArticleNum + " contributions posted");

		// article list
		var articleList = eval(data.lastArticleInfo);
		var liststring = '';

		var titleLength = 0;
		var title = '';
		var author = '';
		var maxTitleLength = 20;
		var maxUserLength = 20;
		var author_2 = '';	

		for (var i in articleList) {
			title = '';
			author = '';
			titleLength = articleList[i].title.length ;
			
			if ($.trim(articleList[i].author).length >= maxUserLength) {
				author_2 = articleList[i].author.substring(0, maxUserLength-3) + "...";
			} else {
				author_2 = articleList[i].author;
			}

			if (articleList[i].enabled == '1') {
				author = "<a href='" + articleList[i].authorURL + "' >" + author_2 + "</a>";
			} else {
				author = author_2;
			}

			if (titleLength <= maxTitleLength) {
				title = "<a href='" + ctx + articleList[i].url + "' title='" + articleList[i].title + "' >" + articleList[i].title + "</a>  posted by " + author;
			} else {
				title = "<a href='" + ctx + articleList[i].url + "' title='" + articleList[i].title + "' >" + articleList[i].title.substring(0,maxTitleLength-3) + "...</a>  posted by " + author;
			}

			if (i == 0) {
				$("#topone").html('<strong>Latest:</strong> ' + title);
			}

			liststring = liststring + ' <tr><td width="80">'+ articleList[i].date +'</td><td>' + title + '</td></tr>';
		}

		$('#lc').html(liststring);

	});

	// article list show/hide
	var showflag = 0;
	$('#toparticles').click(function() {
		if (showflag == 0) {
			$(this).addClass('closem');
			$('#toparticlesdiv').show();

			showflag = 1;
		} else {
			$(this).removeClass('closem');
			$('#toparticlesdiv').hide();
			showflag = 0;
		}
	});
	
}

function sortNumber(a,b){
	return b-a;
}

function showSubPathway(){
	var arr = new Array();
	var $tmp = $("<div>");
	$(".altBLinks").children().each(function(index){
		var rel = $(this).attr("rel");
		arr[index] = rel;
	});
	arr.sort(sortNumber);
	for(var i=0; i<arr.length; i++){			
		var objectId = arr[i];
		$(".altBLinks ." + objectId).each(function(index){
			$tmp.append(this).append(", ");
		});						
	}
	var html = $tmp.html();
	$(".altBLinks").html(html.substring(0, html.length-2)).show();
}

function trackEvent(category, action, label, value){
	if(!label && !value){
		_gaq.push(['_trackEvent', category, action]);
	}else if(label && isNaN(value)){
		_gaq.push(['_trackEvent', category, action, label]);
	}else if(label && !isNaN(value)){
		_gaq.push(['_trackEvent', category, action, label, value]);
	}
}

function checkOtherCountryChage(ref){
	if($(ref).attr("checked") == false){
		$("#check_all_countries").attr("checked", false);
	}
	if($(ref).attr("checked") == true){
		var flag = true;
		$("input.otherCountries").each(function(){
			if($(this).attr("checked") == false){
				flag = false;
			}
		});
		if(flag){
			$("#check_all_countries").attr("checked", true);
		}
	}
}

function bookmarkClickCallback(bookmark){
	var $anchor = $(bookmark);
	var $off = $anchor.offset();	
	var scrollTop = $(window).scrollTop();	
	if($off && $off.top <= scrollTop){
		$(window).scrollTop(scrollTop-60);
	}			
}
//Replace tag <var> with rel attribute text in order to hide the text from google indexing
function replaceVarText(){
	$("var.replaceTxt").each(function() {
		 $(this).replaceWith($(this).attr("rel"));
	});	
}

function htmlDecode(value){ 
  return $('<div/>').html(value).text(); 
}

var valuesLog = new Array();
var changedLog = new Array();

function thingChanges(ref, newVal, callback){
	var allowSaveChange = false;
	if(ref){
		var newValue = "";
		if(typeof ref == "object" && (typeof newVal == "undefined" || typeof newVal == "function")){
			newValue = $(ref).val();
		}else{
			newValue = newVal;
		}
		
		var key = (typeof ref == "string") ? ref : $(ref).attr("name"); 
		
		checkChanges(key, newValue);
		
		for(var changed in changedLog){
			if(changedLog[changed] == true){
				allowSaveChange = true;
				break;
			}
		}
		
		if(typeof callback == 'function'){
			callback(allowSaveChange);
		}else if(typeof newVal == 'function'){
			newVal(allowSaveChange);
		}
	}
}

function logMyValue(name, val){
	valuesLog[name] = val;
	changedLog[name] = false;
}

function checkChanges(name, newVal){
	if(valuesLog[name] != newVal){
		changedLog[name] = true;
	}else{
		changedLog[name] = false;
	}
}

function restoreDefaultValue(element, defaultValue){
	if(element){
		if($.trim($(element).val()) == ''){
			$(element).val(defaultValue);
		}else if($.trim($(element).val()) == defaultValue){
			$(element).val('');
		}
	}
}
