/*-----------------------------------------------------------
    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}});
        }
    }
}

/*
 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;
	}
}

