$(document).ready(function() {
	
	// ====================================
	// = Content showing for main buttons =
	// ====================================
	
	// The function to show the main content by layer
	function showContent(layer, animate) {
		
		$("#background").show();
		$("#footer").hide();
		$("#announcement").hide();

		$("#content").empty().html('<div style="text-align:center; padding-top:50px;"><img src="images/ajax-loader_2.gif" /></div>');
		//alert(layer);
		  
		  $("#content").load(layer+'.php', function(){
		  	if(layer=='get'){
				Recaptcha.create("6LerHMQSAAAAAFUer9pUIzfZ_zt1G5GMY60jjvYd",
    							"recaptcha_panel",
    							{
      								theme: "white",
      								callback: Recaptcha.focus_response_field
    							}
  							);
				try_to_send_mail();
			}
		  });

		$("#nav").children().each(function() {
			if ($(this).attr("id").search(layer) == -1) {
				$(this).addClass("inactive");
				$(this).children().removeClass("active");
			} else {
				$(this).removeClass("inactive");
				$(this).children().addClass("active");
			}
		});

		if (animate == true) {
			$('html,body').animate({scrollTop: $("#nav").offset().top - 16}, 200, "swing");
		}
		
		// setUpHover();
		
		setupFullScreen();
		setupImageViewers();
		setupHovers();
		
		// Load analytics tracking
		setTimeout(function() {
			$("#tracker").attr("src", "/track/" + layer + "/")
		}, 500);
		
		window.location.hash = layer;
	}
	
	// Set up the on click functions for the different menus
	$("#nav").children().click(function() {
		showContent($(this).attr("id").split("_")[1], true);
	});
	
	$('.contact_button').live('click', function() {
	  showContent('get', true);
	 });
	 
	 /************************************* RSS Loader *****************************/

		 function showRssContent(layer, animate) {
		  
		  $("#background").show();
		  $("#footer").hide();
		  $("#announcement").hide();
		  
		  //$('#result').load('ajax/test.html');
		  $("#content").empty().html('<div style="text-align:center; padding-top:50px;"><img src="images/ajax-loader_2.gif" /></div>');
		  
		  layer = layer.split("_")[0];
		  $("#content").load(layer+'.php');
			
		  if (animate == true) {
		   $('html,body').animate({scrollTop: $("#nav").offset().top - 16}, 200, "swing");
		  }
		  //window.location.hash = layer+'_rss';
		 }
		 
		 $(".scroling").children().children().click(function() {
		  showRssContent($(this).attr("id").split("_")[0], true);
		 });
		 
		 $("#done_btn").live("click", function(){
			$.colorbox.close(' ');
			$("#CName").val(' ');
			$("#Email").val(' ');
			$("#Subject").val(' ');
			$("#Inquiry").val(' ');
			$("#if_reply").attr('checked', false);
		 });
		 
		 function isValidEmailAddress(emailAddress) {
            var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
            return pattern.test(emailAddress);
        }
		 
		 function try_to_send_mail(){
		 	$('#submit').live("click", function(){
            	
                var errs='';
                            
                if($('#CName').val()=='')
                    errs+='- Enter your name \n';
				if($('#Email').val()=='')
					errs+='- Enter your email address\n';
				else if(!isValidEmailAddress($('#Email').val()))
					errs+='- Please insert a valid email address!\n';
        
                if(errs!='')
                {
                    alert('Please Follow:\n'+errs);
                    return false;
                }
                else
                {
					$(".ajax_status").html("Sending request ...");
					var dataToSave = $("#frmContact").serialize();
					$.post("action.php", dataToSave,function(data){
                        if(typeof(data)=="string" && data!=''){
                            data = JSON.parse(data);
                        }
                        
						$(".ajax_status").html("").hide;
                        if(data.success === true){
							Recaptcha.reload();
							$.colorbox({
								width:"300",
								height:"200",
								initialWidth: 300,
								href: "#preview_btn2",
								inline:true,
								title: " ",
								overlayClose: false,
								transition:"none"
							});
							$("#cboxClose").css("display", "none");
							return false;
                        }else if(data.success == 'invalid'){
							Recaptcha.reload();
                            $(".ajax_status").html("Invalid Captcha Key. Please try again").css("color","blue").show();
                        }else{		
							Recaptcha.reload();					
                            $(".ajax_status").html("Message Sending Failed").css("color","red").show();
						}
                        
                    }, "json")

                	return false;
                }
            });
		 }
		 
		 
		 var recentHash = document.location.hash;
		 var isRss = "";
		 var checkHash = function() {
		  var hash = document.location.hash;
		  if (hash) {
			hash = hash.substr(1);
			isRss = hash.split("_")[1];
			if(isRss != "rss") {
			 return;
			}
			if (hash == recentHash) {
			  return;
			}
			recentHash = hash;
			showRssContent(hash, true);
		  }
		 }
		 setInterval(checkHash, 2000);
	/**************** END RSS *******************************/
	
	// If there is a location has we open the layer with the content and scroll to it,
	// but only if we're not coming from the same url, because then we'd like to end up
	// at the scroll position we were.
	if (window.location.hash && document.referrer != window.location) {
		showContent(window.location.hash.replace("#", ""), false);
	}
	
	// =========================
	// = Preloading of content =
	// =========================

	preloadContentDelay = 1000;
	
	setTimeout(function() {
		
		preloadNode = $("<div></div>");
		
		preloadNode.css({
			"position": "absolute", 
			"left": "-100000px", 
			"top": "-100000px", 
			"height": "1px", 
			"width": "1px",
			"overflow": "hidden"})
	
		preloadNode.append($("#custom_html").comments())
		preloadNode.append($("#creative_html").comments())
		preloadNode.append($("#about_html").comments())
		preloadNode.append($("#service_html").comments())
		preloadNode.append($("#get_html").comments())
	
		$("body").append(preloadNode);
		
		// setUpHover();
		
	}, preloadContentDelay);

	// ==================================
	// = Set up hovering for mouseovers =
	// ==================================
	
	// function setUpHover() {
	// 
	//	$(".hover").each(function() {
	//		var parentNode = $(this);
	//		var imageNode = parentNode.children("img");
	// 
	//		if (!imageNode.length) {
	//			imageNode = $("<img>");
	//			imageNode.attr("src", parentNode.css("background-image").replace("off", "on"));
	//			imageNode.css({"position": "relative", "opacity": "0.0"}); 
	//			imageNode.appendTo(parentNode);
	//		}
	//	});
	// 
	//	$(".hover").hover(function() {
	//		$(this).children("img").stop().fadeTo(150, 1.0);
	//	}, function() {
	//		$(this).children("img").stop().fadeTo(150, 0.0);
	//	});
	// 
	// }

	// =========================
	// = Main page menu hovers =
	// =========================
	
	function setupHovers() {	
		$(".hoverable").hover(
			function() {$(this).addClass("hover")},
			function() {$(this).removeClass("hover")}
		);
	
		$(".gallery .thumbnail").hover(
			function() {$(this).children("img.fade").stop().fadeTo(200, 1)},
			function() {$(this).children("img.fade").stop().fadeTo(50, 0)}
		);
		$(".profile").hover(
			function() {$('img.fade', this).stop().fadeTo(200, 1)},
			function() {$('img.fade', this).stop().fadeTo(50, 0)}
		);

	};
	
	setupHovers();
	
});
