/*-----------------------------------------------------------
    Toggles element's display value
    Input: any number of element id's
    Output: none 
    ---------------------------------------------------------*/
function toggleDisp() {
    for (var i=0;i<arguments.length;i++){
        var d = $(arguments[i]);
        if (d.style.display == 'none')
            d.style.display = 'block';
        else
            d.style.display = 'none';
    }
}
/*-----------------------------------------------------------
    Toggles tabs - Closes any open tabs, and then opens current tab
    Input:     1.The number of the current tab
                    2.The number of tabs
                    3.(optional)The number of the tab to leave open
                    4.(optional)Pass in true or false whether or not to animate the open/close of the tabs
    Output: none 
    ---------------------------------------------------------*/
function toggleTab(num,numelems,opennum,animate) {
    if ($('tabContent'+num).style.display == 'none'){
        for (var i=1;i<=numelems;i++){
            if ((opennum == null) || (opennum != i)){
                var temph = 'tabHeader'+i;
                var h = $(temph);
                if (!h){
                    var h = $('tabHeaderActive');
                    h.id = temph;
                }
                var tempc = 'tabContent'+i;
                var c = $(tempc);
                if(c.style.display != 'none'){
                    if (!animate || typeof animate == 'undefined')
                        toggleDisp(tempc);
                    else
                        Effect.toggle(tempc,'blind',{duration:0.5, queue:{scope:'menus', limit: 3}});
                }
            }
        }
        var h = $('tabHeader'+num);
        if (h)
            h.id = 'tabHeaderActive';
        h.blur();
        var c = $('tabContent'+num);
        c.style.marginTop = '2px';
        if (!animate || typeof animate == 'undefined'){
            toggleDisp('tabContent'+num);
        }else{
            Effect.toggle('tabContent'+num,'blind',{duration:0.5, queue:{scope:'menus', position:'end', limit: 3}});
        }
    }
}

/*
	the code is used to work with the traffic graph from Compete
	we have 2 set of tabs (one for ranges, and one for measures); the user can choose any combination of tabs from these 2 sets, and we will show him the
	coresponding graph; graph are loaded on the fly, when the user ask a certain graph

	for each posible graph coming there is a div, which will contain when the graph has to be shown a javascript, as described at http://www.alexa.com/site/site_stats/signup

	a global var (pitchWebsite) defined in the view show_alexa_analytics is used
*/


// one set of tabs
var competeMeasures = new Array( 'compete1', 'compete2', 'compete3', 'compete4', 'compete5', 'compete6' ); // People count, Rank, Visit, Attention, Average Stay, Page per visit
// another set of tabs
// tab compete1 has one corresponding tab: y1, tab compete4 has 2 corresponding tabs: m1 and y1
var competeRanges   = new Array( new Array( 'y1' ), new Array( 'y1' ), new Array( 'y1' ), new Array( 'm1', 'y1' ), new Array( 'y1' ), new Array( 'y1' ) );

// special case for constructing img src for compete graph, attention daily
var specialCompeteMeasure = competeMeasures[ 3 ];
var specialCompeteRange   = competeRanges[   3 ][ 0 ];

// the code to add in graph src for each measure
var metrics = new Array( );
metrics[ 'compete1' ] = 'uv';
metrics[ 'compete2' ] = 'rank';
metrics[ 'compete3' ] = 'sess';
metrics[ 'compete4' ] = 'att';
metrics[ 'compete5' ] = 'avgStay';
metrics[ 'compete6' ] = 'ppv';

// which are at every moment the selected tabs (default tabs are '6m'-range and 'r'/reach-measure)
var competeCurrentMeasure = competeMeasures[ 0 ];
var competeCurrentRange   = competeRanges[   0 ][ 0 ];
// when a measure tab is clicked, the selected range tab is reset to this default value
var competeDefaultRange   = competeRanges[   0 ][ 0 ];

// what graphs has already been shown; if the user wants to see one of these again, we just make visible its container (div)
var alreadyShownCompeteGraphs = new Array( competeRanges.length * competeMeasures.length );

// toggle display loading element
function toggleLoadingElem(enabled, tmpElem){	
	var elem = document.getElementById('imgTableLoading');
	if(elem){
		if(enabled){
			elem.style.display = 'block';
		}else{			
			elem.style.display = 'none';
			if(tmpElem){
				tmpElem.parentNode.style.visibility = 'visible';
				if(tmpElem.parentNode.parentNode){
					tmpElem.parentNode.parentNode.isLoaded = true;	
				}
			}
		}	
	}
}

function getVisibleGraph(){
	var parentElem = document.getElementById("graphsContainer");
	var allDivs = parentElem.getElementsByTagName("DIV");
	for(var ii = 0; ii < allDivs.length; ii++){
		var currentElem = allDivs[ii];
		if(currentElem.style.display == 'block'){
			return currentElem;
		}	
	}
	return null;
}

// create all the divs (containers) for all the posible graphs; in these divs we will include -on the fly, when the user asks for a certain graph- the image from compete, to generate the graph
function createDivsForCompete( )
{
	_parentNode = document.getElementById( 'graphsContainer' );
	//loading...
	var loadingText = 'Loading...';
	var imgLoading 	= document.createElement('img');
	var imgTable 	= document.createElement('table');
	var imgTBody 	= document.createElement('tbody');
	var imgTR 		= document.createElement('tr');
	var imgTD		= document.createElement('td');
	var imgSpan 	= document.createElement('span');

	imgTable.appendChild(imgTBody);
	imgTBody.appendChild(imgTR);
	imgTR.appendChild(imgTD);
	imgTD.appendChild(imgLoading);
	imgTD.appendChild(imgSpan);
	imgSpan.innerHTML = loadingText;

	imgTable.style.width = '100%';
	imgTable.style.position = "relative";
	imgTBody.style.display = "block";
	imgTD.style.display = "block";
	imgTR.style.display = "block";
	imgTable.id = "imgTableLoading";
	imgTable.style.textAlign = 'center';
	imgLoading.src = '/images/loading.gif';
	_parentNode.appendChild( imgTable );

	for( var j = 0; j < competeMeasures.length; j++ )
	{
		for( var i = 0; i < competeRanges[ j ].length; i++ )
		{
			var myDiv = document.createElement( 'div' );
			myDiv.id = competeMeasures[ j ] + competeRanges[ j ][ i ];
			_parentNode.appendChild( myDiv );
		}
	}
}

function isElementVisible( idElement )
{
	return document.getElementById( idElement ).style.display.toString( ).toLowerCase( ) != 'none'
}

// user clicked on a measure tab (People count, Rank, Visit, Attention, Average Stay, Page per visit); we will inject the required html (img tag) to bring the required graph
function competeMeasureTab( measure )
{
	competeCurrentRange = competeDefaultRange; // reset selected range tab
	if( isElementVisible( measure + competeCurrentRange ) )
	{
		return;
	}
	competeCurrentMeasure = measure;
	updateCompeteGraphic( );
}

// user clicked on a range tab ('1m', '1y'); we will inject the required html (img tag) to bring the required graph
function competeRangeTab( range )
{
	if( isElementVisible( competeCurrentMeasure + range ) )
	{
		return;
	}
	competeCurrentRange = range;
	updateCompeteGraphic( );
}

function arrayContains( arr, el )
{
	for( var i = 0; i < arr.length; i++ )
	{
		if( arr[ i ] == el )
		{
			return true;
		}
	}
	return false;
}
function arrayIndexOf( arr, el )
{
	for( var i = 0; i < arr.length; i++ )
	{
		if( arr[ i ] == el )
		{
			return i;
		}
	}
	return -1;
}

// update the screen, modifying if necessary:
// - the shown graphic acording to present selected by user pair of tabs (range+measure)
// - the graphic legend
// - the aspect of tabs (selected and not-selected tabs look different)
function updateCompeteGraphic( )
{			
	for( var j = 0; j < competeMeasures.length; j++ )
	{
		for( var i = 0; i < competeRanges[ j ].length; i++ )
		{
			document.getElementById( competeMeasures[ j ] + competeRanges[ j ][ i ] ).style.display = 'none';
		}
		document.getElementById( 'legend_' + competeMeasures[ j ] ).style.display = 'none';
		document.getElementById( 'competeM' + competeMeasures[ j ] ).parentNode.className = '';

		if( competeRanges[ j ].length > 1 ) {
			document.getElementById( competeMeasures[ j ] + 'ranges' ).style.display = 'none';
			for( var k = 0; k < competeRanges[ j ].length; k++ ) {
				document.getElementById( 'ranges' + competeMeasures[ j ] + competeRanges[ j ][ k ] ).parentNode.className = '';
			}
		}
	}
	if( arrayContains( alreadyShownCompeteGraphs, competeCurrentMeasure + competeCurrentRange ) == false ) {
		var imageWidth = 410;
		toggleLoadingElem(true);
		alreadyShownCompeteGraphs.push( competeCurrentMeasure + competeCurrentRange );
		
		// special case
		if( competeCurrentMeasure == specialCompeteMeasure && competeCurrentRange == specialCompeteRange ) {
			var _metrics = 'attD';
			document.getElementById( competeCurrentMeasure + competeCurrentRange ).innerHTML = "<a style = 'visibility: hidden;' href='http://siteanalytics.compete.com/" + pitchWebsite + "?metric=" + _metrics + "'><img style='width:" + imageWidth + "px;' onload='toggleLoadingElem(false, this);' src='http://media.compete.com/" + pitchWebsite + "_" + _metrics + "_" + intervalCompeteAttentionDaily + "_460.png?" + Math.floor(Math.random() * 10000) + "' /></a>";
		} else {
			document.getElementById( competeCurrentMeasure + competeCurrentRange ).innerHTML = "<a style = 'visibility: hidden;' href='http://siteanalytics.compete.com/" + pitchWebsite + "?metric=" + metrics[ competeCurrentMeasure ] + "'><img style='width:" + imageWidth + "px;' onload='toggleLoadingElem(false, this)' src='http://media.compete.com/" + pitchWebsite + "_" + metrics[ competeCurrentMeasure ] + "_460.png?" + Math.floor(Math.random() * 10000) + "' /></a>";
		}
	}
	document.getElementById( competeCurrentMeasure + competeCurrentRange ).style.display = 'block';
	document.getElementById( 'legend_' + competeCurrentMeasure    ).style.display = 'block';

	if( document.getElementById( 'ranges' + competeCurrentMeasure + competeCurrentRange   ) ) {
		document.getElementById( 'ranges' + competeCurrentMeasure + competeCurrentRange   ).parentNode.className = 'selectedTab';
	}
	document.getElementById( 'competeM' + competeCurrentMeasure ).parentNode.className = 'selectedTab';
	if( competeRanges[ arrayIndexOf( competeMeasures, competeCurrentMeasure ) ].length > 1 ) {
		document.getElementById( competeCurrentMeasure + 'ranges' ).style.display = 'block';
	}
	var currVisibleGraph = getVisibleGraph();
	if(currVisibleGraph) {
		if(currVisibleGraph.isLoaded) {
			toggleLoadingElem(false);
		} else {
			toggleLoadingElem(true);
		}
	}
}

/*
 This file is a for user profile and edit profile pages

*/

function toggle_sub_profile(div_to_toggle, check_val)
{
	if (check_val)
	{
		$('sub_'+div_to_toggle).style.display = 'block';
		$('h_'+div_to_toggle).className = 'subheading';
	}
	else
	{
		$('sub_'+div_to_toggle).style.display = 'none';
		$('h_'+div_to_toggle).className = 'subheading_edit';
	}
}

function callDelete(slug) {
	var values = getCheckedValue($("id_network"));
	if (values!='') {
		if (confirm('Are you sure you want to delete?')) {
			location.href='/pitch/remove_network/?val='+values+'&id='+slug;
		}
	}
}

function countChecked(obj) {
	if("undefined" != typeof(maximum)) {
		var message = 'You can choose a maximum of ' + maximum + ' categories for your company profile';
		if(obj!=undefined && obj.form!=undefined) {
			form = $(obj.form.name) ? $(obj.form.name) : obj.form;
			var categories = form.getInputs('checkbox',obj.name);
			var counter = 0;
			total = categories.length;
			var i = 0;
			for(i; i < total; i++) {
				if(categories[i].checked) counter++;
			}
			if(counter > maximum && obj.checked == true) {
				obj.checked = false;
				alert(message);
			}
		}
	}

}

/*
 This file is a standard style sheet for the project

*/

// OPTIONAL: do something here after the new data has been populated in your text area
function onABCommComplete() {
	emailList = $('txt_recipient').value.split(', ');
	for (i=0; i<emailList.length; i++) {
		emailItem = emailList[i].split('" <');
		$('friend_list').value += ( emailItem[1].substring(0, emailItem[1].length-1) +", " )
	}
	$('txt_recipient').value = '';
}

function checkLogin(slug) {
	window.opener.location="/user/login?refer="+slug;
	window.close();
}

function CheckCookies() {

    var cookieEnabled=(navigator.cookieEnabled)? true : false;

    //if navigator,cookieEnabled is not supported
    if (typeof navigator.cookieEnabled=="undefined" && !cookieEnabled){
        document.cookie="testcookie";
        cookieEnabled=(document.cookie.indexOf("testcookie")!=-1)? true : false;
    }

    if (!cookieEnabled)
        location.href="/cookies.html";


  }

    function isPassword(obj) {
    	var regexp = /^([a-zA-Z]|[+]?\d)+$/;
    	return regexp.test(obj.value);
    }
    function isEmail(email) {
		return email.match(/^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/);
    }

    function getCheckedValue(obj) {
    	var val='';
    	var checkAll = obj.id.split("_")[1]+"All";
    	x = obj.getElementsByTagName("input");
    	for (var i=0; i<x.length; i++) {
    		if (x[i].type=='checkbox' && x[i].checked==true && x[i].id!=checkAll) {
    			if (val !='') val += ",";
    			val += x[i].value;
    		}
    	}
    	return val;
    }
    function checkUncheck(obj, val) {
    	var checkAll = obj.id.split("_")[1]+"All";
    	x = obj.getElementsByTagName("input");
    	for (var i=0; i<x.length; i++) {
    		if (x[i].type=='checkbox' && x[i].id!=checkAll && !x[i].disabled) {
    			x[i].checked = val;
    		}
    	}
    }

    function checkUncheckAll(obj, val, chkboxID) {
    	if (val) {
    		x = obj.getElementsByTagName("input");
    		var len = 0;
    		chkValue = 0;
    		for (var i=0; i<x.length; i++) {
    			if (x[i].type=='checkbox' && !x[i].disabled) {
    				if (x[i].id!=chkboxID.id) len++;
    				if (x[i].checked) chkValue ++;
    			}
    		}
    		if (chkValue==len) {
    			chkboxID.checked = true;
    		}
    	} else {
    		chkboxID.checked = val;
    	}
    }

    function showCompetition(val) {
    	if (val!="") {
    		location.href="/competition/show/"+val;
    	}
    }

    function toggleSearchView(obj_to_show, obj_to_hide){
    	obj_to_show.show();
    	obj_to_hide.hide();
    }

    function trim(str)
    {
    	return str.replace(/^\s*|\s*$/g,"");
    }

    function submitFavForm(pitch_id){
		val = ($('inform_update').checked) ? 1 : 0;
		var ajax = new Ajax.Request('/user/add_to_fav', {
										asynchronous:true,
										evalScripts:true,
										onComplete:function(request){clearFields(request.responseText);},
										parameters:'pitch_id='+pitch_id+'&update='+val
								});

		return true
    }

    function clearFields(response){
    	$('id_fav_form').style.display = 'none';
    	$('id_add_to_fav').innerHTML = '';
		$('id_add_to_fav_disp').innerHTML = '<a href="/user/my_favorites" class="btn_pitch already_fav"><span>In your favorites</span></a>';
    }

    function submitCommForm(pitch_id){
    	if($('tar_comments').value == ''){
    		alert("please add some comments");
    	}else{
			$('btn_comm_submit').disabled = "disabled";
			var ajax = new Ajax.Request('/pitch/post_comment',
								{
									parameters: "comment="+encodeURIComponent($F('tar_comments'))+"&pitch_id="+pitch_id,
									asynchronous: true,
									evalScripts: true,
									onComplete: function(request){updateCommFields(request.responseText)}
								})
    	}
    }

	function submitReplyForm(pitch_id, comm_id) {
		if($('tar_comments_'+comm_id).value == ''){
    		alert("please add some comments");
    	}else{
			Element.hide('reply_comment_'+comm_id);
			var ajax = new Ajax.Request('/pitch/post_comment',
								{
									parameters: "comment="+encodeURIComponent($F('tar_comments_'+comm_id))+"&pitch_id="+pitch_id+"&comment_id="+comm_id,
									asynchronous: true,
									evalScripts: true,
									onComplete: function(request){loadComments(pitch_id);}
								})
    	}
	}

	function removeComment(comment_id, pitch_id, is_expert){
   		var ajax = new Ajax.Request('/pitch/remove_comment',
								{
									parameters: "comment_id="+comment_id+"&pitch_id="+pitch_id,
									asynchronous: true,
									evalScripts: true,
									onComplete: function(request){updateCommentCounts(request.responseText);loadComments(pitch_id);}
								})
    }

	function updateCommFields(response){
		Element.toggle($('post_comm_div'));
		$('tar_comments').value = '';
		Element.hide('post_comm_div');
		$('btn_comm_submit').disabled = false;
		updateCommentCounts(response);
		loadComments($F('hid_pitch_id'));
	}

	function updateCommentCounts(response) {
		if (response != '') {
			arr_val = response.split("|&&|");
			$('id_comment').innerHTML = arr_val[1] + ' comment' + ((arr_val[1]<=1) ? '' : 's');
		}
	} 

	function loadComments(pitch_id) {
		loading($("id_comments"));

		new Ajax.Updater('id_comments', '/pitch/pitch_comments',
						{
							asynchronous:true,
							evalScripts:true,
							parameters:'pitch_id='+pitch_id
						})
	}

	function submitReplyNewsComment(news_id, comm_id) {
		if ($('tar_comments_'+comm_id).value == '') {
    		alert("please add some comments");
			return false;
    	}
	}
	function submitNotes(pitch_id){
    	if ($('txt_note').value == '') {
    		alert("A note cannot be blank");
    	} else {
			$('btn_note_submit').disabled = "disabled";
			Element.toggle($('btn_note_cancel'));
			var ajax = new Ajax.Request('/pitch/add_note',
								{
									parameters: "note="+escape($F('txt_note'))+"&pitch_id="+pitch_id,
									asynchronous: true,
									evalScripts: true,
									onComplete: function(request){completeNote(pitch_id, request.responseText)}
								})
    	}
    }

	function removeNote(note_id, pitch_id){
   		var ajax = new Ajax.Request('/pitch/remove_note',
								{
									parameters: "note_id="+note_id+"&pitch_id="+pitch_id,
									asynchronous: true,
									evalScripts: true,
									onComplete: function(request){loadNotes(pitch_id)}
								})
    }

    function completeNote(pitch_id, response){
		$('btn_note_submit').disabled = false;
		Element.toggle($('btn_note_cancel'));
		$('txt_note').value = '';
		Element.hide('post_note_div');
		loadNotes(pitch_id);
    }

	function loadNotes(pitch_id) {
		loading($("id_notes"));
		new Ajax.Updater('id_notes', '/pitch/pitch_notes',
				{asynchronous:true, evalScripts:true, parameters:'pitch_id='+pitch_id}
			)
	}

	function changeCountry(val, obj) {
    	if (val=='United States') {
    		$('id_country').style.display = 'block';
    		$(obj+'_state').focus();
    	} else {
    		$('id_country').style.display = 'none';
    	}
    }

    function loading(div_object){
    	div_object.innerHTML = '<div class="loading"></div>';
    }

    function markInappropriate(id) {
		if (confirm('Are you sure you want to mark this pitch as inappropriate?')) {
			new Ajax.Request('/user/mark_inappropriate',
				{
					asynchronous:true,
					evalScripts:true,
					onComplete:function(request){Element.hide('id_inappropriate');$('id_inappropriate_disp').innerHTML=request.responseText},
					parameters:'id='+id
				})
		}
    }

	function open_popup_window(target_path, width, height) {
		popup = window.open(target_path, 'popupwindow', 'width='+width+', height='+height+', scrollbars=1, resizable=0, menubar=0, location=0, toolbar=0')
		popup.focus();
	}

	function addEmailFromText(e){
		var keycode = e.which;
		if (keycode == undefined) keycode = e.keyCode;
		if (keycode == 13) {
			addEmail();
			Event.stop(e);
		}
	}

	function editDocumentTitle(id, title) {
		params = "id="+id+"&title="+$(title).value;
		new Ajax.Request('/pitch/edit_document',
				{
					asynchronous:true,
					onComplete:function(request){onEditComplete(id, request.responseText)},
					parameters:params
				})
	}
	function onEditComplete(id, value) {
		Element.show('id_'+id);
		Element.hide('edit_'+id);
		$('title_'+id).innerHTML = value;
	}

	function disable_forms(id, action)
	{
		$(action+'_disabler_'+id).style.height = $('item_'+id).offsetHeight+"px";
		$('move_message_'+id).style.display = '';
		$(action+'_disabler_'+id).style.display = '';
		$(action+'_inner_text_'+id).style.display = '';
	}

	function enable_forms(id, action)
	{	$('move_message_'+id).style.display = 'none';
		$(action+'_disabler_'+id).style.display = 'none';
		$(action+'_inner_text_'+id).style.display = 'none';
	}


	function move(id,pitch_id){
	  var list = $('sortable_items').getElementsByTagName('li');

	  var items = $A(list);
	  items.each(function(it) {
	   it.className = 'sortable_li';
	  });
	  if (id == '')
		  Sortable.create("sortable_items", {onUpdate:function(){$('loading').show();new Ajax.Request('/pitch/update_network_list/'+pitch_id, {asynchronous:true, evalScripts:true, onComplete: function(request){$('loading').hide();},parameters:Sortable.serialize("sortable_items")})}, only:'sortable_li'} );
	  else
		 Sortable.create("sortable_items", {onUpdate:function(){$('loading').show(); new Ajax.Request('/pitch/update_documents_list/'+pitch_id, {asynchronous:true, evalScripts:true, onComplete: function(request){$('loading').hide();}, parameters:Sortable.serialize("sortable_items")})}, only:'sortable_li'});

	 //  Sortable.create("sortable_items", {onUpdate:function(){new Ajax.Request('/pitch/update_network_list/'+pitch_id, {asynchronous:true, evalScripts:true, parameters:Sortable.serialize("sortable_items")})}, only:'sortable_li'});
	//  disable_forms(id, 'move');
	 }

	function validateCurrency( fld )
	{
       if(/^\d+$/.test(fld.value) && fld.value > 0)
		    fld.value=fld.value.split("").reverse().join("").replace(/(\d{3})/g,"$1 ").replace(/,$/,"").split("").reverse().join("");
		if (fld.value == 0)
			fld.value =0;
	}

	function removeSpaces(fld) {
		var tstring = "";
		string = '' + fld.value;
		splitstring = string.split(" ");
		for(i = 0; i < splitstring.length; i++)
		tstring += splitstring[i];
		fld.value= tstring;
	}

    function noNumbers(e)	{
		var keynum
		var keychar
		var numcheck

		if(window.event) // IE
		{
			keynum = e.keyCode
		}
		else if(e.which) // Netscape/Firefox/Opera
		{
			keynum = e.which
			if (keynum<=31)
				return true;

		}
		else
			return true;

		keychar = String.fromCharCode(keynum)
		numcheck = /\d/
		return ( numcheck.test(keychar) || keychar=='')
	}


	   function checkLogoField(fieldname) {
			logo=$(fieldname).value.toLowerCase();
			var ext = logo.substr(logo.lastIndexOf('.')+1);
			if (logo ==''){
				alert("Please enter the correct path for image");
				return false;
			}
			if (ext == 'jpg' || ext == 'jpeg' || ext == 'png' || ext == 'gif'){
				return true;
			}else{
				alert("Only png, jpg ,jpeg or gif extensions are supported");
				return false;
			}
		}

var slider = {
	sliderId:0,
	currentPage:0,
	sliderLength:0,
	autoRun:0,
	startSlider: function(sliderid, sliderlength, autorun) {
		sliderId = sliderid;
		sliderLength = sliderlength;
		autoRun = autorun;
		window.setTimeout(function(){slider.show(0, 1)}, autoRun);
		Element.show('navigation-bar');
	},
	show: function(previousPage, nextPage){
		Effect.Fade($(sliderId+previousPage));
		nextPageName=sliderId+nextPage;
		window.setTimeout("Effect.Appear($(nextPageName), {duration:3})", 1000);
		$('current_slide_no').innerHTML=nextPage+1;
		currentPage = nextPage;
		window[sliderId+"timer"]=setTimeout(function(){slider.nextSlide()}, autoRun);
	},
	nextSlide: function(){
		nextPage = (currentPage==sliderLength) ? 0 : currentPage+1;
		this.show(currentPage, nextPage);
	},
	previous: function(){
		previousPage = (currentPage==0) ? sliderLength : currentPage-1;
		clearTimeout(window[sliderId+"timer"]);
		this.show(currentPage, previousPage);
	},
	next: function(){
		nextPage = (currentPage==sliderLength) ? 0 : currentPage+1;
		clearTimeout(window[sliderId+"timer"]);
		this.show(currentPage, nextPage);
	},
	mouseOver: function() {
		clearInterval(window[sliderId+"timer"]);
	},
	mouseOut: function() {
		window[sliderId+"timer"]=setTimeout(function(){slider.nextSlide()}, autoRun);
	}
}

function toggleInboxMenu(menu_item_obj, menu_image_obj) {
	if ($(menu_item_obj).style.display == 'none') {
		Element.show(menu_item_obj);
		$(menu_image_obj).src = '/images/left_menu_close.gif';
	}
}

function addEmailAddress(email_url, email_address, action_type, id) {
	if (confirm("Do you want to add \"" + email_address + "\" to your account?")) {
		redirect_url = '/user/addoutside_email?email=' + email_url + '&action_type=' + action_type;
		if ( id > 0 ) {
			redirect_url += '&message_id=' + id
		}
		window.location = redirect_url;
	}
}

function Expand(lines) {
	agt=navigator.userAgent.toLowerCase();
	this.height = lines*1.27;
	this.pixHeight = parseInt(lines*15.2);
	if (agt.indexOf("safari") != -1) {
		this.height = lines*119/100;
		this.pixHeight = parseInt(lines*76)/10;
	}
}

Expand.prototype.toggle = function (container) {
  var opDiv = "opacity_div_" + container;
  if ( $(opDiv) ) {
    if ($(opDiv).style.display == 'none') {
      $(opDiv).style.display = 'block';
    }
    else $(opDiv).style.display = 'none';
  }
  
	if ($(container).style.height==this.height+'em') {
		$(container).style.height='auto';
	} else {
		$(container).style.height=this.height+'em';
	}
}

Expand.prototype.cleanup = function () {
	links = document.links;
	for(var i=0; i < links.length; i++) {
		if(links[i].id.match('link_to_')) {
			container = links[i].id.replace('link_to_','');
			if(($(container).offsetHeight < this.pixHeight) ) {
				$(container).style.height = 'auto';
			} else if($(container).offsetHeight < 150*this.pixHeight/100) {
				$(container).style.height = 'auto';
			} else	{
				$(container).style.height = this.height+'em';
				$(links[i].id).style.display = 'inline';
        var opDiv = "opacity_div_" + container;
        if ( $(opDiv) ) $(opDiv).style.display = 'block';
			}
		}
	}
}

function countChecked(obj) {
	if("undefined" != typeof(maximum)) {
		var message = 'You can choose a maximum of ' + maximum + ' categories for your company profile';
		if(obj!=undefined && obj.form!=undefined) {
			form = $(obj.form.name) ? $(obj.form.name) : obj.form;
			var categories = form.getInputs('checkbox',obj.name);
			var counter = 0;
			total = categories.length;
			var i = 0;
			for(i; i < total; i++) {
				if(categories[i].checked) counter++;
			}
			if(counter > maximum && obj.checked == true) {
				obj.checked = false;
				alert(message);
			}
		}
	}

}

// used in edit news; insert a hidden input with the mime type of the image to be uploaded to s3
function setS3ContentTypeAndExtension( input_id, content_type_id, key_id )
{
	var err_message = "Only png, jpg ,jpeg or gif extensions are supported!";
	var name_and_path = $(input_id).value.toLowerCase( );
	if( name_and_path.length == 0 )
	{
		alert( 'Please select a file!' );
		return false;
	}
	var idx = name_and_path.lastIndexOf( "." );
	if( idx == -1 )
	{
		alert( err_message );
		return false;
	}
	var extension = name_and_path.substr( idx + 1 );
	if( extension == '' )
	{
		alert( err_message );
		return false;
	}
	var mime_type = '';
	switch( extension )
	{
		case 'jpg' :
		case 'jpeg':
			mime_type = 'image/jpeg';
			break;
		case 'gif' :
			mime_type = 'image/gif';
			break;
		case 'png' :
			mime_type = 'image/png';
			break;
		default :
			break;
	}
	if( mime_type == '' )
	{
		alert( err_message );
		return false;
	}
	else
	{
		$(key_id).value += '.' + extension;
		$(content_type_id).value = mime_type
		return true;
	}
}

