/*
// JavaScript Document
// Firestorm Creative Studios
// Custom Funtionalilty for FCS Main Site
*/

//$.noConflict();

$(document).ready(function()
{

//fcs_menu(); //improves the css dropdown menu with animation and ie6 compatibility
initMenus();//right bar menus
fcs_newsticker(".ticker span",5000); // starts the newsticker, number defines the time between transitions in milliseconds
fcs_fader(".preview_images a",".featured_item"); // this is the mainpages fading script-> when a image is clicked a fadeout followed by a fade in occurs
fcs_pointer(); // this script manages the pointer below the preview pics
fcs_autoslide(".preview_images a",6000); // this script starts the automatic slideshow, number represents the time between the transition in milliseconds
fcs_next_slide(".preview_images a",".featured_item",".show-next"); // shows the next slide
//fcs_form(); // initializes ajax sending of the contact form

fix_ie6(); // adds some improvements to the site, fix pngs etc.

//$("#rightBarSearch #s").val("Search the Site");

//network menu
$("a.menu_class").toggle(function () {
	$("ul.the_menu").slideToggle('fast');
	$(this).addClass("menu_open");
	}, function () {
		$("ul.the_menu").slideToggle('fast');
		$(this).removeClass("menu_open");
});

//Sort Showcase Drop Down
$("a#sortShowcase").toggle(function () {
	$("ul.catList").slideToggle('medium');
	$(this).addClass("menu_open");
	}, function () {
		$("ul.catList").slideToggle('medium');
		$(this).removeClass("menu_open");
});

//gallery caption
$('.project-thumb').hover(function(){
	$(this).children('.showcaseOverlay').slideToggle('fast');
}, function() {
	$(this).children('.showcaseOverlay').slideToggle('fast');
});


//Sidebar menu
$("ul.toggle .toggleHeading").toggle(function () {
	$(this).find('h3').removeClass("open");
	$(this).parent().find('ul.showcats').slideToggle('fast');
	
	}, function () {
		$(this).parent().find('ul.showcats').slideToggle('fast');
		$(this).find('h3').addClass("open");
});

//slide action on right bar lists
$('a.nudge').hover(function() { //mouse in
		$(this).animate({ paddingLeft: '30px' }, 300);
	}, function() { //mouse out
		$(this).stop().animate({ paddingLeft: '20px' }, 300);
	});

//showcase view
$("a.switch_thumb").toggle(function(){
		if (!$(this).hasClass ("swap")) {
			$(this).addClass("swap");
			$(".display").fadeOut("fast", function() {
				$(this).fadeIn("fast").addClass("thumb_view");
			});
			$.cookie('showcasePref', 'thumb');
		}else{
			$(this).removeClass("swap");
			$(".display").fadeOut("fast", function() {
				$(this).fadeIn("fast").removeClass("thumb_view");
			});
			$.cookie('showcasePref', 'list');
		}
		return false;
		//alert("Cookie: "+$.cookie('showcasePref'));
	}, function () {
		if ($(this).hasClass ("swap")) {
			$(this).removeClass("swap");
			$(".display").fadeOut("fast", function() {
				$(this).fadeIn("fast").removeClass("thumb_view");
				
			});
			$.cookie('showcasePref', 'list');
		}else{
			$(this).addClass("swap");
			$(".display").fadeOut("fast", function() {
				$(this).fadeIn("fast").addClass("thumb_view");
				
			});
			$.cookie('showcasePref', 'thumb');
		}
		return false;
		//alert("Cookie: "+$.cookie('showcasePref'));
	});

/*//capture anchor links
$('a[href*=#]').click(function() {
 if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
 && location.hostname == this.hostname) {
   var $target = $(this.hash);
   $target = $target.length && $target
   || $('[name=' + this.hash.slice(1) +']');
   if ($target.length) {
  var targetOffset = $target.offset().top;
  $('html,body')
  .animate({scrollTop: targetOffset}, 1000);
    return false;
   }
 }
  });*/
//file upload field magic
$('input[type=file]').each(function(){
  
  var uploadbuttonlabeltext = $(this).attr('title'); //get title attribut for languagesettings
  if(uploadbuttonlabeltext == ''){
    var uploadbuttonlabeltext = 'Browse';
  }
  
  var uploadbutton = '<input type="button" class="button_button" value="'+uploadbuttonlabeltext+'" />';
   $(this).wrap('<div class="fileinputs"></div>');
    $(this).addClass('file').css('opacity', 0); //set to invisible
    $(this).parent().append($('<div class="fakefile" />').append($('<input type="text" />').attr('id',$(this).attr('id')+'__fake')).append(uploadbutton));
 
    $(this).bind('change', function() {
      $('#'+$(this).attr('id')+'__fake').val($(this).val());;
    });
    $(this).bind('mouseout', function() {
      $('#'+$(this).attr('id')+'__fake').val($(this).val());;
    });
  });
});//End

//*****************************************************
// Begin Functions
//****************************************************/

$(document).ready(function(){

	$(".post .share").click(function(){
	  $(this).next("div").slideToggle("medium");
		$(this).toggleClass("active"); return false;
	});

});

/* Tooltip */



$(function() {
	$(".tooltip").tooltip({
		track: true,
		delay: 0,
		showURL: false,
		showBody: " - ",
		fade: 250
	});
});


function fix_ie6()
{
	//impliment png fixes to selectors
	if(($.browser.msie && parseInt($.browser.version) < 7))
	{
		$(".header_logo img, #nav #mainnav li, #wrapper, #featured, #featured_bottom img, .pointer, #clientLogin,#submitTicket, #content, #footer").addClass("ie6fix");
	}
}

//Control the Client Area buttons
/*$(function(){
	$('a#clientLogin,a.clientLogin').click(function(){$('#loginPanel').slideToggle(); return false;});
	$('#loginPanel').css('display', 'none');
});*/// JavaScript Document

//Reveal do thumbthing list
$(function(){
	$('a.getStarted').click(function(){$('ul.getStarted').slideToggle(); return false;});
	$('ul.getStarted').css('display', 'none');
});// JavaScript Document

$(function(){
	$('a#clientLogin,a.clientLogin').click(function(){$('#popup-login').fadeIn(400); return false;});
	$('#popup-login a.close').click(function(){$('#popup-login').fadeOut(400); return false;});
});// JavaScript Document

//Control the Ticket buttons
$(function(){
	$('a#submitTicket, .submitTicket').click(function(){
		//Options array					   
		var options = { 
			target: '#output',
			beforeSubmit:  validateTicket,  // pre-submit callback 
			success: showResponse,    // post-submit callback 
			resetForm: true,         // reset the form after successful submit 
			//-- other available options: 
			//url:       url         // override for form's 'action' attribute 
			//type:      type        // 'get' or 'post', override for form's 'method' attribute 
			dataType:  'script',        // 'xml', 'script', or 'json' (expected server response type) 
			//clearForm: true        // clear all form fields after successful submit 
			//resetForm: true        // reset the form after successful submit
		
			// $.ajax options can be used here too, for example: 
			//timeout:   3000
		};
		$("#popup-ticket-form").empty();
		$('#popup-ticket').fadeIn(400); 
		$("#popup-ticket #contentLoading").animate({ opacity: "show" }, "fast");
		//$("#popup-ticket").load("drs/includes/ticket.form.php");
		$.ajax({
		   url: "/drs/includes/ticket.form.php",
		   cache: false,
		  success: function(html){
			  $("#popup-ticket #contentLoading").animate({ opacity: "hide" }, "fast");
			  $("#popup-ticket-form").append(html);
			  $('#ticketForm').submit(function() { 
				// submit the form 
				$(this).ajaxSubmit(options); 
				// return false to prevent normal browser submit and page navigation 
				return false; 
			});
		  }
		 });

	});
	
	$('#popup-ticket a.close').click(function(){$('#popup-ticket').fadeOut(400); return false;});return false;
});// JavaScript Document




//Right bar menus
function initMenus() {
	$('ul.menu ul').hide();
	$.each($('ul.menu'), function(){
		$('#' + this.id + '.expandfirst ul.test').show();
	});
	$('ul.menu li a').click(
		function() {
			var checkElement = $(this).next();
			var parent = this.parentNode.parentNode.id;

			if($('#' + parent).hasClass('noaccordion')) {
				$(this).next().slideToggle('normal');
				return false;
			}
			if((checkElement.is('ul')) && (checkElement.is(':visible'))) {
			
				if($('#' + parent).hasClass('collapsible')) {
					$('#' + parent + ' ul:visible').slideUp('normal');
				}
				return false;
			}
			if((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
				$('#' + parent + ' ul:visible').slideUp('normal');
				checkElement.slideDown('normal');
				return false;
			}
		}
	);
}

//drop down menus
function fcs_menu()
{
		$("#nav a").removeAttr('title');
		$("#nav ul").css({display: "none"}); // Opera Fix
		
		$(" #nav li").hover(function()
		{
			$(this).find('ul:first').css({visibility: "visible",display: "none"}).slideDown(400,"easeInOutQuart");
		}
		,function()
		{
			$(this).find('ul:first').css({visibility: "hidden"});
		});
		
}

//home page feature slider next
function fcs_next_slide($items_to_click, $items_to_fade,$next)
{
	$items = $($items_to_fade);
	$click_these_items = $($items_to_click);
	var x = 0;
	//alert('next slide called!');
	$items.each(function(i)
	{
		$(this).find($next).click(function()
		{
		i+1 < $click_these_items.length ? x = i + 1 : x = 0;	
		$click_these_items.filter(":eq("+x+")").trigger('click');
		return false;
		});
	});
}


function fcs_newsticker($items_to_fade, $display_time)
{
	
	tickerchange = setInterval(fcs_start_ticker, $display_time);
	var $tickeritem = $($items_to_fade);
	var i = 1;
	
	function fcs_start_ticker()
	{
	$tickeritem.filter(":eq("+i+")").trigger('fade');
	i+1 < $tickeritem.length ? i++ : i = 0;	
	}
	
	  $tickeritem.each(function(i)
	  {
		  $(this).bind("fade",function()
		  {	
			  $new_ticker_item = $tickeritem.filter(":eq("+i+")");
			  
			  if( $new_ticker_item.css("display") == "none" )
			  {
				  $tickeritem.filter(":visible").fadeOut(400, function()
				  {	
					  $new_ticker_item.fadeIn(400);
				  });
			  }
			  
		  });
	  });
}


function fcs_autoslide($items_to_click, $display_time)
{	
	interval = setInterval(fcs_start_autoplay, $display_time);
	var $click_these_items = $($items_to_click);
	var i = 1;
	//alert('autostart called!');
	$click_these_items.click(function($eventobject, $autoplay)
	{
		if(interval && !$autoplay) clearInterval(interval);
	});
	
	
	function fcs_start_autoplay()
	{	
		//alert('autoplay running');
		$click_these_items.filter(":eq("+i+")").trigger('click',[true]);
		i+1 < $click_these_items.length ? i++ : i = 0;
		
	}
	
}


function fcs_fader($items_to_click, $items_to_fade)
{	
	var $item = $($items_to_fade);
	//alert('fader called on '+$item.css("display"));
	$($items_to_click).each(function(i)
	{
		$(this).click(function()
		{	
			//alert('ITEM CLICKED!');
			
			$new_item = $item.filter(":eq("+i+")");
			//alert('i value: '+i);
			if( $new_item.css("display") == "none" )
			{
				//alert('item display none!');
				$item.filter(":visible").fadeOut(400, function()
				{	
					//alert('item faded in!');
					$new_item.fadeIn(400);
				});
			}
			
			return false;
			
		});
		
	});
	
}

function fcs_pointer()
{	
	var $wrapper = $(".preview_images");
	var $slider = $('<div class="pointer"></div>').appendTo($wrapper);
	
	var $slider_half = $slider.width()/2;
	$(".preview_images a").each(function(i)
	{
		$(this).click(function()
		{	
			$(".current_prev").removeClass('current_prev');
			$(this).addClass('current_prev');
			
			$image_pos = $(this).position();
			$newposition = $image_pos.left + $(this).width()/2 - $slider_half;//to center the pointer graphic
			//$newposition = $image_pos.left;//to left justify the pointer graphic
			$slider.animate({"left":$newposition},500,"easeOutBack");
			/*$slider.fadeOut(400, function()
				{	
					$slider.animate({"left":$newposition},200,"easeOutBack");
					$slider.fadeIn(300);
				});*/
			
			
		});
		
	});
	
}



function fcs_form(){
	if(!($.browser.msie && parseInt($.browser.version) < 7)) // ajax form disabled in ie6
	{
		
	var my_error;
	$(".ajax_form #send").bind("click", function(){
											 
	my_error = false;
	$(".ajax_form #name, .ajax_form #message, .ajax_form #email ").each(function(i){
				
				var value = $(this).attr("value");
				var check_for = $(this).attr("id");
				var surrounding_element = $(this).parent();
				if(check_for == "email"){
					if(!value.match(/^\w[\w|\.|\-]+@\w[\w|\.|\-]+\.[a-zA-Z]{2,4}$/)){
						
						surrounding_element.attr("class","").addClass("error");
						
						my_error = true;
						}else{
						surrounding_element.attr("class","").addClass("valid");	
						}
					}
				
				if(check_for == "name" || check_for == "message"){
					if(value == ""){
						
						surrounding_element.attr("class","").addClass("error");
						
						my_error = true;
						}else{
						surrounding_element.attr("class","").addClass("valid");	
						}
					}
						   if($(".ajax_form #name, .ajax_form #message, .ajax_form #email").length  == i+1){
								if(my_error == false){
									$(".ajax_form").slideUp(400);
									
									var $datastring = "ajax=true";
									$(".ajax_form input, .ajax_form textarea").each(function(i)
									{
										var $name = $(this).attr('name');	
										var $value = $(this).attr('value');
										$datastring = $datastring + "&" + $name + "=" + $value;
									});
																		
									
									$(".ajax_form #send").fadeOut(100);	
									
									$.ajax({
									   type: "POST",
									   url: "send.php",
									   data: $datastring,
									   success: function(response){
									   $(".ajax_form").before("<div class='ajaxresponse' style='display: none;'></div>");
									   $(".ajaxresponse").html(response).slideDown(400); 
									   $(".ajax_form #send").fadeIn(400);
									   $(".ajax_form #name, .ajax_form #message, .ajax_form #email , .ajax_form #website").val("");
										   }
										});
									} 
							}
					});
			return false;
	});
}

}
// Clear input text and darken color on a form field
function clearAndColor(el, e2) {

	//grab the current fields value and set a variable

	if (el.defaultValue==el.value) el.value = "";

	//Change the form fields text color

	if (el.style) el.style.color = "#333";
}

//Replace the default text
function reText(el){

	//Change the form fields text color

	if (el.style) el.style.color = "#ccc";

	if (el.value== "") el.value = el.defaultValue;

}

//Newsletter Submit
$("#newsSubmit").click(function()
	{	
	
	// First, disable the form from submitting
	$('form#frmNewsletter').submit(function() { return false; });
	$(".newsletterContainer #contentLoading").animate({ opacity: "show" }, "fast");
	// Grab form action
	formAction = $("form#frmNewsletter").attr("action");
	
	// id for email field
	emailId = "yuhtud";
	emailId = emailId.replace("/", "");
	emailId = emailId + "-" + emailId;
	
	// Validate email address with regex
	if (!checkEmail(emailId)) 
	{
		//alert("Please enter a valid email address");
		$("#frmNewsletter input#yuhtud-yuhtud").css({color:"#990000"});
		$("#frmNewsletter input#yuhtud-yuhtud").val("Valid Email Address Required");
		$(".newsletterContainer #contentLoading").animate({ opacity: "hide" }, "fast");
		return;
	}
	
	// Serialize form values to be submitted with POST
	var str = $("form#frmNewsletter").serialize();
	
	// Add form action to end of serialized data
	final = str + "&action=" + formAction;
	
	// Submit the form via ajax
	$.ajax({
		url: "/emailNewsProxy.php",
		type: "POST",
		data: final,
		success: function(html){
			$(".newsletterContainer #contentLoading").animate({ opacity: "hide" }, "fast");
			$("#frmNewsletter").hide(); // If successfully submitted hides the form
			$("#confirmation").slideDown("medium");  // Shows "Thanks for subscribing" div
		}
	});
});
//check the newsletter field and validate email address
function checkEmail(email)
{	
	var pattern = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	var emailVal = $("#" + email).val();
	return pattern.test(emailVal);
}