//preloading the big images of the project on one_project page
jQuery.preloadImages = function()
{
	var sources = new Array();
	
	sources = arguments[0];
	images = new Array();

	for(var i = 0; i < sources.length; i++)
	{
		images[i] = jQuery("<img>").attr("src", sources[i]);
	}

}

//function for equalizing the content of the subfooter section (level3)
function equalHeightFooter(){

	var highestCol = Math.max( jQuery('.useful_section_top').height(), jQuery('.little_menu').height());
	jQuery('.useful_section_top').css('height', highestCol);
	jQuery('.little_menu').css('height', highestCol);		
}

//function to make the slide effect of the images on one_project page (top images)
function makeScrollable(wrapper, scrollable){
  // Get jQuery elements
  var wrapper = $(wrapper), scrollable = $(scrollable);

  // Hide images until they are not loaded
  scrollable.hide();
  var loading = $('<div class="loading">Зареждане...</div>').appendTo(wrapper);

  // Set function that will check if all images are loaded
  var interval = setInterval(function(){
    var images = scrollable.find('img');
    var completed = 0;

    // Counts number of images that are succesfully loaded
    images.each(function(){
      if (this.complete) completed++;
    });
    if (completed == images.length){
      clearInterval(interval);
      // Timeout added to fix problem with Chrome
      setTimeout(function(){

        loading.hide();
        // Remove scrollbars
        wrapper.css({overflow: 'hidden'});                                              

        scrollable.slideDown('slow', function(){
          enable();
        });
      }, 1000);
    }
  }, 100);/* Defines the period of the execution of the function!!!!!!!!!!!!!!!!!!!! */

  function enable(){
  // height of area at the top at bottom, that don't respond to mousemove
  var inactiveMargin = 50;
  // Cache for performance
  var wrapperWidth = wrapper.width();
  var wrapperHeight = wrapper.height();
  // Using outer height to include padding too
  
  //console.log(scrollable.height());/*759px*/
  
  var scrollableHeight = scrollable.outerHeight() + 2*inactiveMargin;
  //console.log(scrollableHeight);/*859px*/
  
  // Do not cache wrapperOffset, because it can change when user resizes window
  // We could use onresize event, but it's just not worth doing that
  // var wrapperOffset = wrapper.offset();

  //When user move mouse over menu
  wrapper.mousemove(function(e){
    var wrapperOffset = wrapper.offset();
    
    // Scroll menu
    var top = (e.pageY -  wrapperOffset.top) * (scrollableHeight - wrapperHeight) / wrapperHeight  - inactiveMargin;
    if (top < 0){
      top = 0;
    }

    wrapper.scrollTop(top);
  });

  }
}


//gallery variables - 3 sizes images!
var gal_size_middle = '506x350';
var gal_size_preview = '1000x';

//function for switching the images of the project when hovered on one_project page
function switchImages(){
	
	//gallery variables - 3 sizes images! - Globally defined
	//var gal_size_middle = '506x350';
	//var gal_size_preview = '1000x';
	
	$('.blockProjectImages .itemSmallImg a').hover(function(){
		
		var temp_old_url = $(this).attr('href');
		//alert(temp_old_url);
		//Replace preview with medium size!
		var temp_new_url = temp_old_url.replace(gal_size_preview, gal_size_middle);
		//alert(temp_new_url);
		
		//CK if the image is current - do not animate!
		var temp_current_url = $('.blockProjectImages .itemLargeImg img').attr('src');
		//alert(temp_current_url);
		if(temp_current_url==temp_new_url) {
			//skip
		}
		else {
			
			//Finding the index of the link in the right column of project images
			thisParent = $(this).parent();
			thisIndex = $(thisParent).parent().children().index(thisParent);
			
			//fullsize is "bind"-ed somewhere. TODO - Replace with PrettyPhoto
			
			if (temp_old_url != $('.blockProjectImages .itemLargeImg').find("img").attr("src")){
				
				$('.blockProjectImages .imagesNav .button').removeClass('button_selected');
				
				if ($('.blockProjectImages .itemLargeImg img').is(':animated')) {
					$('.blockProjectImages .itemLargeImg img').stop().animate({opacity: 0}, 200, function(){
						$(this).attr("src", temp_new_url).animate({opacity: 1}, 400	);
					});
				}
				else {
					$('.blockProjectImages .itemLargeImg img').animate({opacity: 0}, 200, function(){
						$(this).attr("src", temp_new_url).animate({opacity: 1}, 400	);
					});
				}
				
				// Change a[href=] and Re-Bind onclick event to the medium image/link OR simulate (Trigger) Click
				//images = ['images/fullscreen/image1.jpg','images/fullscreen/image2.jpg','images/fullscreen/image3.jpg'];
				//titles = ['Title 1','Title 2','Title 3'];
				//descriptions = ['Description 1','Description 2','Description 3'];
				//$.prettyPhoto.open(images,titles,descriptions);
				$('.blockProjectImages .itemLargeImg a').attr('href', temp_old_url);
				galleryBindClickMediumImage();
				
				$('.blockProjectImages .imagesNav .button').eq(thisIndex).addClass('button_selected');
				
			}
			//.css("visibility", "hidden")
			
		}
		
	},function(){
		return false;
	})
}
function galleryBindClickMediumImage() {
	$('.blockProjectImages .itemLargeImg a').unbind('click').bind('click', function(e){
		e.preventDefault();
		var temp_image_preview = $(this).attr('href');
		//alert(temp_image_preview);
		
		//Walk through all URLs to compare anf trigger click
		$('.blockProjectImages .itemSmallImg a').each(function(){
			var temp_this = $(this).attr('href');
			if(temp_this==temp_image_preview) {
				$(this).trigger('click');
			}
		});
		
		return false;
	});
}
//function for dynamically adding buttons(in this case dots) to the image preview of the project on one_project page
function addImageNavigation(){
	$('.itemSmallImgWrapper .itemSmallImg').each(function(i){
		var button = $("<div></div>").attr('class', 'button');
		$('.blockProjectImages .imagesNav').append(button);
		if (i > 0) {
			$('.blockProjectImages .imagesNav .button').eq(i).addClass('notFirst');
		}
	});
	
	//add a div with .clear class to clear the floats of the buttons' divs
	var clear_div = $("<div></div>").attr('class', 'clear');
	$('.blockProjectImages .imagesNav').append(clear_div);
	
	//position the .imagesNav div centrally
	cont_width = $('.blockProjectImages .itemLargeImg').outerWidth();
	//alert(cont_width);
	
	nav_width = $('.blockProjectImages .imagesNav').width();
	//alert(nav_width);
	
	if (cont_width > nav_width){
		$('.blockProjectImages .imagesNav').css({'left' : (cont_width - nav_width) / 2});
	}
	
	//Add .button_selected class - initaily the first image is shown so the first button should be selected
	$('.blockProjectImages .imagesNav .button').eq(0).addClass('button_selected');
	
	//Add hover effect on the buttons
	$('.blockProjectImages .imagesNav .button').hover(function(){
		$(this).addClass('button_hovered');
	},
	function(){
		$(this).removeClass('button_hovered');
	});
	
	//Onclick - change the big image with the matching image from the right col
	$('.blockProjectImages .imagesNav .button').click(function(){
		
		//The index of the button that called the function
		thisIndex = $(this).parent().children().index(this);
		//alert(thisIndex);
		
		
		//The address to the big image - matching the index of the clicked button and the index of the image
		//in the right column (the small images)
		temp_old_url = $('.blockProjectImages .itemSmallImg').eq(thisIndex).find('a').attr('href');
		//alert(temp_old_url);
		
		//Replace preview with medium size!
		var temp_new_url = temp_old_url.replace(gal_size_preview, gal_size_middle);
		//alert(temp_new_url);
		
		//The current big image
//		big_img_src = $('.blockProjectImages .itemLargeImg').find("img").attr("src")
		//CK if the image is current - do not animate!
		var temp_current_url = $('.blockProjectImages .itemLargeImg img').attr('src');
		//alert(temp_current_url);
		if(temp_current_url==temp_new_url) {
			//skip
		}
		else {
			
			$('.blockProjectImages .imagesNav .button').removeClass('button_selected');
			
			if ($('.blockProjectImages .itemLargeImg img').is(':animated')) {
				$('.blockProjectImages .itemLargeImg img').stop().animate({opacity: 0}, 200, function(){
					$(this).attr("src", temp_new_url).animate({opacity: 1}, 400);
				});
			}
			else {
				$('.blockProjectImages .itemLargeImg img').animate({opacity: 0}, 200, function(){
					$(this).attr("src", temp_new_url).animate({opacity: 1}, 400);
				});
			}
			
			$(this).addClass('button_selected');
			
			// Change a[href=] and Re-Bind onclick event to the medium image/link OR simulate (Trigger) Click
			$('.blockProjectImages .itemLargeImg a').attr('href', temp_old_url);
			galleryBindClickMediumImage();
			
		}
		
	});
}


//function for swiching between list type preview and thumbnail type preview on one_project page
function list_thumbnail_switch(elem1, elem2){
	$(elem1).hide();
	$(elem2).show();
}

//function user for the teaser
function onBefore(){
	var thisIndex = $(this).parent().children().index(this);
	$("#teaser_nav div").removeClass("button_selected");
	$("#teaser_nav div").eq(thisIndex).addClass("button_selected");
}

//function for aligning the buttons of the teaser in the middle
function centerTeaserBtns(){
	//get the width of the buttons bar
	buttons_width = $('#teaser_nav').outerWidth();
	//alert(buttons_width);
	
	//calculating the width of the teaser(if ever changed)
	teaser_width = $('#hp_teaser').width();
	//alert(teaser_width);
	
	//it is assumed that the buttons won't be so much that their length would be more than the length of the teaser container
	$('#teaser_nav').css({'left' : (teaser_width - buttons_width) / 2});
}

//function for activating the custom srollbar of the similar projects section on one_project page
function scrollSimilarProjects(container){
	
	//make an object out of the argument passed
	container = $(container);
	
	//variable for summing up the overall width
	calc_width = 0;
	
	//Calculating the width of all child elements plus their margins to actually calculate the real width of the container
	children_array = container.children();
	children_array.each(function(i){
		elem_width = $(this).width();
		//alert('Element ' + i + ' width: ' + elem_width);
		
		elem_margin = parseInt($(this).css('margin-left'));
		//alert('Element ' + i + ' margin: ' + elem_margin);
		
		calc_width = calc_width + elem_width + elem_margin;
		//alert('Until element ' + i + ' calc_width is: ' + calc_width);
	});
	//Dynamically calculating the width of the container and set it explicitly
	container.css({'width' : calc_width});

	//Activate the scroll function
	$('#thumbnail_type').jScrollHorizontalPane({scrollbarHeight:7, showArrows:false, wheelSpeed : 68});
}

//function calling the preloading function with the needed parameters
function loadImages(){
	
	sources = new Array();
	
	$('.blockProjectImages .itemSmallImg').each(function(i){
		sources[i] = $(this).find('a').attr('href');
	});
	
	$.preloadImages(sources);
}

//function for aligning the services' blocks on services page
function alignServices(){
	$('#services_container .services_wrapper .servicesRow').each(function(i){
		
		var highest = 0;
		
		$('.blockOneService', this).each(function(ii){
			var this_height = 0;
			this_height += $('h2', this).outerHeight() + $('.itemText', this).outerHeight();
			//alert('this_height ' + ii + ' ' + this_height);
			if (this_height > highest) {
				highest = this_height;
				//alert(highest);
			}
		});
		
		$('.blockOneService', this).each(function(ii){
			$('.itemFluidArea', this).height(highest);
		});
		
	});
}

function projectsHomeBindCycle()
{
    /*Cycle the pictures when they are hovered - vertical scroll (home page) */
     $('.projects_slider .frame').each(function(){
     	$(this).cycle({
     		fx:      'scrollDown', 
		    speed:    300, 
		    timeout:  2000 
     	});
     	$(this).cycle('pause');
     });
    /*Hover - pause*/
	$('.projects_slider .frame').hover(function(){
    	$(this).cycle('resume');
    }
    ,function(){
    	$(this).cycle('pause');
    });
    /* End */
}

var js_projects_home_container_hover = 0; // used to keep the hover state
var reload_projects_home_delay = 13000; // reload interval (if hover is not detected)
// setTimeout ( "reloadProjectsHome()", reload_projects_home_delay ); // set this on document.ready
function reloadProjectsHome()
{
	// (do something here)
	//alert(123);
	
	if( $('#js_projects_home_container').length ) {
		
		//return false;
		//alert(123);
		
		//console.log(js_projects_home_container_hover);
		
		// if hover is not detected - reload projects
		if( js_projects_home_container_hover === 0 ) {
			jQuery.get(
				"/ajax-load-projects"
				,{
					//a: "1"
				}
				,function(responseText, textStatus, XMLHttpRequest)
				{
					// Callback function!!!   	//alert("done");
					//console.log(responseText);      //alert(textStatus); // success
					if( responseText.length ) {
						$('#js_projects_home_container').fadeOut(300, function(){
							jQuery(this).html(responseText).fadeIn(600, function(){
								//callback
								// rebind cycles
								projectsHomeBindCycle();
							});
						});
					}
				}
				,"html"
			);
		}
		
		setTimeout ( "reloadProjectsHome()", reload_projects_home_delay );
		
	}
}

function fbs_click() {
	u=location.href;
	//t=document.title; // [object NodeList]
	//t = $("html title").text(); // ie7 doesn't work - http://bytes.com/topic/javascript/answers/161441-how-get-page-title
	//alert(t);
	t = getPageTitle();
	window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
	return false;
}

function getPageTitle()
{
	var result = '';
	var t = document.getElementsByTagName('title')[0];
	if ( !!t.childNodes.length ) {
		//alert( t.firstChild.data );
		var result = t.firstChild.data;
	} else if ( t.innerHTML ) {
		//alert( t.innerHTML );
		var result = t.innerHTML;
	}
	
	return result;
}


/******************************/
/* ON DOCUMENT READY FUNCTION */
/******************************/

jQuery(document).ready(function() {

	//Call the preloading function for the big (middle sized) images of the project on one_project page
	loadImages();
	
	//Disable links in the vertical slider on the one_project page
	$('.blockProjectImages .itemSmallImgWrapper a').click(function(){
		return false;
	});
	
	/* Hover over the horizontal menu */
	$('#horizontal_menu a').hover(function(){
		$(this).parent().addClass('hovered');
	},
	function(){
		$(this).parent().removeClass('hovered');
	});

	/*Home page projects carousel*/
    jQuery('#header_carousel').jcarousel({
        scroll: 1
    });
    
	/*Cycle the pictures when they are hovered - vertical scroll (home page) */
	projectsHomeBindCycle();
	
	
	/*Equalize first and second block (copyright and RSS) in level3*/
	equalHeightFooter();
	
	/*Equalize the height of the main content - home page*/
	/* equalContent(); */
	
	/*Make a vertical scroll of the images in the one_project page*/
	makeScrollable("div.itemSmallImgWrapper", "div.itemSmallImages");
	
	/* Make the projects on the home page slide on mouse movement event */
//2009-12-29 - DO not scroll
//	makeScrollable("div.projects_slider_wrapper", "div.projects_slider");
	
	/* Switching the images of the project - one_project page */
	switchImages();
	galleryBindClickMediumImage();
	
	/******************/
	
	//scrollWithButtons("div.projects_slider_wrapper", "div.projects_slider");
	
	/* Mouse wheel enabling */
	/*$('#thumbnail_type').bind('mousewheel', function(event, delta) {
        var dir = delta > 0 ? -1 : 1,
            vel = Math.abs(delta);
        $(this).text(dir + ' at a velocity of ' + vel);
        %(this).animate({slideTo:40}, "normal")
        return false;
    });*/
    
	//Activate the scroll of the projects (thumbnail_type)
	scrollSimilarProjects('#thumbnail_type .inner_thumbnail_type');
	
	//Activate the scroll of the projects (list_type)
	//scrollSimilarProjects('#list_type .inner_list_type');
	
	
	$('.select_type_list a').click(function(){
		$('#select_type_list_text').animate({width: 'show'});
		$('#select_type_thumbnail_text').hide();
		list_thumbnail_switch('.thumbnail_type_wrapper', '.list_type');
		$('.select_type_thumbnail').removeClass('selected');
		$('.select_type_list').addClass('selected');
		var $lefty=$('#select_type_list_text');
		return false;
	});
	$('.select_type_thumbnail a').click(function(){
		$('#select_type_list_text').hide();
		$('#select_type_thumbnail_text').animate({width: 'show'});
		list_thumbnail_switch('.list_type', '.thumbnail_type_wrapper');
		$('.select_type_list').removeClass('selected');
		$('.select_type_thumbnail').addClass('selected');
		return false;
	});
	//Hide the thumbnail list
	$('.list_type').hide(0);
	$('#select_type_thumbnail_text').animate({width: 'show'}); // IE6 fix - the jScroll have problems with default CSS values. When called, this fixes the problem! //jquery animate width show
	
	// Hover over the submit button of the form on the contact_us page
	$('.blockContactForm .submit_btn').hover(function(){
		$(this).addClass('submit_btn_hovered');
	},
	function(){
		$(this).removeClass('submit_btn_hovered');
	});
	
	
	//Hover over the logos in the bottom section of each page
	$('.common_section .logos .apple').hover(function(){
		$(this).addClass('image_1_hovered');
	},
	function(){
		$(this).removeClass('image_1_hovered');
	});
	
	$('.common_section .logos .bwa').hover(function(){
		$(this).addClass('image_2_hovered');
	},
	function(){
		$(this).removeClass('image_2_hovered');
	});
	
	$('.common_section .logos .iphone').hover(function(){
		$(this).addClass('image_3_hovered');
	},
	function(){
		$(this).removeClass('image_3_hovered');
	});
	
	$('.common_section .logos .novmak').hover(function(){
		$(this).addClass('image_4_hovered');
	},
	function(){
		$(this).removeClass('image_4_hovered');
	});
	
	//Start the teaser on the home page
	$('#hp_teaser').cycle({
		fx: 'fade',
		
		speed: 2500,
		before:  onBefore,
	    timeout: 6000,
		pager:  '#teaser_nav',
		pause: 1,
		pagerAnchorBuilder: function(idx, slide) {
			return '#teaser_nav div:eq(' + idx + ')';
	    }
	});
	
	//Hover over the teaser buttons
	$('#teaser_nav .button').hover(function(){
		$(this).addClass('button_hovered');
	},
	function(){
		$(this).removeClass('button_hovered');
	});

	//center the buttons of the teaser
	centerTeaserBtns();
	
	//Add project images navigation
	addImageNavigation();
	
	//Call to the function for aligning the services' blocks on services page
	alignServices();
	   
	$('#ex2').jqm({ajax: '/googleMap', trigger: 'a.ex2trigger', onHide: function(h) { 
		h.o.remove();
		h.w.fadeOut(888); // hide window
    }});
    
    
	//$("#longdescimg").fullsize(); // bind event on the default picture
	
	//Replace fullsize() - #longdescimg
	//$().piroBox({
	$(".blockProjectImages .itemSmallImg a").piroBox({
		my_speed: 400, //animation speed
		bg_alpha: 0.5, //background opacity
		radius: 4, //caption rounded corner
		scrollImage : true, // true == image follows the page, false == image remains in the same open position
		pirobox_next : 'piro_next', // Nav buttons -> piro_next == inside piroBox , piro_next_out == outside piroBox
		pirobox_prev : 'piro_prev',// Nav buttons -> piro_prev == inside piroBox , piro_prev_out == outside piroBox
		close_all : '.piro_close, .piro_overlay',// add class .piro_overlay(with comma)if you want overlay click close piroBox
		slideShow : 'slideshow', // just delete slideshow between '' if you don't want it.
		slideSpeed : 6 //slideshow duration in seconds(3 to 6 Recommended)
	});
	
//	$(".AAA__blockProjectImages .itemSmallImg a").prettyPhoto({
//		animationSpeed: 'normal', /* fast/slow/normal */
//		padding: 40, /* padding for each side of the picture */
//		opacity: 0.35, /* Value betwee 0 and 1 */
//		showTitle: false, /* true/false */
//		allowresize: true, /* true/false */
//		counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
//		theme: 'light_rounded_2', /* light_rounded / dark_rounded / light_square / dark_square */
//		hideflash: false, /* Hides all the flash object on a page, set to TRUE if flash appears over prettyPhoto */
//		modal: false, /* If set to true, only the close button will close the window */
//		changepicturecallback: function(){}, /* Called everytime an item is shown/changed */
//		callback: function(){} /* Called when prettyPhoto is closed */
//	});
	
	$('#inquiryStyledSelect').styledSelect();
	
	// ?iframe=true&width=100%&height=100%
	$("#portfolio_container a[rel^='prettyPhoto'], #one_project_container .itemLink a[rel^='prettyPhoto'], #one_project_container .similarItemLink a[rel^='prettyPhoto']").each(function(){
		
		//IE6/7 (Bug) Feature(!) here - When the URL in the href equals to the LinkText, on changing the href - the LinkText is also changed to the Href value!!!
		// http://groups.google.com/group/jquery-dev/browse_thread/thread/22029e221fe635c6?pli=1
		var temp = $(this).attr('href');
		var temp_text = $(this).text(); //use text(), not val() for correct value
		
		$(this).attr('href', temp  + '?iframe=true&width=100%&height=100%');
		//Now restore the original text!
		$(this).text(temp_text);
		
		// Do not call pretty photo here! It doesn't open correct index of the clicked link
		
	});
	
	
	// Call directly with specific selector and not into EACH() loop. It doesn't open correct index of the clicked link
	$("#portfolio_container a[rel^='prettyPhoto'], #one_project_container .itemLink a[rel^='prettyPhoto'], #one_project_container .similarItemLink a[rel^='prettyPhoto'], a.contactMapModal[rel^='prettyPhoto']").prettyPhoto({
		animationSpeed: 'normal', /* fast/slow/normal */
		padding: 40, /* padding for each side of the picture */
		opacity: 0.35, /* Value betwee 0 and 1 */
		showTitle: false, /* true/false */
		allowresize: true, /* true/false */
		counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
		theme: 'light_rounded_2', /* light_rounded / dark_rounded / light_square / dark_square */
		hideflash: false, /* Hides all the flash object on a page, set to TRUE if flash appears over prettyPhoto */
		modal: false, /* If set to true, only the close button will close the window */
		changepicturecallback: function(){}, /* Called everytime an item is shown/changed */
		callback: function(){} /* Called when prettyPhoto is closed */
	});
	
	// Home page - this is similar to setInterval!
	if( $('#js_projects_home_container').length ) {
		setTimeout ( "reloadProjectsHome()", reload_projects_home_delay );
		
		$('#js_projects_home_container').hover(function(){
			js_projects_home_container_hover = 1;
		},function(){
			js_projects_home_container_hover = 0;
		});
	}
	
	$("#antyButton").click(function(){
	    //alert('s');
	    //$("#antyBot").remove();
	    $("#antyDiv").append('<input type="hidden" name="anty" value="1" id="antyBot" />');
	});
	
});
