$(function (){
	$('input:text, textarea')
		.focus(function(){$(this).addClass('focus')})
		.blur(function(){$(this).removeClass('focus')});
	
	$('.order_form').click(OrderForm);
	$('.order_call').click(OrderForm);
	$('.order_header_div').click(OrderFormHeaderClick);
	$('.order_btn').html('');
	$('.mailers a').click(mailers)
	
	$('#order_frame_js').load(OrderFormFrameLoad);
	
	$("a.toggleVacancy").click(function(){
		var id = this.id;
		$("#toggleVacancy_"+id).slideToggle(1000,function(){
			if ($("#"+id).html().substr(4,1) == '+')
				html = $("#"+id).html().replace("<h2>+","<h2>-");
			else
				html = $("#"+id).html().replace("<h2>-","<h2>+");
			$("#"+id).html(html);
		});
	})
	$(".tabs a").hover(function(){
		var parent = $(this).parents("div.tab_container");
		$(".tab_content",parent).hide();
		$(".tabs a",parent).removeClass("active");
		$(this).addClass("active");
		$(this.hash).show();
	});
	$("a.slide").click(function(){
		$(this.hash).slideToggle("slow");
		$(this).toggleClass("plus");
		return false;
	});
	if (document.location.hash){
		hash = document.location.hash;
		$("a[href$="+hash+"]").hover();
	}
	
	if (getCookie('chat_btn_show') != 'N'){
		timeout_Open  = setTimeout("$('#chat').animate({width: 214}).addClass('show');", 3000);
		timeout_Close = setTimeout("$('#chat').animate({width:0}).removeClass('show');", 23000);
	}
	
	$('#chat').toggle(
		function(){
			$(this).animate({width: 214}).addClass('show');
			var date = new Date(); date.setTime( date.getTime() + (1000 * 3600) );
			setCookie('chat_btn_show', 'Y', date.toString(), '/');
			
			clearTimeout( timeout_Open ); clearTimeout( timeout_Close );
		},
		function(){
			$(this).animate({width:0}).removeClass('show');
			var date = new Date(); date.setTime( date.getTime() + (1000 * 3600) );
			setCookie('chat_btn_show', 'N', date.toString(), '/');
			
			clearTimeout( timeout_Open ); clearTimeout( timeout_Close );
		}
	)
	/*
	if (getCookie('chat_btn_show') != 'N')
	{
		fnChatTimeout_Open  = function(){};
		fnChatTimeout_Close = function(){$(this).animate({width:0}).removeClass('show');};
		
		//setTimeout("$('#chat').click();", 3000);
		//setTimeout("$('#chat').click();", 23000);
	}
	*/
	
	$('#chat div').click(function(){
		window.open(host + '/lz/chat.php?intgroup=Q2FzdGNvbQ==&amp;hg=Pw__&en=0JPQvtGB0YLRjA','','width=600,height=580,left=0,top=0,resizable=yes,menubar=no,location=no,status=yes,scrollbars=yes')
		return false;
	});
	
	$(".light-box").lightBox();
	$("#portfolio_carousel").jcarousel({
		itemLoadCallback: portfolio_itemLoadCallback,
		itemVisibleInCallback:portfolio_itemVisibleInCallback,
		wrap: 'both',
		scroll: 1
	});
	$("#client_carousel").jcarousel({
		wrap: 'circular',
		auto: 5
	});
	
})
	
function mailers()
{
	var email = $('.mailers input.text').val();
	if (!email.match(/[0-9a-z_]+@[0-9a-z_^.]+.[a-z]{2,3}/i)) 
	{
		alert("<span style='color:red;'>Не корректный ввод email</span>");
		return false;
	}
	
	var data = {
		'action': $(this).attr('act'),
		'email' : email
	};
	
	$.ajax({
		type   : 'POST',
		url    : host + '/lib/mailers_js.php',
		data   : data,
		success: function(resp){alert(resp);}
	})
	
	return false;
}

function AuxVars(vars) {
	for (prop in vars) {
		this[prop] = vars[prop];
	}
}
var avars = '';
function OrderForm(event) {
	var _avars_ = {
		fadeSpeed: 500, /* скорость появления окошек оформления заявки и обратного звонка */
		winerh: (window.innerHeight ? window.innerHeight : (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.offsetHeight))
	}
	avars = new AuxVars(_avars_);
	
	if (typeof(window.scrollY) == 'undefined') window.scrollY = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
	$('#order_supcontent_div')
		.css('height',$(document).height())
		.appendTo(document.body)
		.fadeIn(avars.fadeSpeed);

	if ( this.className.indexOf('order_form') != -1 ) {
		
		
		$('#order_content_div')
			.css('display','block')
			.appendTo('#order_supcontent_div');
			var top = parseInt((avars.winerh/2 - $('#order_content_div')[0].scrollHeight/2) + window.scrollY);
			if (top < 0) top = 0;
			$('#order_content_div').css("top",top);
			
	} else if ( this.className.indexOf('order_call') != -1 ) {
		$('#order_call_content_div')
			.css('display','block')
			.appendTo('#order_supcontent_div')
		var top = (avars.winerh/2 - $('#order_call_content_div')[0].scrollHeight/2) + window.scrollY;
		if (top < 0 ) top = 0;
		$('#order_call_content_div').css("top",top);
	}
	
	$('#order_mask_div')
		.css('opacity','0.5')
		.css('height',$(document).height())
		.appendTo(document.body)
		.fadeIn(avars.fadeSpeed);
	
	return false;
}
function OrderFormHeaderClick(event) {
	var el = event.target || event.srcElement;
	if ( el.className == 'order_header_close' ) {
		CloseOrderForm();
		return false;
	}
}
function CloseOrderForm() {
	$('#order_supcontent_div')
		.fadeOut(avars.fadeSpeed, function(){ $('#order_content_div').css('display','none');$('#order_call_content_div').css('display','none'); })
	$('#order_mask_div')
		.fadeOut(avars.fadeSpeed)
	$('#order_frame_js')
		.fadeOut(avars.fadeSpeed);
	$('#orders_form_js')[0].reset();
	$('#orders_call_form_js')[0].reset();
}
function OrderFormFrameLoad() {
	var doc = window.frames.order_frame_js.document || document.getElementById('order_frame_js').contentDocument;
	var el = doc.getElementById('order_done_js');
	
	var _avars_ = {
		fadeSpeed: 500, /* скорость появления окошек оформления заявки и обратного звонка */
		winerh: (window.innerHeight ? window.innerHeight : (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.offsetHeight))
	}
	avars = new AuxVars(_avars_);
	if (typeof(window.scrollY) == 'undefined') window.scrollY = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
	var top = parseInt((avars.winerh/2 - $('#order_frame_js')[0].scrollHeight/2) + window.scrollY);
			if (top < 0) top = 0;
	if ( el ){
		if (el.className != 'error'){
			$.prompt(el.innerHTML,{callback:CloseOrderForm});
		} else {
			$.prompt(el.innerHTML);
			$('.captcha-reload img').click();
		}
		//$.prompt(el.innerHTML,{callback:CloseOrderForm})
	}
}

function setCookie (name, value, expires, path, domain, secure) {
      document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}
function getCookie(name) {
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
}

function portfolio_itemLoadCallback(carousel, state)
{
	if (carousel.has(carousel.first, carousel.last)) {
        return;
    }
    
    $.ajax({
    	type	: 'GET',
//    	url		: 'http://' + document.domain + '/castcom.ru/js/ajax/portfolio.php',
		url		: 'http://' + document.domain + '/js/ajax/portfolio.php',
    	data	: 'first=' + carousel.first + '&last=' + carousel.last + '&cache=' + Math.random(),
    	success	: function(resp){
    		try
    		{
    			var arResult = eval('(' + resp + ')');
    			var item 	 = null;
    			carousel.size( arResult.total );
    			first = carousel.first;
    			for (i = 0; i < arResult.items.length; i++)
    			{
    				arItem = arResult.items[i]
    				item = carousel
    					.add(first + i, getHTML( arItem ))
    					.data('arrow_src', arItem.arrow);
    				if (i == 0)
    				{
    					portfolio_itemVisibleInCallback(carousel, item);
    				}
    			}
    		} catch (e) {}
    	}
    });
    
    function getHTML( arItem )
    {
    	var st_return = '<img src="' + arItem.image + '">'
    			+ ((arItem.is_new == 'Y') ? '<div class="sticker_new"></div>' : '')
    			+ '<div class="text-container">'
    			+ '<div class="h_1" ' + ((arItem.color_head) ? 'style="color: ' + arItem.color_head + '"' : '') + '>' + arItem.title + '</div>'
    			+ '<div ' + ((arItem.color_text) ? 'style="color: ' + arItem.color_text + '"' : '') + '>' + arItem.brief + '</div>'
    			+ '<div><a class="more" href="' + arItem.href + '">подробнее</a></div>'
    			+ '</div>';
    	return st_return;
    }
}

function portfolio_itemVisibleInCallback(carousel, item, index, state, eventName)
{
	arrow_src = $(item).data('arrow_src');
	$(carousel.buttonNext).css('background', 'url(' + arrow_src + ') 0 0 no-repeat');
	$(carousel.buttonPrev).css('background', 'url(' + arrow_src + ') -17px 0 no-repeat');
}
