



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 initTinyMCE(elementsList, maxlength) {
	if (typeof maxlength == "undefined") {
	    tinyMCE.init({
			// General options
			mode : "exact",
			elements : elementsList,
			theme : "advanced",
			relative_urls : false,
			plugins : "safari,pagebreak,style,layer,table,advhr,advlink,inlinepopups,preview,searchreplace,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras",
			disk_cache : true,

			// Theme options
			theme_advanced_disable: "image,help,cleanup,hr,sub,sup,visualaid,indent,outdent",
			theme_advanced_buttons1 : "bold,italic,underline,|,charmap,|,justifyleft,justifyfull,|,bullist,numlist,|,undo,redo,|,link,unlink,|,table,|,anchor,|,fullscreen,preview,removeformat,code",
			theme_advanced_buttons2 : null,
			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",
			theme_advanced_statusbar_location : "bottom",
			theme_advanced_resizing : true,
			theme_advanced_path : false,

//			content_css : "/css/jquery.wysiwyg.css",
			// Drop lists for link/image/media/template dialogs
			template_external_list_url : "lists/template_list.js",
//			external_link_list_url : "lists/link_list.js",

			// Table defaults
			table_default_border: '1',
			table_default_cellspacing: '0',

			// v1.2 begin:
//			auto_focus : "wysiwyg",
			fix_content_duplication : false,
			invalid_elements : "+a[id|style|rel|rev|charset|hreflang|dir|lang|tabindex|accesskey|type|name|href|target|title|class|onfocus|onblur|onclick|ondblclick|onmousedown|onmouseup|onmouseover|onmousemove|onmouseout|onkeypress|onkeydown|onkeyup],-strong/-b[class|style],-em/-i[class|style],-strike[class|style],-u[class|style],+p[style|dir|class|align],-ol[class|style],-ul[class|style],-li[class|style],br,img[id|dir|lang|longdesc|usemap|style|class|src|onmouseover|onmouseout|border=0|alt|title|hspace|vspace|width|height|align],-sub[style|class],-sup[style|class],-blockquote[dir|style],-table[border=0|cellspacing|cellpadding|width|height|class|align|summary|style|dir|id|lang|bgcolor|background|bordercolor],-tr[id|lang|dir|class|rowspan|width|height|align|valign|style|bgcolor|background|bordercolor],tbody[id|class],thead[id|class],tfoot[id|class],-td[id|lang|dir|class|colspan|rowspan|width|height|align|valign|style|bgcolor|background|bordercolor|scope],-th[id|lang|dir|class|colspan|rowspan|width|height|align|valign|style|scope],caption[id|lang|dir|class|style],-div[id|dir|class|align|style],-span[style|class|align],-pre[class|align|style],address[class|align|style],-h1[style|dir|class|align],-h2[style|dir|class|align],-h3[style|dir|class|align],-h4[style|dir|class|align],-h5[style|dir|class|align],-h6[style|dir|class|align],hr[class|style],-font[face|size|style|id|class|dir|color],dd[id|class|title|style|dir|lang],dl[id|class|title|style|dir|lang],dt[id|class|title|style|dir|lang]",
			handle_event_callback : "keydown",
			// v1.2 end;
			entity_encoding : "raw"
		});
	} else {
		tinyMCE.init({
			// General options
			mode : "exact",
			elements : elementsList,
			theme : "advanced",
			relative_urls : false,
			plugins : "safari,style,layer,table,advhr,advlink,inlinepopups,preview,searchreplace,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,maxlength",
			disk_cache : true,

			// Theme options
			theme_advanced_disable: "image,help,cleanup,hr,sub,sup,visualaid,indent,outdent",
			theme_advanced_buttons1 : "bold,italic,underline,|,charmap,|,justifyleft,justifyfull,|,bullist,numlist,|,undo,redo,|,link,unlink,|,table,|,anchor,|,fullscreen,preview,removeformat,code",
			theme_advanced_buttons2 : null,
			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",
			theme_advanced_statusbar_location : "bottom",
			theme_advanced_resizing : true,
			theme_advanced_path : false,

			// Drop lists for link/image/media/template dialogs
			template_external_list_url : "lists/template_list.js",
//			external_link_list_url : "lists/link_list.js",

			// Table defaults
			table_default_border: '1',
			table_default_cellspacing: '0',

			// maxlength value
			maxlength_wysiwyg : maxlength,

			// v1.2 begin:
//			auto_focus : "wysiwyg",
			fix_content_duplication : false,
			invalid_elements : "+a[id|style|rel|rev|charset|hreflang|dir|lang|tabindex|accesskey|type|name|href|target|title|class|onfocus|onblur|onclick|ondblclick|onmousedown|onmouseup|onmouseover|onmousemove|onmouseout|onkeypress|onkeydown|onkeyup],-strong/-b[class|style],-em/-i[class|style],-strike[class|style],-u[class|style],+p[style|dir|class|align],-ol[class|style],-ul[class|style],-li[class|style],br,img[id|dir|lang|longdesc|usemap|style|class|src|onmouseover|onmouseout|border=0|alt|title|hspace|vspace|width|height|align],-sub[style|class],-sup[style|class],-blockquote[dir|style],-table[border=0|cellspacing|cellpadding|width|height|class|align|summary|style|dir|id|lang|bgcolor|background|bordercolor],-tr[id|lang|dir|class|rowspan|width|height|align|valign|style|bgcolor|background|bordercolor],tbody[id|class],thead[id|class],tfoot[id|class],-td[id|lang|dir|class|colspan|rowspan|width|height|align|valign|style|bgcolor|background|bordercolor|scope],-th[id|lang|dir|class|colspan|rowspan|width|height|align|valign|style|scope],caption[id|lang|dir|class|style],-div[id|dir|class|align|style],-span[style|class|align],-pre[class|align|style],address[class|align|style],-h1[style|dir|class|align],-h2[style|dir|class|align],-h3[style|dir|class|align],-h4[style|dir|class|align],-h5[style|dir|class|align],-h6[style|dir|class|align],hr[class|style],-font[face|size|style|id|class|dir|color],dd[id|class|title|style|dir|lang],dl[id|class|title|style|dir|lang],dt[id|class|title|style|dir|lang]",

			handle_event_callback : "keydown",
			// v1.2 end;
			entity_encoding : "raw"
		});
	}


}

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]+[_|\-|\.]?)*[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,id){
	var str="^(((file|gopher|news|nntp|telnet|http|ftp|https|ftps|sftp)://)|(www\.))+(([a-zA-Z0-9\._-]+\.[a-zA-Z]{2,6})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(/[a-zA-Z0-9\&amp;%_\./-~-]*)?$";
	var re=new RegExp(str);
	if (re.test(url)){
		if(url.indexOf('://')=='-1') $('#'+id).val('http://'+url);
		return true;
	}else{
		return false;
	}
}


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;
}


$(document).ready(function()
{
	var h = $("#miniport_content").height();

	if ($("#miniport_content").height() > 125)
	{
		$("#miniport_content").css("overflow","hidden");
		$("#miniport_content").height(125);
	}
	else
	{
		$("#miniport_content").css("overflow","auto");
		$(".lien-more-4").hide();
	}

	// miniport content show full open and close
	$(".lien-more-4").toggle(function()
	{
		$("#miniport_content").height(h + 10);
		$("#miniport_content").css("overflow","auto");
		$(this).text("Show partial introduction");
	},
	function()
	{
		$("#miniport_content").css("overflow","hidden");
		$("#miniport_content").height(125);
		$(this).text("Show full description");
	});

/*
	$(".lien-more-4").click(function()
	{
		$("#miniport_content").height(h + 10);
		$("#miniport_content").css("overflow","auto");
		$(this).hide();
	});
*/
	$(".btn").hover(function()
	{
		$(this).addClass("btn_hover");
		$(this).removeClass("btn");
	},
	function()
	{
		$(this).addClass("btn");
		$(this).removeClass("btn_hover");
	});

	var currenrel = '';
	$(".show_a").toggle(function()
	{
		if (currenrel != '')
		{
			$("." + currenrel).hide('slow');
			$("a[@rel='" + currenrel + "']").find("img").attr("src", "/images/v1.3/icon_plus.gif");
		}

		var showid = $(this).attr("rel");
		$("." + showid).show('slow');
		$(this).find("img").attr("src", "/images/v1.3/icon_neg.gif");
		currenrel = showid;
	},
	function()
	{
		var showid = $(this).attr("rel");
		$("." + showid).hide('slow');
		$(this).find("img").attr("src", "/images/v1.3/icon_plus.gif");
	});
	
});
