// JavaScript Document

var timestamp10 = false;
var timestamp5 = false;
var filetransfer = false;

$(document).ready(function(){ 

		if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))) {
			
			/*$("#Menu1 ul li").bind("touchend", function(event) {
				var clicked = this;
				
				$("#Menu1 ul li").has('div').each(function(index){
					//alert($(this).children().css("display"));
					if (this != clicked){
					//if ($(this).children().css("display") == "block")
						//$(this).children().css("display", "none");
					}*/
					/*else {
						if ($(clicked).children().css("display") == "block"){
							$(clicked).children().css("display", "none");
							
							//alert("destroy");
						}
						else {
							$(clicked).children().css("display", "block");
							//alert("build");
						}
					}*/
				/*	else {
							//$(clicked).children().css("display", "block");
					} 
				});
				//event.stopPropagation();
				//alert(cleared);
				//event.preventDefault();
			}); 
			
			$("#Menu1 ul li").click(function(){
			});*/
			
			$("#Menu1 ul li").click(function(){
				
				var clicked = this;
				
				$("#Menu1 ul li").has('div').each(function(index){
					//alert($(this).children().css("display"));
					if (this != clicked){
					if ($(this).children().css("display") == "block")
						$(this).children().css("display", "none");
					}
					else {
						if ($(clicked).children().css("display") == "block"){
							$(clicked).children().css("display", "none");
							
							
						}
						else {
							$(clicked).children().css("display", "block");
						}
					}
				});
				
				//var Stuff = 
				//$(this).find("div").css('display', 'none');
				
				//$('#Menu1').focus();
				
				//alert(Stuff.innerHTML);
			});
		}	

        $("ul.sf-menu").supersubs({ 
            minWidth:    12,   // minimum width of sub-menus in em units 
            maxWidth:    35,   // maximum width of sub-menus in em units 
            extraWidth:  1     // extra width can ensure lines don't sometimes turn over 
                               // due to slight rounding differences and font-family 
        }).superfish();  // call supersubs first, then superfish, so that subs are 
                         // not display:none when measuring. Call before initialising 
                         // containing tabs for same reason. 

		// For Autosuggest
		
		var options_xml = {
			script: function (input) { return "/ajax/search/" + input; },
			varname:"input",
			entries:10,
			timeout:6000,
			delay:10,
			cache:false
		};
		var as_xml = new bsn.AutoSuggest('NoteQ', options_xml);

		$("a[rel*=blogfancybox]").fancybox({ 
									   	'titlePosition' : 'over',
										'padding'		: 0,
										'titleFormat'	: formatTitle,
										'transitionIn'  : 'elastic',
										'transitionOut'	: 'elastic'
									   });
		
		$("a[rel*=bannerfancybox]").fancybox({ 
										'padding'		: 0,
										'hideOnContentClick'	: true,
										'showNavArrows'	: false,
										'titleShow'		: false,
										'transitionIn'  : 'elastic',
										'transitionOut'	: 'elastic'
									   });
		
		$('a[rel*=facebox]').livequery(function() {
			$(this).facebox({
				loading_image : 'loading.gif',
				close_image   : 'closelabel.gif'
			  });
		});

		$('#webtop-login').click(function() {
			
			$.fancybox.showActivity();
			
			$.fancybox({
						  	padding: 0,
							disableNavButtons: false,
							modal : true,
							href  : '/ajax/webtopLogin'
			});
		
		});
		
		$('#password-alert').live("click", function() {
			
			jQuery.facebox("<div style='width: 500px;'>Depending on how your company administrator has configured your company's account, this may be a password assigned specifically for remote access only.  If you received a welcome email, it will contain password instructions. If you have difficulty signing on, technical support can be reached at <a href='http://support.anx.com'>Positive Pro support</a></div>");
			return false;
			
		});
		
		$('#cancel-link').live("click", function() {
			
			$.fancybox.close();
			return false;
			
			
		});
		
		
		$('.close-window').live("click", function() {
			
			$.fancybox.close();
			return false;
			
			
		});		
		
		
		// To validate contact form
		
		$(".numeric").format({precision: 14,autofix:false});
				
		// Site search functionality
		
		$("#NoteQ").focus(function() {
			var t = $("#NoteQ").val();
			if (t == 'search site') {
				$("#NoteQ").val('');
			}
		});
		
		$("#NoteQ").blur(function() {
			var t = $("#NoteQ").val();
			if (t == '') {
				$("#NoteQ").val('search site');
			}
		});

		$('#ap_upload_file').mouseover(function() {
			this.style.backgroundImage = 'url(/img/default_action_button_on.png';
		});
		$('#ap_upload_file').mouseout(function() {
			this.style.backgroundImage = 'url(/img/default_action_button_off.png';
		});

		// Round only IE4.0+
		
//		if (!document.all) {
//			$('.rounded').corners();
//			$('.rounded-bottom').corners("5px transparent bottom");
//		}
		
		
		
		// Apply focus to login box if it exists
		
		if( $("#UserLogin").length ) {
			$("#UserLogin").focus();
		}
		
		
		
		// Cycle ticker on splash page
		
		if($('#ticker-cycle').length) {
			$("#ticker-cycle").cycle({
				fx: 'fade',
				pause: true,
				timeout: 5000
			});		
		}
		
		$('#optinEmail').live("keyup", function() { 
			$('#optinEmail').removeClass('SD_error'); 
		});
		
				
		if ( $(".tbpopup").length ) {
			
			content = $('#thickboxcontent').html();
			$.fancybox( content, 
						  { 
						  	padding: 0, 
							modal : false,
							showCloseButton : false
						  }
					  );
		}

		$("#accordion").accordion({ header: "h3" });
				
		$("#tabs").tabs();

		
}); 

function formatTitle( title, currentArray, currentIndex, currentOpts ) {
	return '<div id="fancybox-title" style="width: 100%;"><span id="fancybox-title-over"><strong>' + title + '</strong><br/>' + $('#img-cap-' + currentIndex).html() + '</span></div>';
	
}

function ajaxSubmitComment(val) {
	dataString = $('#CommentAddForm').serialize();
	
	htmlstring  = '<h1>Add Comment</h1>';
	
	htmlstring += '<div style="text-align: center; width: 500px;" >';
	htmlstring += '<p>Please wait while we add your comment.</p>';
	htmlstring += '<div style="width: 34px; margin: 0 auto;" ><img src="/img/indicator_blue_large.gif" alt="loading anim" /></div>';
	
	htmlstring += '</div>';
	
	$('#inlineCommentforTB').html(htmlstring);

	$.ajax({  
	  type: "POST",  
	  url: val.action ,  
	  data: dataString,  
	  success: function(data) {  
		if (data.indexOf('commentadded') != -1) {


			/*

			list  = document.getElementById("comments_ordered_list");
			newel = document.createElement("li");
			
			var newDate = new Date;
			var tempID  = newDate.getTime();
				alert(tempID);
				
				var tempID = new String (tempID);
				
				alert(tempID.length);
				
				lengthOfId = tempID.length - 5;
				alert(lengthOfId);
			    tempID     = tempID.substr( lengthOfId );
				 
				alert(tempID);
				
			newel.setAttribute('id', tempID);
			newel.className = 'tempCommentStyle';
			
			list.insertBefore(newel, list.firstChild)
			content = '<p>hello</p>';
			
			$('#' + tempID ).append(content);
			
			*/

			htmlstring  = '<div style="text-align: center; width: 500px;" >';
			htmlstring += '<p>Your comment has been successfully added. Your comment must be approved before it is visible online.</p>';
			htmlstring += '</div>';
			
			$('#inlineCommentforTB').html(htmlstring);

		}
		else if (data.indexOf('commentfailed') != -1) {
			
			htmlstring  = '<div style="text-align: center; width: 500px;" >';
			htmlstring += '<p>There was a problem adding your comment. Please try again later.</p>';
			htmlstring += '</div>';
			
			$('#inlineCommentforTB').html(htmlstring);			
		}
	  }  
	});  	
	

	return false;


}	
function bindAllToFacebox(){
	jQuery('a[rel="facebox"]').facebox();
} 

function emailStory(val) {
	dataString  = $('#sendStoryAsEmail').serialize();
	
	htmlstring  = '<div style="text-align: center; width: 500px;" >';
	htmlstring += '<p>Please wait while we send your message.</p>';
	htmlstring += '<div style="width: 34px; margin: 0 auto;" ><img src="/img/indicator_blue_large.gif" alt="loading anim" /></div>';
	
	htmlstring += '</div>';
	
	
	$('#inlineCommentforTB').html(htmlstring);
	
	
	
	$.ajax({  
	  type: "POST",  
	  url: val.action ,  
	  data: dataString,  
	  success: function(data) {  
		if (data.indexOf('emailsent') != -1) {

			htmlstring  = '<div style="text-align: center; width: 500px;" >';
			htmlstring += '<p>Your message has been successfully delivered. You must wait 3 minutes before emailing another story.</p>';
			htmlstring += '</div>';
			
			$('#inlineCommentforTB').html(htmlstring);

		}
		else if (data.indexOf('emailsenderror') != -1) {
			
			htmlstring  = '<div style="text-align: center; width: 500px;" >';
			htmlstring += '<p>There was a problem delivering your message. Please try again later.</p>';
			htmlstring += '</div>';
			
			$('#inlineCommentforTB').html(htmlstring);			
		}
	  }  
	});  	
	

	return false;


}

function cfReset() {
	if (confirm("Are you sure you want to reset?")) {
		document.contactus.reset();
		document.getElementById("fname").focus();
	}
}




function sessionTimeOut() {
	//alert('Your session has timed out.');
	
	content  = '<div style="padding: 20px;"> ';
	content += 'Your session has timed out, please log back in.';	
	content += '</div>';	
	content += '<br/>';	
	
	jQuery.facebox(content);	
	
}


function sessionTimeOutCheck() {
	//alert('Your session has timed out.');
	
	if ($('div#nosessiontimeout:visible').length == 0) {
		var url		   = "/ajax/validatesession";
	}
	else {
		var url		   = "/ajax/validatesession/remainlogged";
	}
	
	var content    = '';
	$.ajax({  
	  type: "POST",  
	  url:  url,  
	  cache: false,
	  success: function(data) {  
		if (data.indexOf('loggedin') != -1) {
			timestamp10 = false;
			timestamp5  = false;
			
			// Do nothing - user is logged in.
		
		}
		else if (!timestamp10 && data.indexOf('10minutes') != -1) {
			timestamp10 = true;
			alert('You will be logged out in 10 minutes');
		}
		else if (!timestamp5 && data.indexOf('5minutes') != -1) {
			timestamp5 = true;
			alert('You will be logged out in 5 minutes');
		}
		else if (data.indexOf('notlogged') != -1) {
			
			if ($('div#sessiontimedout:visible').length == 0) {
				content  = '<div id="sessiontimedout" style="padding: 20px;"> ';
				content += 'Your session has timed out, please log back in.';	
				content += '</div>';	
				content += '<br/>';	
				jQuery.facebox(content);	
			}
		}
	  }  
	}); 
	
}

function validateEmail (email) {
	var emailRegEx = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if(email.match(emailRegEx)) {
		return true;
	}
	else {
		return false;
	}
}

function optinForEmail () {
	
	var content    = '';
	var email      = $('#optinEmail').val();
	if ( validateEmail( email ) ) { 
		email = '/' + email; 
	}
	else if ( !validateEmail( email ) ) {
		$('#optinEmail').addClass('SD_error');
		return false;		
	}
	else {
		$('#optinEmail').addClass('SD_error');
		return false;
	}
	
	
	url = '/blog/stayNotified' + email ;
	
	$.ajax({  
	  type: "POST",  
	  url:  url ,  
	  success: function(data) {  
		if (data.indexOf('exists') != -1) {
				content  = '<h3>Stay Notified</h3>';
				content += 'The email you entered already exists in our database.';	
				content += '<br/>';	
				content += '<br/>';	
				content += '<input type="button" value="Close Window" onclick="$.facebox.closeNoReload();" />';
		
		}
		else if (data.indexOf('success') != -1) {
				content  = '<h3>Stay Notified</h3>';
				content += 'Your email address has been added to our mailing list.';	
				content += '<br/>';	
				content += '<br/>';	
				content += '<input type="button" value="Close Window" onclick="$.facebox.closeNoReload();" />';
		}
		else if (data.indexOf('failure') != -1) {
				content  = '<h3>Stay Notified</h3>';
				content += 'There was a problem adding your email address to our mailing list. Please try again later.';	
				content += '<br/>';	
				content += '<br/>';	
				content += '<input type="button" value="Close Window" onclick="$.facebox.closeNoReload();" />';
		}
		$('#SN_content').html(content);
	  }  
	}); 



	return false;	
}

$(function() {
	$("input[name='phone']").keyup(function() {
		var curchr = this.value.length;
		var curval = $(this).val();
		if (curchr == 3) {
			$("input[name='phone']").val("(" + curval + ")" + "-");
		} else if (curchr == 9) {
			$("input[name='phone']").val(curval + "-");
		}
	});
});


