
$(document).ready(function() {
////console.log($('body').hasClass("first"));
$('body').addClass('first');

/* Title Problem */
/*
if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt )
  {
    var len = this.length;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}*/

function detectMobile(){
	var list = ['iPad','iPod','iPhone'];
	var p = navigator.userAgent;
	for(i in list)
		if(p.indexOf( list[i] ) != -1) return true;
	return false;
}
function shadowBoxTitles(){
    $('[title]').each(function() {
        $this = $(this);
        $.data(this, 'title', $this.attr('title'));
        $this.removeAttr('title');
    });
}
if(detectMobile()){
	Shadowbox.init({viewportPadding:100,onClose:closeFunction, onOpen:openFunction});	
	setTimeout(function(){
		$('#fixmenu').attr('class','right_content');
		$('#strack').remove();
	},20);
}else{
	Shadowbox.init();	
}	

function closeFunction(){
	$('body').css('overflow','scroll');
}
function openFunction(){
	$('body').css('overflow','hidden');
}

var insideHashChange = false;
setTitle( window.location.hash );

////console.log("document ready");
var counti = 0;
var prevHash = "-1";
var tim;


var r = $(".right_content");
r.addClass("fixed_menu");
if(!detectMobile()){
	r.css('top','0px');
	r.css('height',$(window).height()-35);
	$("#menu_scroll").css('height',$(window).height()-215);
	r.css('left',($(window).width()/2+243)+"px");
	
	
}

var me = $('#menu');
var sc = $('#menu_scroll');
var th = $('#sthumb');
th.animate({opacity:0},1);
$('#strack').animate({opacity:0},1);


$(window).resize(function() {
	//window.trigger('onscroll');//.scroll();
	if(!detectMobile()){
		r.css('height',$(window).height()-35);
		r.css('left',($(window).width()/2+243)+"px");
		$("#menu_scroll").css('height',$(window).height()-185);
	}
			
	$("#content .left_content#two").css("min-height",($(window).height()-65)+"px");
	$("* html #content .left_content#two").css("height",($(window).height()-65)+"px").css("overflow","visible");
});
$(window).trigger('resize');

//
if(!groupExists("topBanners"))
addGroup( $(".top_banner_ch") , 12000, "topBanners", true, 400);

//setTimeout(function(){ $('html,body').stop().animate({scrollTop: $('html,body').scrollTop()+2 }, 1); }, 50);

$(window).bind('hashchange',function(){
	clearTimeout(tim);
	tim = setTimeout(function(){
		if (window.location.hash != prevHash) {
			counti++;
			////console.log("Hash changed ("+counti+"): "+window.location.hash+", Inside Change: " + insideHashChange);
			
			if(!insideHashChange){
				var h = window.location.hash.split("/");
				if(h.length > 0 && h[0] != "#"){
					if(h.length > 1 && h[0].indexOf("#search") != -1){
						////console.log("search for: "+h[1]);
						$("#search_input").val(h[1].replace(/_/g," "));
						search($("#search_input").val());
					}else if(h[0].length > 0 && $("."+h[0].substring(1)).length != 0){
						$("."+h[0].substring(1)).trigger('click');
					}else{
						closeSearch();
					}
				}else{
					closeSearch();		
				}
			}
			setTitle( window.location.hash );
			insideHashChange = false;
			prevHash = window.location.hash;
	    }
	},100);
});
$(window).trigger('hashchange');

function setTitle( h ){
	var ha = h.split("/");
	h = ""
	for(var i in ha){
		if(i < ha.length){
			if(i==0)		
				ha[i] = ha[i].substring(1);
			else
				h+=": ";
			ha[i] = String(ha[i]).replace(/_/g," ");
			ha[i] = capitaliseFirstLetter( ha[i] );
			h+=ha[i];
		}
	}
	var hai = "MOLOS Group" + ((h!="") ? " / " : "") + h;
	$(document).attr('title', hai );
}
function capitaliseFirstLetter(string){
    return string.charAt(0).toUpperCase() + string.slice(1);
}

setTimeout(function(){
	$(window).trigger('hashchange');
},100);


if(detectMobile()){
	setInterval(function(){
		if($('#sb-container').css('position') != "absolute"){
			$('#sb-container').css('position','absolute');			
		}
		$('#sb-container').css('height', $(window).height()+200+"px !important" );
		
		$('#sb-container').css('top',$(window).scrollTop()-100);
	},10);
}


function toHashName( s ){
	return s.toLowerCase().replace(/ /g,"_");
}

$('#menu_scroll').bind('mouseenter', function(){
	if($(this).height() < $('#menu').height() && !detectMobile() ){
		//$(this).css('overflow-y','scroll');
		th.stop().animate({opacity:0.5},300);
		$('#strack').animate({opacity:0.1},300);
	}
});
$('#menu_scroll').bind('mouseleave', function(){
	if(!detectMobile()){	
		//$(this).css('overflow-y','hidden');
		th.stop().animate({opacity:0},300);
		$('#strack').animate({opacity:0},300);
	}
});

th.bind('click',function(){
	return false;
});

sc.bind('scroll',function(){
	if(!detectMobile()){
		th.css('top', ( sc.scrollTop()/(me.height()-sc.height() ) )*(sc.height()-th.height()+5) +150+"px" );
		th.css('height', (sc.height()/me.height()*sc.height())+"px");
	}
	//window.trigger('onscroll');
	//$(window).scroll();
});

// ON LOAD REMOVE THE FIRST THUMB AND PUT IT IN BIG BOX
$(".small_box:first-child").hide().queue( function(){ changeBigBox_Project($(this)) } ).find('a').attr('rel','shadowbox[group]');

// rightMenuScroll(){

function getScrollTop(){
    if(typeof pageYOffset!= 'undefined'){
        //most browsers
        return pageYOffset;
    }
    else{
        var B= document.body; //IE 'quirks'
        var D= document.documentElement; //IE with doctype
        D= (D.clientHeight)? D: B;
        return D.scrollTop;
    }
}

	var menu = $('#menu');
	var tbMargin = 20;	
	var speed=400;
	// IF IN MOBILE SET SPEED TO ZERO
	if(detectMobile())	
		speed = 0;	
	// DO NOT CHANGE
	var defaultY = menu.offset().top;
	var defaultHeight = menu.height()+30;
	var prevT = -1;
	var s = 0;
	// SCROLL EVENT	
	$(window).scroll( function (){ 
		defaultHeight = menu.height()+30;
		var scrollTop = $(window).scrollTop();
		var windowHeight = $(window).height();
		var menuY = menu.offset().top;
		
		//diff = 1;
		//if(prevT != -1) var diff =  scrollTop-prevT;
		
		//$("#footer .center-content").html( $(window).height()-35 );
		/*
		r.css('height',$(window).height()-35);
		r.css('left',($(window).width()/2+243)+"px");
		$("#menu_scroll").css('height',$(window).height()-185);
		
		th.css('top', ( sc.scrollTop()/(me.height()-sc.height() ) )*(sc.height()-th.height()+5) +150+"px" );
		th.css('height', (sc.height()/me.height()*sc.height())+"px");
		*/
		var _default = true;
		//if(scrollTop > defaultY-(tbMargin) ){
			/*
			r.addClass("fixed_menu");
			r.css('top','0px');
			$(".scroll_content").scroll(1000);
			s += (scrollTop-prevT);
			$(".scroll_content").scrollTop($(".scroll_content").scrollTop()+(scrollTop-prevT));
			//console.log("right:"+$(window).width());
			r.css('left',($(window).width()/2+243)+"px");
			*/
			/*if(defaultHeight < windowHeight){
					menu.stop().animate({'top':  scrollTop-defaultY+(tbMargin)},speed);
					_default = false;
			}else{
				if(diff >= 0){
					if(menuY+defaultHeight < scrollTop+windowHeight-(tbMargin))
						menu.stop().animate({'top':  (scrollTop+windowHeight-defaultHeight-(tbMargin))-defaultY},speed);
					_default = false;
				}else{
					if(menuY > scrollTop+(tbMargin))
						menu.stop().animate({'top':  scrollTop-defaultY+(tbMargin)},speed);
					_default = false;
				}
			}*/
		/*}else{
			var r = $("#fixmenu");
			r.removeClass("fixed_menu");
			r.scrollTop(0);
		}
		if(_default) menu.stop().animate({'top': 0},speed);*/
		//prevT =  scrollTop;
		
		//$("#footer .center-content").html((scrollTop+windowHeight)+">"+($(document).height()-150));
		
		if(scrollTop+windowHeight > $(document).height()-150){
			//console.log("Scroll");
			loadMore();
		}
	});
// } <- rightMenuScroll
	
		
	
	// MENU AND CATEGORY CLICK
	$('.category_item').click(function(){
		if(!clickBlocked){
			blockClick();
			closeSearch(false);
			if($(this).parent().parent().find('.projects').length != 0){
				aId = $(this).attr('class').split(' ')[1];
				//console.log(aId+" - "+activeId);
				if(aId == activeId){
					closeFilter();
					return;
				}
				deActiveMenu();
				setActiveCategory( $(this).parent() );
				filterProducts("category_id", aId);
				
				var linkHash = $(this).attr('class').split(' ')[2];
				var hash = window.location.hash;
				if(linkHash != hash){
					window.location.hash = toHashName(linkHash);
					insideHashChange = true;
				}		
				activeId = aId;
			}
			
		}
		return false;
	});	
	
	$('.menu_item').click(function(){
		if(!clickBlocked){
			blockClick();
			closeSearch(false);
			aId = $(this).attr('class').split(' ')[1];
			deActiveMenu();
			setActiveMenu( $(this).parent() );
			if(aId == activeId){
				closeFilter();
				return;
			}
			
			if($(this).hasClass("projects")){			
				filterProducts("menu_id", aId)
			}else if($(this).hasClass("text")){
				filterProducts("none",-1,false);
				changeBigBox_Text(aId);
			}else if($(this).hasClass("contact")){
				filterProducts("none",-1,false);
				changeBigBox_Contact(aId);
			}else if($(this).hasClass("clients")){
				filterProducts("none",-1,false);
				changeBigBox_Clients(aId);
			}
			
			var linkHash = $(this).attr('class').split(' ')[3];
			var hash = window.location.hash;
			if(linkHash != hash){
				window.location.hash = toHashName(linkHash);
				insideHashChange = true;
			}
			activeId = aId;
		}
		return false;
	});	
	
	var clickBlocked = false
	function blockClick(){
		clickBlocked = true;
		setTimeout(function(){ clickBlocked=false; },600);		
	}
	
	
	//SEARCH
	var t;
	var c=0;
	$('#close_search').stop().fadeOut(0);
	$("#search_input").keyup(function(event){
		if(event.keyCode == 13){
			clearTimeout(t);
			
			search($(this).val());
			insideHashChange = true;
			window.location.hash = "search/"+toHashName($(this).val());			
		}else if(event.keyCode == 27){
			closeSearch();
		}else{
			var s = $(this).val();
			clearTimeout(t);
			t = setTimeout(function(){				
				if(s == ""){
					closeSearch();
				}else{
					search(s);
					insideHashChange = true;	
					window.location.hash = "search/"+toHashName(s);
				}
			},250);
		}
	});
	function search(s){
		deActiveMenu();
		showSearchX();
		filterProducts("search",-1,true, s);		
	}
	
	$('#close_search').click(function(){
		closeSearch();
	});
	function closeSearch( _i ){
		(_i==undefined)?_i=true:null;
		$("#search_input").val("");
		hideSearchX();
		if(_i)
			closeFilter();
	}
	function showSearchX(){
		$('#close_search').stop().fadeIn();
	}
	function hideSearchX(){
		$('#close_search').stop().fadeOut();
	}
	
// filterProducts(){
	var activeLi;
	var activeType;
	var activeId = -1;	
	// SET ACTIVE MENU AND CATEGORY / DEACTIVATE
	function setActiveMenu( liEl ){
		liEl.find('.menu_close').stop().animate({width:11,marginRight:4},200);
		activeLi = liEl;
		activeLi.find('a').stop().animate({color:"#4a423c"},200);
		activeType = "menu";
	}
	function setActiveCategory( liEl ){
		liEl.find('.x').animate({width:11},200);
		activeLi = liEl;
		activeType = "category";
	}
	function deActiveMenu(){
		if(activeLi){
			if(activeType == "menu"){
				activeLi.find('.menu_close').animate({width:0,marginRight:0},200);
				activeLi.find('a').stop().animate({color:"#867b6f"},200);
			}else if(activeType == "category"){
				activeLi.find('.x').stop().animate({width:0},200);
			}
		}
		activeLi = null;
	}
	
	// CLOSE 
	$('.menu_close').click(function(){
		if(activeLi)
			closeFilter();
	});
	$('.category_close').click(function(){
		if(activeLi)
			closeFilter();
	});
	function closeFilter(){
		activeId = -1;
		filterProducts("none",-1);
		deActiveMenu();
		
		window.location.hash = "";
		insideHashChange = true;
	}
	// FILTER THUMBS
	var loadItems = 6;
	var PAGE = 0;
	var openBy = "none";
	var openId = -1;
	var openSetBigBox = undefined;
	var openSearchWord = undefined;
	
	// OPEN FIRST
	//filterProducts(null,-1);
	var gr = 0;
	
	function filterProducts(_by,_id,_setBigBox,_searchWord){
		//_setBigBox = false;
		// SCROLL TO TOP
		(_by ==null)?_by = "none" : null;
		(_setBigBox == undefined)?_setBigBox=true:null;
		(_searchWord == undefined)?_searchWord="":null;
		
		//console.log("Filter Products {by:"+_by+", id:"+_id+",setBigBox:"+_setBigBox+",searchWord:"+_searchWord);
		
		if(openBy != _by || openId != _id || openSetBigBox != _setBigBox || _searchWord != openSearchWord){
		
			openBy = _by;
			openId = _id;
			openSetBigBox = _setBigBox;
			openSearchWord = _searchWord;		
			
			// FIRST SCROLL
			$('html,body').stop().animate({scrollTop: 0}, 200);	
			// THEN FADE OUT IMAGES
			//$("a.shbox").attr('rel','shadowbox['+(gr++)+']');
			$(".currentBoxes").delay(220).animate({opacity:0},200,function(){ $(this).remove() });
	
			// RESET PAGE
			PAGE = 0;
			
			bLoading = true;		
			
			$("#loading_text").show();
			$("#loading_text_p").html("");
				
			setTimeout(function(){
			$.ajax({
				url: 'getBoxes.php',
				type: "POST",
				data: {id : _id, by: _by, page: PAGE, items: loadItems*2 , bigbox: _setBigBox, offset: 0 , searchWord: _searchWord },
				success: function( data ) {
					$("#small_boxes").html(data);	
					$(".anim").css("display","block");			
					// FADE IN NEW THUMBS
					$(".nextBoxes").addClass("currentBoxes").removeClass("nextBoxes");
					$(".anim").animate({opacity:0},0).delay(100).animate({opacity:1}, 400);
					$(".anim").removeClass("anim");
					bLoading = false;
					$("#loading_text").hide();
					//console.log("---["+_setBigBox+"] - ["+_id+"] - ["+_by+"]---");
					if(_setBigBox && _id != -1 && _by != "none"){ 
						changeBigBox_Category( $(".small_box:first").find(".category_id").attr('class').split(' ')[1] );
						//changeBigBox_Project( $(".small_box:first") );
						//$(".small_box:first").hide();
					}else if((_setBigBox && _id == -1 && _by == "none") || _searchWord.length > 0){
						changeBigBox_HomePage();
					}
					shadowBoxTitles();
					
					Shadowbox.clearCache();
					if($('a.shbox').length > 0)
					Shadowbox.setup($('a.shbox'),{flashParams:{movieWidth:"500",height:366}});
					
					$('.small_box').mouseenter(mouseEnter);
					$('.small_box').mouseleave(mouseLeave);
					PAGE++;
				}
			});
			},600);
			
		}		
	}
	var bLoading = false;
	function loadMore(){
		if(!bLoading && PAGE != 0){
			//console.log("Load More");
			PAGE++;
			//console.log("PAGE: "+PAGE);
			bLoading = true;
			if( Number($('a.shbox').length) != Number($("#res_length").html()) ){
				$("#loading_text").show();
				$("#loading_text_p").html($('a.shbox').length+"/"+$("#res_length").html());
			}
			$.ajax({
				url: 'getBoxes.php',
				type: "POST",
				data: {id : openId, by: openBy, page: PAGE, items: loadItems , offset: $("a.shbox").length, searchWord: openSearchWord },
				success: function( data ) {
					bLoading = false;
					//$("#small_boxes").find(".currentBoxes").append("MoreText, ");
					//console.log("Loaded:"+$(data).find("a.shbox").length);
					//var b = $("#small_boxes").find(".currentBoxes");
					document.getElementById('bboxes').innerHTML = document.getElementById('bboxes').innerHTML+data;
					//$("#small_boxes").find(".currentBoxes").append(data);	
					//$(".anim").css("display","block");
					// FADE IN AND CHANGE THE CLASS OF THE NEW ITEM
					
					//$(".anim").animate({opacity:0},0).delay(100).animate({opacity:1}, 400);
					$(".anim").removeClass("anim");
					bLoading = false;
					$("#loading_text").hide();
					
					shadowBoxTitles();		
					if($('a.shbox').length > 0)			
					Shadowbox.setup($('a.shbox'));
					
					$('.small_box').mouseenter(mouseEnter);
					$('.small_box').mouseleave(mouseLeave);
					
					//$(window).animate({scrollTop: $(document).height() }, 100);
					
				}
			});
		}
	}
// } <- filterProducts


// bigBox(){
	var activeBigBox;
	
	function changeBigBox_Text( _id, _text ){
		(_text==undefined)?_text="-1":null;
		$.ajax({
			url: 'getText.php',
			type: "POST",
			data: {id : _id, text: _text},
			success: function( data ) {
				var time = closeCurrentBigBox()*200+1;
				$("#big_box_content").append(data);				
				// FADE IN AND CHANGE THE CLASS OF THE NEW ITEM
				$(".nextBig").animate({opacity:0},0).animate({opacity:1}, time, function(){ $(this).addClass("currentBig").removeClass("nextBig"); });
			}
		});
	}
	
	function changeBigBox_Clients( _id ){
		$.ajax({
			url: 'getClients.php',
			type: "POST",
			data: {id : _id},
			success: function( data ) {
				var time = closeCurrentBigBox()*200+1;
				
				$("#big_box_content").append(data);				
				// FADE IN AND CHANGE THE CLASS OF THE NEW ITEM
				$(".nextBig").animate({opacity:0},0).animate({opacity:1}, time, function(){ $(this).addClass("currentBig").removeClass("nextBig"); });
				
				initClients( $(".clients_big.nextBig") );
			}
		});
	}	
	
	function changeBigBox_Contact( _id ){
		$.ajax({
			url: 'getContact.php',
			type: "POST",
			data: {id : _id},
			success: function( data ) {
				var time = closeCurrentBigBox()*200+1;
				$("#big_box_content").append(data);				
				// FADE IN AND CHANGE THE CLASS OF THE NEW ITEM
				$(".nextBig").animate({opacity:0},0).animate({opacity:1}, time, function(){ $(this).addClass("currentBig").removeClass("nextBig") });
				initContact();
				loadMap();
				addPoints();
			}
		});
	}
	
	/* CONTACT INIT */
	function initContact(){
		$(".submit").click(function() {  $("#contactform").trigger('submit'); });
        $("#contactform").validate({ onkeyup:false, submitHandler:contact_submit });
        //$('#security_code').attr('value', '');
	}
	function contact_done() { window.location = '/'; }
	function contact_submit(){
		$("#contact-details").html("<img src='Images/loading_contact.gif'>Sending...");
		$.ajax({
			type: "POST",
			url: "sendmail.php",
			data: $("#contactform").serialize(),
			success: function(data){
				if (data == "SUCCESS"){
					$("#contact-details").html("Successfully sent");
					//alert("Success");
					//$('#contactform').fadeOut('slow', function() { $('#contact_sent').slideDown('slow', function(){ setTimeout (contact_done,5000); }); });
				}else if (data == "BADCODE"){
					//alert("The security code you typed was wrong. Please try again.");
				}else{
					if(data == "first_name"){
						$("#first_name").val( "First name required" )
					}else if(data == "email"){
						$("#email").val( "Email required" )
					}else if(data == "comments"){
						$("#comments").val( "Message required" )
					}else if(data == "invalid_email"){
						$("#email").val( "Please enter valid email" )
					}
					$("#contact-details").html("Message not sent, please try again: "+data);//. Error data: "+data
				}
			}
		});
	}
	
	function openFirstVisible(){
		$('.small_box').each(function(){
			if($(this).find('a').attr('rel').indexOf("shadowbox[group]") != -1){
				$(this).find('a').trigger('click');
				return false;
			};
		});
	}
	
	var openCat = -1;
	function changeBigBox_Category( _id ){
		if(openCat != _id){
			$.ajax({
				url: 'getCat.php',
				type: "POST",
				data: {id : _id},
				success: function( data ) {
					var time = closeCurrentBigBox()*200+1;
					openCat = _id;
					$("#big_box_content").append(data);				
					// FADE IN AND CHANGE THE CLASS OF THE NEW ITEM
					$(".nextBig").animate({opacity:0},0).animate({opacity:1}, time, function(){ $(this).addClass("currentBig").removeClass("nextBig") })
				}
			});
		}
	}
	function changeBigBox_HomePage(){
		if(!groupExists('homeSlideshow')){
			//$("#big_box").stop().animate({height:175},0);
			$.ajax({
				url: 'getHome.php',
				type: "POST",
				success: function( data ) {
					var time = closeCurrentBigBox()*200+1;
					$("#big_box_content").append(data);				
					// FADE IN AND CHANGE THE CLASS OF THE NEW ITEM
					$(".nextBig").animate({opacity:0},0).animate({opacity:1}, time, function(){ $(this).addClass("currentBig").removeClass("nextBig") })
					addGroup( $(".home-slideshow") , 11000, "homeSlideshow", true, 400);
					addGroup( $(".v_image") , 0, "galleryV", false, 0);
				}
			});
		}
	}
	
	
	function changeBigBox_Project( smallBox ){
		var time = closeCurrentBigBox()*300+1; // closeCurrentBigBox() - returns 0 if there is no open item, and 1 if the item is open

		var imgUrl = smallBox.find('a').attr("href");
		var color = smallBox.find(".color").attr('class').split(' ')[1];
		
		var toAdd= "<div class='project_big nextBig'>";
				// IMAGE
				toAdd+="<div class='big_box_image'>";
					toAdd += "<div class='"+smallBox.find('.menu_id').attr('class')+"'></div>"; 
					//toAdd+= "<a href='"+imgUrl+"' rel='shadowbox[group]' class='shbox'>";
					toAdd+= "<a href='#' class='flink'>";
						toAdd+="<img src='"+smallBox.find('img').attr("src").replace("=203","=242").replace("=203","=242").replace(":140",":215").replace("=140","=215")+"' alt='image'>"
					toAdd+="</a>";
				toAdd+="</div>";
				// TEXT
				toAdd+="<div class='big_box_text'>";
					toAdd+= "<div class='project_big_category'>";
						// GET LOGO SOURCE
						var catId = smallBox.find(".category_id").attr('class').split(' ')[1];
						var logoSrc = $(".cat_"+catId+" .logo_src").html();
						// OUTPUT LOGO AND LOGO TITLE
						toAdd+= "<img class='project_big_logo' src='"+logoSrc+"' alt='image'>";
						toAdd+= "<span class='project_big_logo_title'>"+$(".cat_"+catId+" .category_item font").html()+"</span>";
					toAdd+="</div>";
					
					// OUTPUT PROJECT TITLE / TEXT
					toAdd+= "<div class='project_big_text' >";
						toAdd+= "<h4 style='color:"+color+";'>"+smallBox.find('.small_box_title_t').html()+"</h4><br>";
						toAdd+= smallBox.find('.small_box_title_c').html();
						toAdd+= smallBox.find('.small_box_text').html();
					toAdd+="</div>";
				toAdd+="</div>";
				// LINE
				toAdd+="<div class='big_box_line' style='background-color:#"+ color +";'></div>";
			toAdd+="</div>";
			
		// APPEND THE NEW ITEM TO BOX
		$("#big_box_content").append(toAdd);
		// FADE IN AND CHANGE THE CLASS OF THE NEW ITEM
		$(".nextBig").animate({opacity:0},0).animate({opacity:1}, time, function(){ $(this).addClass("currentBig").removeClass("nextBig"); });
		
		$(".flink").click(function(){
			openFirstVisible();
			return false;
		});
		
		$('.big_box_image').mouseenter(mouseEnter);
		$('.big_box_image').mouseleave(mouseLeave);
	}	
	function closeCurrentBigBox(){
		openCat = -1;
		if(groupExists('homeSlideshow')){
			removeGroup("homeSlideshow");
			removeGroup("galleryV");
			//$("#big_box").stop().animate({height:230},0);
		}
		
		$('html,body').stop().animate({scrollTop: 0}, 400);	
		// FADE OUT AND REMOVE THE CURRENT ITEM
		t = 300;
		if(detectMobile())
			t = 0;
		$(".currentBig").animate({opacity:0},t,function(){ $(this).remove() });
		$("#big_box_content").find('a').attr('rel','shadowbox');
		if($('a.shbox').length != 0)	
			Shadowbox.setup($('a.shbox'));
		return (detectMobile())?0:1;//$(".currentBig").length;
	}
// } <- bigBox


// initClients(){
	var clients;
	var openedClient = null;
	function initClients( _clients ){
		openedClient = null;
		clients = _clients;
		
		$(".client_logo").each(function(){
			if($(this).css('display') == "block"){
				$(this).stop().animate({opacity:0},0);
			}
		});	
		
		$(".client_logo").click(function(){
			deActivateClient();
			activateClient($(this));
			filterProducts("client_id",$(this).attr('class').split(' ')[1].substring(2) ,false);
		});
		$(".clients_pagination li").click(function(){
			$(".clients_pagination li.active").removeClass('active');
			$(this).addClass('active');
			changeClientsPage( $(this).html() );
		});
		changeClientsPage(1);
	}
	function deActivateClient(){
		if(openedClient != null){
			openedClient.stop().animate({borderColor:"#ffffff"},300);
		}
	}
	function activateClient(cl){
		cl.stop().animate({borderColor:"#eeeeee"},300);
		openedClient = cl;
	}
	function changeClientsPage(_n){
		var cNumber = 0;
		if(_n-1 == 0)
			cNumber = 4;
		else
			cNumber = 6;
			
		var pastLogos = 0;
		if(_n-1 == 1){
			pastLogos = 4;
		}else if(_n-1 > 1){
			pastLogos = 4 + (_n-2)*6;
		}
			
		var n = _n;
		var t = detectMobile()?0:300;
		// FADE OUT
		$(".client_logo").each(function(){
			if($(this).css('display') == "block"){
				$(this).stop().animate({opacity:0},t);
			}
		});	
		// FADE IN
		setTimeout(function(){
			var i = 0;
			$(".client_logo").each(function(){
		
				if(_n-1 == 0){
					$(".big_box_image").show();
					$(".change_class").addClass("big_box_text").removeClass("big_box_text_full");
					$(".client_logo").css("margin","5px 15px");
				}else{
					$(".big_box_image").hide();
					$(".change_class").addClass("big_box_text_full").removeClass("big_box_text");
					$(".client_logo").css("margin","5px 27px");
				}
		
				if(i>=pastLogos && i<pastLogos+cNumber){
					$(this).css('display','block').animate({opacity:1},t);
				}else{
					$(this).css('display','none');
				}
				i++;
			});
		},t);
	}
// } <- initClients


// SMALL BOXES MOUSE OVER
	function mouseEnter(){
		if(openBy != "menu_id"){
			var mid = $(this).find(".menu_id").attr('class').split(' ')[1];
			$('.menu_item').each(function(){
				if($(this).attr('class').split(' ')[1] == mid){
					var _color = '#'+$(this).parent().parent().find('font').attr('color');
					$(this).stop().css('text-decoration','underline').animate({color:_color},100);
				}
			});
		}
	}
	
	function mouseLeave(){
		if(openBy != "menu_id"){
			var mid = $(this).find(".menu_id").attr('class').split(' ')[1];
			$('.menu_item').each(function(){
				if($(this).attr('class').split(' ')[1] == mid){
					$(this).stop().css('text-decoration','none').animate({color:"#867b6f"},100);
				}
			});
		}
	};
	
	
	$('#contact_molos').click(function(){
		$('.menu_item.contact').trigger('click');
	});
	
	$('#logo').click(function(){		
		closeSearch();
	});

	
	var aGroups;// = new Array();
	var g = 0;
	var groupNames;
	function addGroup( _objs , _delay , _name, _timeOut, _speed ){
		if(aGroups == undefined) aGroups = new Object();
		if(groupNames == undefined) groupNames = new Array();
		
		var gs = (_name == null) ? ("group_"+(g++)) : (_name);
		if(groupNames.indexOf(gs) == -1){
			groupNames.push(gs);
			//console.log("addGroup:"+gs);
			aGroups[gs] = new Object();
			var i = 0;
			aGroups[gs].objs = new Array();
			$(_objs).each(function(){
				if(i != 0)
					$(this).hide();
				else
					$(this).fadeIn(_speed);
				aGroups[gs].objs[i] = $(this);
				i++;
			});
			aGroups[gs].name = gs;
			aGroups[gs].length = _objs.length;
			aGroups[gs].current = 0;
			aGroups[gs].delay = _delay;
			aGroups[gs].cont = true;
			aGroups[gs].bTimeOut = _timeOut;
			aGroups[gs].speed = _speed;
			if(_timeOut)
				aGroups[gs].timeOut = setTimeout(processSlides, aGroups[gs].delay, aGroups[gs]);
			return gs;
		}
	}	
	function groupExists(_name){
		if(aGroups == undefined) aGroups = new Array();
		if(groupNames == undefined) groupNames = new Array();

		if(groupNames.indexOf(_name) != -1)
			return true;
		return false;
	}	
	function removeGroup( _name ){
		if(groupNames.indexOf(_name) != -1){
			//console.log("removeGroup:"+_name);
			clearTimeout(aGroups[_name].timeOut);
			delete aGroups[_name];
			groupNames.splice(groupNames.indexOf(_name),1);
		}
	}	
	function processSlides( _obj ){
		if(_obj && _obj.cont){
			var r = _obj.current;
			_obj.current++;
			if(_obj.current == _obj.length)
				_obj.current = 0;
			$(_obj.objs[r]).fadeOut(_obj.speed);
			$(_obj.objs[_obj.current]).fadeIn(_obj.speed);
			if(_obj.name == "homeSlideshow" && _obj.current == 0){
				processSlides(aGroups['galleryV']);
			}
			if(_obj.bTimeOut)
				_obj.timeOut = setTimeout(processSlides,_obj.delay, _obj);
		}
	}	
	
	var focus = true;
	$(window).blur(function(){
		if(focus){
			focus = false;
			// Pause Slideshows
			for(var i in aGroups)
				clearTimeout(aGroups[i].timeOut);
		}
	});
	$(window).focus(function(){
		if(!focus){
			focus = true;
			// Restart Slideshows
			for(var i in aGroups)
				aGroups[i].timeOut = setTimeout(processSlides,aGroups[i].delay, aGroups[i]);
		}
	});
	
	
	function changeGalleryVImage(){
	}
	
	// GOOOOOOOOGLE MAPS
	//<![CDATA[
	// Google Map Maker script v.1.1
	// (c) 2006 Richard Stephenson http://www.donkeymagic.co.uk
	// http://mapmaker.donkeymagic.co.uk
	var map;
	var icon0;
	var newpoints = new Array();
	function addLoadEvent(func) { 
		var oldonload = window.onload; 
		if (typeof window.onload != 'function'){ 
			window.onload = func
		} else { 
			window.onload = function() {
				oldonload();
				func();
			}
		}
	}
	/*addLoadEvent(loadMap);
	addLoadEvent(addPoints);*/
	function loadMap() {
		map = new GMap2(document.getElementById("map"));
		map.addControl(new GLargeMapControl());
		//map.addControl(new GMapTypeControl());
		map.setCenter(new GLatLng( 42.64480297872606, 21.1553817987442), 17);
		 map.setMapType(G_SATELLITE_MAP);
	 
		icon0 = new GIcon();
		icon0.image = "http://www.google.com/mapfiles/marker.png";
		icon0.shadow = "http://www.google.com/mapfiles/shadow50.png";
		icon0.iconSize = new GSize(20, 34);
		icon0.shadowSize = new GSize(37, 34);
		icon0.iconAnchor = new GPoint(9, 34);
		icon0.infoWindowAnchor = new GPoint(9, 2);
		icon0.infoShadowAnchor = new GPoint(18, 25);
	}
	function addPoints() {		 
		
		newpoints[0] = new Array(42.64480297872606, 21.1553817987442, icon0, 'MOLOS Group', 'MOLOS Group'); 
	
		for(var i = 0; i < newpoints.length; i++) {
			var point = new GPoint(newpoints[i][1],newpoints[i][0]);
			var popuphtml = newpoints[i][4] ;
			var marker = createMarker(point,newpoints[i][2],popuphtml);
			map.addOverlay(marker);
		}
	}		 
	function createMarker(point, icon, popuphtml) {
		var popuphtml = "<div id=\"popup\">" + popuphtml + "<\/div>";
		var marker = new GMarker(point, icon);
		GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowHtml(popuphtml);
		});
		return marker;
	}

});

