// JavaScript Document
function isEmail(strEmail){
	var patrn = /^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/;
	return patrn.test(strEmail);
}

$(document).ready(function(){
	// main menus - dropdowns
	// =================================================
	$(".sf-menu .li_1:last").css("background-image","none");
	//$(".sf-menu .li_1 ul:last").addClass("lastfix");
	
	$(".sf-menu")
	.superfish({
		animation : { opacity:"show", height:"show" }
	})
	$(".sf-menu")
	.find(">li:has(ul)")
		.mouseover(function(){
			$("ul", this).bgIframe({opacity:false, src:'#'});
		})
		.find("a")
			.focus(function(){
				$("ul", $(".nav>li:has(ul)")).bgIframe({opacity:false});
			});

	// Treatment pages - move 'Other treatments' to the bottom
	$("#li_other-drugs-and-treatments").appendTo( $("#ul_treatments") );
	// Treatment pages - move 'Under FDA Review' to the bottom
	$("#li_under-fda-review").appendTo( $("#ul_treatments") );
	
	//Support Groups Left Menu
	$('#sg ul').hide();
	$("#sg h3").toggle(
		function(){
			$(this).attr("class","prev");
			$("#sg h3").not($(this)).removeAttr("class");
			
			$("#sg ul").not($(this)).slideUp("normal");
			$(this).parent().children("ul").slideDown("normal");
		},
		function(){
			if($(this).hasClass("prev"))
			{
				$(this).parent().children("ul").slideUp("normal");
				$(this).removeClass("prev");
			}
			else
			{
				$("#sg ul").not($(this)).slideUp("normal");
				$(this).parent().children('ul').slideDown('normal');
				$(this).removeClass("prev");
			}
		}
	);
	
	$('#adslides').cycle();
	
	
	$("#archives h4").toggle(
		function(){$("#archives h5[id^='"+$(this).attr("id")+"']").show();$("#archives div[class^='"+$(this).attr("id")+"']").hide();},
		function(){$("#archives h5[id^='"+$(this).attr("id")+"']").hide();$("#archives div[class^='"+$(this).attr("id")+"']").hide();}
	);
	$("#archives h5").toggle(
		function(){
			$(this).next("div").show();
			if ($(this).next("div").text().length<20)
			{
				$(this).next("div").text("Loading...");
				var str=$.trim($(this).attr("id"));
				var y=str.substring(1,5).toString();
				var m=str.substring(7).toString();
				$(this).next("div").load("/news/load/"+y+"/"+m);
			}
		},
		function(){$(this).next("div").hide();}
	);

	
	//build an anchor list in the left column
	if($(".secondleft").text().replace(/\s/g,'').length<20)
	{
		var strHtml='';
		$(".secondright a[name]").each(function(){
			strHtml=strHtml+'<li><a href="#'+$(this).attr("name")+'">'+$(this).text()+'</a></li>';
		});
		
		if (strHtml!='')
		{
			strHtml='<ul>'+strHtml+'</ul>';
			$(".secondleft h2").after(strHtml);
		}
	}

	$("#login input:first").focus();
	
	// Tips & Tricks left column
	/*if (document.location.href.indexOf('/coping/tips/') > 0) {
		// Load the Tips & Tricks sidebar from this url:
		var url = '/coping/tips/index.html';
		$(".secondleft ul").html('<li>Loading...</li>')
		    .load(url+' .secondleft ul');
	}*/



	// Add Pictures Page
	var randomPicnumber=Math.floor(Math.random()*111111)
	var picType = $.query.get('Type');
	if (picType == 'photoalbum') {
	}else{
		$("#uploadify").uploadify({
			'uploader'       : '/inc/uploadify/uploadify.swf',
			'script'         : '/inc/uploadify/uploadify.php',
			'cancelImg'      : '/inc/uploadify/cancel.png',
			'folder'         : '/temp/'+randomPicnumber,
			'queueID'        : 'fileQueue',
			'fileDesc'	 : '*.jpg',
			'fileExt'	 : '*.jpg',
			'sizeLimit'	 : '2000000',
			'auto'           : true,
			'multi'          : true,
			'onComplete'	 : function(event, queueID, fileObj, response, data) {
					     $('#filesUploaded').append(fileObj.name+'<br>');
					     $('#randomPicnumber').val(randomPicnumber);
					     alert($('#randomPicnumber').val());
						}
		});
	}
	
	// Insert the "Add This" button
	$("#addthis").html('<a href="http://www.addthis.com/bookmark.php?v=250&pub=xa-4a5a6e9d27f6cb06" '+
			'onmouseover="return addthis_open(this, \'\', \'[URL]\', \'[TITLE]\')" onmouseout="addthis_close()"'+
			' onclick="return addthis_sendto()"><img src="/images/lg-share-en.gif"'+
			' width="125" height="16" alt="Bookmark and Share" style="border:0"/></a>'+
			'<script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js?pub=xa-4a5a6e9d27f6cb06">'+
			'</script>'
	);

	// Google Analytics - tracking code UA-11537798-1
	$.geekGaTrackPage('UA-11537798-1');
	
	// Bind facebox link click
	jQuery('a[rel*=facebox]').facebox();
	
	// For poll
	$(".poll-link").click(function(e) {
		if ($("#pollmenuwrap div").length > 0)
		{
			// Put the contents of the #pollmenuwrap element into the facebox	
			$.facebox( $("#pollmenuwrap").html() );
			// Empty the #pollmenuwrap element
			$("#pollmenuwrap").empty();
		}
		else
		{
			// The #pollmenuwrap element is blank - reload via AJAX
			$.get('/poll', function(data) { $.facebox(data) })
		}
		e.stopPropagation();
		return false;
	});
	
	// Bind a handler for facebox onload
	$(document).bind('reveal.facebox', bindPollFaceboxEvents);
		
	// Bind click handlers for WebBoard registration buttons
	$("#webboard-proceed").click(function(e){
		// Redirect to page 2
		document.location.href='/connect/register-02';
	});
	$("#webboard-agree").click(function(e){
		// Redirect to registration page 3
		document.location.href='/webboard/register-03.php';
	});
	$("#webboard-disagree").click(function(e){
		// Redirect to home page
		document.location.href='/';
	});
	
});

function bindPollMenuEvents()
{
	$("#pollview").unbind('click').click(function(e){
       	$.post('/poll/view', function(data) { $.facebox(data) })
       	e.stopPropagation();
       	return false;
	});
	$("#pollresults").unbind('click').click(function(e){
		// show loading
       	$.post('/poll/results', function(data) { $.facebox(data) });
       	e.stopPropagation();
       	return false;
	});
	$("#pollarchive").unbind('click').click(function(e){
       	$.post('/poll/archive', function(data) { $.facebox(data) })
       	e.stopPropagation();
       	return false;
	});
	/*$("#pollhome").unbind('click').click(function(e){
       	jQuery(document).trigger('close.facebox');
       	e.stopPropagation();
       	return false;
	});*/
}

/* Bind Poll Facebox Events */
function bindPollFaceboxEvents(e){
	// Scroll to the top
	$(window).scrollTop(0);
	// When the facebox has loaded, bind the poll form submission handler
	//alert('loaded facebox, content='+$("#voteform").html());
	$("#voteform").validate(
		{
			invalidHandler: function(form, validator){return false;},
		    submitHandler: function(form){
		    	// Show loading animation
		    	//$("#facebox .content").html('<img src="/images/facebox/loading.gif" />');
		    	jQuery(document).trigger('loading.facebox');
		        $(form).ajaxSubmit({
		        	// When the server responds, run this function
					success:function(response){
						//alert('response='+response);
						$.facebox(response);
						// Bind facebox link click
						//jQuery('#PreviousPoll a[rel*=facebox]').facebox();
					}
				});
        		return false; 
        	}
		}
	);
	// Bind facebox link click
	jQuery('#PreviousPoll a[rel*=facebox]').facebox();
	
	// Bind a handler for facebox onload
	$(document).unbind('reveal.facebox').bind('reveal.facebox', bindPollFaceboxEvents);
	
	bindPollMenuEvents();
}
