/*	FUNCTIONS */

	function close_xchange_confirm()
	{
		$('#xchange_confirm').jqmHide();
	}
	
	function set_cookie(name, value, exp_y, exp_m, exp_d, path, domain, secure )
	{
		var cookie_string = name + "=" + escape(value);
		if (exp_y) {
			var expires = new Date(exp_y, exp_m, exp_d);
			cookie_string += "; expires=" + expires.toGMTString();
		}
	    cookie_string += "; path=" + escape(path);
		if (domain) {
			cookie_string += "; domain=" + escape(domain);
		}
		if (secure) {
			cookie_string += "; secure";
		}
		document.cookie = cookie_string;
	}
	
	function readCookie(cookieName)
	{
		var theCookie=""+document.cookie;
		var ind=theCookie.indexOf(cookieName);
		if (ind==-1 || cookieName=="") {
			return "";
		}
		var ind1=theCookie.indexOf(';',ind);
		if (ind1==-1) {
			ind1=theCookie.length;
		} 
		return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
	}
	
	function popLogin()
	{ 
		$('#alert_modal_container').jqm({ 
			ajax: '/includes/modules/login.php?alert=1', 
			target: false, 
			modal: true 
		}).jqmShow(); 
	} 
	
	function is_logged_in()
	{
		return (readCookie('user_id') > 0) ? true : false;
	}
	
	function fbs_click()
	{
		u = location.href;
		t = document.title;
		window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
	}
	
	function toggle_markers(index,value,position,toggle)
	{
		var i = 0;
		for (i=0; i<gmarkers.length; i++) {
			var this_cat = gmarkers[i].gmcategory.split('_');
			if (this_cat[index] == value) {
				if(position=='on'){
					gmarkers[i].show();
				}else{
					gmarkers[i].hide();
				}
			}else{
				if(toggle==1){
					gmarkers[i].hide();	
				}
			}
		}
		return false;
	}
	
	function selmem(name,id)
	{
		$('#username').val(name);
		$('#username').addClass('live_search_suc');
		$('#member_id').val(id);
		$('div.live-search-results').slideUp(100);
		return false;
	}
	
	function rm_invite(obj)
	{
		$(obj).parent().fadeOut('fast',function(){ $(obj).remove(); });
		return false;	
	}
	
	
	function cal_sifr(){
		if(typeof sIFR == "function" && !sIFR.UA.bIsIEMac && (!sIFR.UA.bIsWebKit || sIFR.UA.nWebKitVersion >= 100)){
			sIFR.replaceElement("#events_calendar .heading2 h3", named({
				sFlashSrc: trade_gothic, 
				sColor: "#FFFFFF", sWmode: 'transparent', sCase: 'upper', 
				nPaddingTop: 0, nPaddingRight: 0, nPaddingBottom: 0, nPaddingLeft: 0,
				sFlashVars: 'textalign=center'
			}));
		}
	}





/* ------------------------------------------------------------------------------------------------*/


/* DOCUMENT READY */


$(document).ready(function() {

	tooltip();
	
	$('textarea').focus(function(){
		if ($(this).val() == $(this).attr('title')) {
			$(this).val('');	
		}
	}).blur(function(){
		if ($(this).val() == '') {
			$(this).val($(this).attr('title'));	
		}
	});
	
	
	// Opt-In/Out Bulletin post notification
	$("input.opt_notify").click(function(){
		
		var obj = $(this);
		var opt = 0;
		var type = $(obj).attr('id');
		var user = $(obj).val();
		
		if($(obj).is(':checked')) {
			opt = "1";
		}
		
		var data = {
			'type': type,
			'opt': opt,
			'user': user
		};
		$.post('/includes/helpers/jquery.notify.php', data, function(response){
			$(obj).parent().after('<div id="'+type+'_opt_message" class="opt_message>'+response+'</div>');
			setTimeout(function(){ $("#"+type+"_opt_message").fadeOut(); }, 2000);
		});
		
	});
	
	
	// force blog post links to open in new window
	$("#blog_page #blog p a:not(a.alt)").attr('target','_blank');
	
		
	// Live-Search
	$('.usersearch').liveSearch({ajaxURL: '/includes/helpers/jquery.usernamesearch.php?q='});
	$('#users_add').hide();
	
	
	// Modals
	$('a.fancyit').fancybox({ 'overlayOpacity' : 0.5, 'titlePosition'  : 'over' });
	$('a.iframe').fancybox({ 'overlayOpacity' : 0.5 });
	$('a.fancyvideo').fancybox({ 
		'overlayOpacity' : 0.5, 
		'padding' : 0, 
		'transitionIn' : 'none', 
		'transitionOut' : 'none', 
		'type' : 'iframe', 
		'titleShow' : false, 
		'showNavArrows' : false,
		'width' : '75%',
		'height' : '75%',
		'scrolling' : 'no'
		});
	
	
	
	// Login Modal
	$('#login_modal_container').jqm({ ajax: '/includes/helpers/jquery.login.php', trigger: 'a.modal' });
	$('#alert_modal_container').jqm({ ajax: '/includes/helpers/jquery.login.php?alert=alert', trigger: '.alert' });
	
	if($('#manual_modal').length>0)
	{
		$('#alert_modal_container').jqmShow({
			ajax: '/includes/helpers/jquery.login.php?alert=alert'
		});
	}


	// Mailing List
	$('#join_mailing_list').bind('click', function() {
		join_mailing_list($("#name").val(),$("#email").val());											
		return false;												
	});
	
	
	// Text Counter
	if($("textarea.limit").length>0)
	{
		$("textarea.limit").textlimit('p.counter span',parseFloat($('textarea.limit').attr('rel')));
	}
	
	
	// Facebook Share
	$('a.fs').click(function(){
		if ($(this).hasClass("fbs_click"))
		{ 
			fbs_click();
		}
		$(this).parents('form').submit();	
		return false;
	});


	// Add/Remove
	$("a.addit").click(function(){
		var this_button = $(this);
		if ($(this_button).hasClass('r'))
		{
			var goahead = confirm("Are you sure you want to remove this item?");
			if (!goahead) { 
				return false;
			}
		}
		$.post("/includes/helpers/jquery.book.php", { vars: $(this).attr('id') }, function(response) {
			if ($(this_button).hasClass('r')) {
				$('#'+response).animate({opacity: 'toggle', height: 'toggle'});
			} else {
				$(this_button).html('<i class="added"></i><b>'+response+'</b>');
			}
		});
		$(this).removeClass('addit');
		$(this).removeClass('button');
		$(this).removeClass('button_2');
		$(this).addClass('sm_active');
		return false;
	});
	
	
	$("a.block_connection").click(function(){
		var this_button = $(this);
		$.post("/includes/helpers/jquery.book.php", { vars: $(this_button).attr('id') }, function(response) {
			$(this_button).parents("div.connection").animate({opacity: 'toggle', height: 'toggle'});
		});
		return false;
	});
	
	
	// Remove from User Account
	$("a.admin_r").click(function(){
		var goahead = confirm("Are you sure you want to remove this item?");
		if (!goahead) { 
			return false;
		}
		$.post("/includes/helpers/jquery.profile.php", { vars: $(this).attr('rel') }, function(response) {
			$('#'+response).slideToggle();
		});
		return false;
	});
	
	
	// Remove from User Account
	$("a.requester").click(function() {
		var this_button = $(this);
		if ($(this_button).hasClass('r'))
		{
			var goahead = confirm("Are you sure you want to remove this item?");
			if (!goahead) { 
				return false;
			}
		}
		$.post("/includes/helpers/jquery.requests.php", { vars: $(this).attr('rel') }, function(response) {
			if ($(this_button).hasClass('r')) {
				$('#'+response).slideToggle();
			} else {
				$(this_button).parent().html('<strong>Request Accepted!</strong>');
			}
		});
		return false;
	});
	
	
	
	// Flag
	$("a.flagit").click(function(){
		var this_button = $(this);
		$.post("/includes/helpers/jquery.flag.php", { vars: $(this).attr('rel') }, function(response) {
			$(this_button).html(response);
		});
		return false;
	});
	
	
	// Comment delete
	$("a.deleteit").click(function(){
		var this_button = $(this);
		if (confirm("Are you sure you want to delete?")) {
			$(this_button).html("Deleting...");
			$.post("/includes/helpers/jquery.delete.php", { vars: $(this).attr('rel') }, function(response) {
				$(this_button).html(response);
			});
		}
		return false;
	});
	
	
	// Mail message delete
	$("a.delete_mail").click(function(){
		var this_button = $(this);
		if(confirm("Are you sure you want to delete?")){
			$.post("/includes/helpers/jquery.mail.delete.php", 
				{ vars: $(this).attr('rel') },
				function(response){
					$(this_button).html(response);
					if(response != "Error"){
						if($('#inbox .inbox_item').length == 1){
							$(this_button).parents('.inbox_item').after('<li>You have no messages.</li>');
						}
						$(this_button).parents('.inbox_item').slideUp('100');
					}
				}
			);
		}
		return false;
	});
	
	
	// RSVP
	$(".rsvp").click(function() {
		if (!$(this).hasClass('alert')) {
			$('li.rsvp').html('<img src="/assets/images/ajax-loader-2.gif" alt="" />');
			$.post("/includes/helpers/jquery.rsvp.php", { vars: $(this).attr('rel') }, function(response) {
				$('li.rsvp').html(response);
			});
		}
		return false;
	});
	
	
	$('#invite_form_add').click(function(){
		var name_html = $('#invite_form').html();
		$('#submit_row').before('<div class="row">'+name_html+'<a href="#" onclick="rm_invite(this); return false;" title="Remove"><img src="/assets/images/cancel.png" class="inr" alt="Remove" /></a></div>');
		return false;
	});

	
	
	$('#xchange_confirm').jqm({modal: true, toTop: true});
	  
	// trigger a confirm whenever links of class alert are pressed.
	$('#xchange_page a.xchange_option').click(function() { 
		
		if ($(this).hasClass('alert')) {
			return false;
		}
		
		$('#xchange_confirm').jqmShow().html('<div id="modal"><a class="jqmClose close_button" href="#"><img width="21" height="21" alt="Close" src="/assets/images/modal_close.png"></a><div class="modal_content"><p>Are you sure you would like to submit that you have completed:<br /><br /> <strong>'+$(this).text()+'</strong></p></div><div class="buttons"><a href="#" class="button" rel="'+$(this).attr('rel')+'"><i>Yes</i></a> <a href="#" class="button"><i>No</i></a></div></div>').end()
		.find('a.button')
			.live('click', function() {
				if($(this).text() == 'Yes') {
					$.post("/includes/helpers/jquery.xchange.php", { info: $(this).attr('rel'), comment: '' }, function(response) {
						$("#xchange_confirm .buttons").remove();
						$("#xchange_confirm .modal_content").html(response);	
						setTimeout("close_xchange_confirm()", 2500);				 		
					});
				} else {
					$('#xchange_confirm').jqmHide();
				}
				return false;
			}).end()
		.find('a.jqmClose')
			.live('click', function() {
				$('#xchange_confirm').jqmHide();
				return false;
			});
		return false;
	});
	

	$("#custom_xchange a.post_xchange").click(function(){
		var $_info;
		
		if ($("#custom_xchange select").length > 0)
		{
			$_info = $("#custom_xchange select").val()+'_'+$("#custom_xchange #custom_xchange_info").val();
		}
		else
		{
			$_info = $("#custom_xchange #custom_xchange_info").val();
		}
		$.post("/includes/helpers/jquery.xchange.php", { info: $_info, comment: $("#custom_xchange textarea").val() }, function(response) {
			if (response != '') {
				$('#xchange_confirm').jqmShow().html('<div id="modal"><div class="modal_content">'+response+'</div></div>');
				setTimeout("close_xchange_confirm()", 2500);
				$("#custom_xchange textarea").val('');
			}
		});
		return false;
	});
	
	
	// activate stats scroller on stories page
	$("#scroller").scrollable({
		items: '.list',
		loop: true,
		size: 1
	}).autoscroll({ 
		autoplay: true,
		interval: 6000,
		autopause: true
	}).circular().navigator();
	
	
	// activate xchange feed scroller
	$(".xchange_feed").scrollable({
		items: '.feed_items',
		loop: true,
		speed: 800,
		margin: -323,
		size: 3,
		onSeek: function(event, index){
			var items = this.getItems();
			$(items).removeClass('active');
			$(items).eq(index+1).addClass('active');
		}
	}).autoscroll({ 
		autoplay: true,
		interval: 6000,
		autopause: true
	})
	.end().find('.feed_items .entry').eq(1).addClass('active');
	
		

	// Invite - Import toggler
	$(".import_link").click(function(){
		$("#import_form").slideToggle();
		$("#invite_form").slideToggle();
		return false;
	});
	
	
	// Toggle Markers
	$('a.gmtoggle').click(function() {
		if ($('#map').css('display') == 'none') {
			$('#mapan').fadeOut('fast',function(){$('#map').fadeIn('fast');});
			map.checkResize();
		}	
		map.checkResize();
		toggle_markers($(this).attr('rel'));
		return false;
	});
	
	
	// Toggle Map Markers
	$(".map_toggler").click(function(){
		var specs = $(this).attr('rel').split('_');	
		toggle_markers(specs[0],specs[1],specs[2],specs[3]);									 
	});
	
	
	// turn on/off map sections (people, groups, etc) - does not not control filters within sections
	$(".map_toggler2").click(function(){
		var sectionList = $("#sections").val();
		sectionList = sectionList.split("~");
		
		var section = $(this).attr("rel");
		
		// update show/hide label
		if($(this).attr("checked") === true){
			sectionList.push(section);
		} else {
			var index_value = $.inArray(section, sectionList);
			var range = 1;
			sectionList.splice(index_value,range);
		}
		
		// update section visibility
		map_get_markers(sectionList);
	});
	
	
	// Story text toggler
	$(".story_toggler").click(function(){
		$(this).parent().parent().toggleClass("full_story");
		if($(this).html() == "Read full story"){
			$(this).html("Show story overview");
			$("#story_intro").fadeOut("fast",function(){$("#story_details").fadeIn();});
		} else if($(this).html() == 'Show story overview') {
			$(this).html("Read full story");
			$("#story_details").fadeOut("fast",function(){$("#story_intro").fadeIn();});
		} else if($(this).html() == 'Leer el escenario completo') {
			$(this).html("Listado escenario");
			$("#story_intro").fadeOut("fast",function(){$("#story_details").fadeIn();});
		} else {
			$(this).html("Leer el escenario completo");
			$("#story_details").fadeOut("fast",function(){$("#story_intro").fadeIn();});
		}
		return false;
	});
	
	
	// Make Things Clickable
	$(".clickable").click(function(){
		var linkURL = $(this).children("a").attr("href");
		if (!linkURL) {
			linkURL = $(this).children("div").children("a").attr("href");
		}
		window.location.href = linkURL;
		return false;
	});
	
	
	// Toggle	
	$(".toggler").click(function(){
		obj = $(this).attr("rel");
		$('#'+obj).slideToggle("fast");
		if(obj == "comment_form" || obj == "topic_form"){
			sIFR.replaceElement('#'+obj+' .heading1 h2', named({
				sFlashSrc: trade_gothic, 
				sColor: "#FFFFFF", sWmode: 'transparent', sCase: 'upper',
				nPaddingTop: 0, nPaddingRight: 0, nPaddingBottom: 0, nPaddingLeft: 0
			}));
		}
		return false;
	});
	
	
	// Toggle	
	$(".toggler_true").click(function(){
		obj = $(this).attr("rel");
		$('#'+obj).slideToggle("fast");
		return true;
	});
	
	
	// Collapser
	$(".collapser").click(function(){
		if($(this).hasClass("collapsed")){
			$(this).removeClass("collapsed");
		} else {
			$(this).addClass("collapsed");
		}
		$('#'+$(this).attr("rel")).toggle();
		return false;
	});
	
	
	
	// Tabs
	$("ul.tabs").tabs('div.tabs_wrapper > .tab_content');
	// end tabs
	
	
	// Add a Comment
		$("a.post_comment").click(function(){
		
			if (($('#comment').val() == $('#comment').attr('title')) || ($('#comment').val() == '')) {
				alert('Please enter a comment.');
				return false;
			}
				
			$('#comments a.comment').fadeOut('fast');
			// record it		
			$.post("/includes/helpers/jquery.add_comment.php", {	
				user_id: $('#user_id').val(), 
				val: $('#val').val(), 
				type: $('#type').val(), 
				comment: escape($('#comment').val()),
				story: $('input[name="story"]:checked').val() 
				}, function(response) {
					$('#comment_form').fadeOut('fast').html('<div class="message"><p>Thank you. Your comment has been submitted!</p></div>').fadeIn('fast');
				}
			);
			
			if ($(this).hasClass("fbs_click")) {
				fbs_click();
			}
			
			return false;
		});
	// end add comment
	
	
	// Facebook share checkbox
		$("#facebook_share").click(function(){
			if($("#facebook_share:checked").length === 0){
				// remove onclick event from form post button
				$("a.post_comment").removeClass("fbs_click");
				$("a.fs").removeClass("fbs_click");
			} else {
				// add onclick event to form post button that will fire Facebook share dialog
				$("a.post_comment").addClass("fbs_click");
				$("a.fs").addClass("fbs_click");
			}
		});
	// end facebook share
	
	
	// Add a response
	$('a.post_response').click(function(){ 
		$('#post_response').submit();
		return false;
	});


	// Signup Form
		$("#display_name").blur(function(){
			$("#usernameLoading").show().html('<div class="error checking">Checking Availability...</div>');
			var this_case = $(this).attr('rel');
			$.post("/includes/helpers/jquery.form_checks.php?case="+this_case, { username: $("#display_name").val() }, function(response) {
				$("#usernameLoading").html(response);
			});
			return false;
		});
	// end signup form
	
	
	
	// SITE NAVIGATION - SUB-NAVIGATION
		$("#site_nav li").hover(function(){
			$(this).addClass("sfhover");
		}, function(){
			$(this).removeClass("sfhover");
		});
	// end site nav
	
	
	
	// SITE NAV : Feature Rollovers
		var imagine_config = {
			sensitivity: 8,
			interval: 200,
			over: function(){ $("#imagine_rollover").fadeIn(); },
			timeout: 500,
			out: function(){ if (!$("#imagine_rollover").hasClass('active')) { $("#imagine_rollover").fadeOut(); } }
		};
		$("a.feature_imagine").hoverIntent(imagine_config);
	
		var act_config = {
			sensitivity: 8,
			interval: 200,
			over: function(){ $("#act_rollover").fadeIn(); },
			timeout: 500,
			out: function(){ if (!$("#act_rollover").hasClass('active')) { $("#act_rollover").fadeOut(); } }
		};
		$("a.feature_act").hoverIntent(act_config);
		
		$("#imagine_rollover, #act_rollover").hover(function(){
			$(this).addClass('active');
		}, function(){
			$(this).removeClass('active');
			$(this).fadeOut();
		});
		
		$("body").click(function(){
			$("#act_rollover").fadeOut();
			$("#imagine_rollover").fadeOut();
		});
	// end nav feature rollovers
	
	
	
	// Rounded corners
	$(".roundme").css("position", "relative").append('<div class="corner_lt"></div><div class="corner_rt"></div><div class="corner_rb"></div><div class="corner_lb"></div>');
	$(".roundme_2").css("position", "relative").append('<div class="corner_lt"></div><div class="corner_rt"></div><div class="corner_rb"></div><div class="corner_lb"></div>');

});




    


/* ------------------------------------------------------------------------------------------------*/


/* PLUGINS */



/*
 * TextLimit - jQuery plugin for counting and limiting characters for input and textarea fields
 * 
 * pass '-1' as speed if you don't want slow char deletion effect. (don't just put 0)
 * Example: jQuery("Textarea").textlimit('span.counter',256)
 *
 * $Version: 2007.10.24 +r1
 * Copyright (c) 2007 Yair Even-Or
 * vsync.design@gmail.com
 */ 
jQuery.fn.textlimit=function(counter_el,thelimit,speed,toggleTrim){var charDelSpeed=speed||15;var toggleCharDel=speed!=-1;var red_alert=false;var that=this[0];updateCounter();function updateCounter(){jQuery(counter_el).text(thelimit-that.value.length)};this.keypress(function(e){if(this.value.length>=thelimit&&e.charCode=='44540')e.preventDefault()}).keyup(function(e){updateCounter();if(this.value.length>=(thelimit-10)){jQuery(counter_el).css({color:'#f00'});red_alert=true}else{if(red_alert){jQuery(counter_el).css({color:'inherit'});red_alert=false}};if(this.value.length>=thelimit&&toggleTrim){if(toggleCharDel){that.value=that.value.substr(0,thelimit+100);var init=setInterval(function(){if(that.value.length<=thelimit){init=clearInterval(init);updateCounter()}else{that.value=that.value.substring(0,that.value.length-1);jQuery(counter_el).text('trimming...  '+(thelimit-that.value.length))}},charDelSpeed)}else this.value=that.value.substr(0,thelimit)}})};





/**
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne <brian@cherne.net>
*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);





/*
* Tooltip jQuery script 
* <http://cssglobe.com/post/1695/easiest-tooltip-and-image-preview-using-jquery>
*
* @author Alen Grakalic (http://cssglobe.com)
*/
this.tooltip=function(){xOffset=10;yOffset=20;$("a.tooltip").hover(function(e){this.t=this.title;this.title="";$("body").append("<p id='tooltip'>"+this.t+"</p>");$("#tooltip").css("top",(e.pageY-xOffset)+"px").css("left",(e.pageX+yOffset)+"px").fadeIn("fast")},function(){this.title=this.t;$("#tooltip").remove()});$("a.tooltip").mousemove(function(e){$("#tooltip").css("top",(e.pageY-xOffset)+"px").css("left",(e.pageX+yOffset)+"px")})};