var mainCarousel, thumbsCarousel;

$(function() {
    $("#jcarousel").jcarousel({
       wrap: "circular",
	   visible: 1,
	   scroll: 1,
	   initCallback: mainCarouselInit
    });
	$("#thubms-carousel").jcarousel({
		wrap: "circular",
		visible: 4,
		scroll: 1,
		initCallback: thumbsCarouselInit
    });
	
	$("#mix").hover(
		function() {
			$("#disc-obj").animate({bottom: "-10px"}, 150);
		},
		function() {
			$("#disc-obj").animate({bottom: "0px"}, 150);
		}
	);
	
	var curLeftItem = null;
	var ciTop = null;
	
	$("#rs-slider").jCarouselLite({
		vertical: true,
		visible: 3,
		scroll: 1,
		circular: true,
		btnNext: "#rs-next",
		btnPrev: "#rs-prev",
		speed: 500,
		beforeStart: function() {
			var bt = getElementPosition(document.getElementById("rs-slider")).top;
			var bh = getElementPosition(document.getElementById("rs-slider")).height;
			var items = $("#rs-slider li .this");
			curLeftItem = null;
			
			for (var i = 0; i < items.length; i++) {
				var it = getElementPosition(items.eq(i).get(0).parentNode).top;
				if (it >= bt && it < bt + bh) {
					curLeftItem = items.eq(i).get(0).parentNode;
					ciTop = it;
					break;
				}
				else {
					var ob = items.eq(i).get(0).parentNode;
					$(".tl-left", ob).animate({width: "257px", right: "27px"}, 100);
					$(".tl-right", ob).animate({right: "15px"}, 100);
					$(".tl-left .info", ob).animate({marginRight: "-100px", opacity: 0}, 100);
					$(".item:not('.small')", ob).animate({marginRight: "57px"}, 150);
					$(".item.small", ob).animate({marginRight: "76px"}, 150);
				}
			}
		}
	});
	
	$("#rs-next").click(function() {
		if (curLeftItem != null) {
			var ot = getElementPosition(curLeftItem).top;
			var bt = getElementPosition(document.getElementById("rs-slider")).top;
			if (ot - bt == 236) {
				$(".tl-left", curLeftItem).animate({width: "339px", right: "12px"}, 100);
				$(".tl-right", curLeftItem).animate({right: "0px"}, 100);
				$(".tl-left .info", curLeftItem).animate({marginRight: "10px", opacity: 1}, 100);
				$(".item:not('.small')", curLeftItem).animate({marginRight: "107px"}, 150);
				$(".item.small", curLeftItem).animate({marginRight: "137px"}, 150);
			}
			else {
				$(".tl-left", curLeftItem).animate({width: "257px", right: "27px"}, 100);
				$(".tl-right", curLeftItem).animate({right: "15px"}, 100);
				$(".tl-left .info", curLeftItem).animate({marginRight: "-100px", opacity: 0}, 100);
				$(".item:not('.small')", curLeftItem).animate({marginRight: "57px"}, 150);
				$(".item.small", curLeftItem).animate({marginRight: "76px"}, 150);
			}
		}
	});
	
	$("#rs-prev").click(function() {
		if (curLeftItem != null) {
			var ot = ciTop;
			var bt = getElementPosition(document.getElementById("rs-slider")).top;
			
			if (ot - bt == 0) {
				$(".tl-left", curLeftItem).animate({width: "339px", right: "12px"}, 100);
				$(".tl-right", curLeftItem).animate({right: "0px"}, 100);
				$(".tl-left .info", curLeftItem).animate({marginRight: "10px", opacity: 1}, 100);
				$(".item:not('.small')", curLeftItem).animate({marginRight: "107px"}, 150);
				$(".item.small", curLeftItem).animate({marginRight: "137px"}, 150);
			}
			else {
				$(".tl-left", curLeftItem).animate({width: "257px", right: "27px"}, 100);
				$(".tl-right", curLeftItem).animate({right: "15px"}, 100);
				$(".tl-left .info", curLeftItem).animate({marginRight: "-100px", opacity: 0}, 100);
				$(".item:not('.small')", curLeftItem).animate({marginRight: "57px"}, 150);
				$(".item.small", curLeftItem).animate({marginRight: "76px"}, 150);
			}
		}
	});
	
	$("#overlay, .popup .close").live("click", function() {
		closePopup();
	});

    // SS2011
    try {
        $(document).ready(function() {
            $('#starinsky-overlay').fadeIn('fast', function() {
                $('#box').fadeIn('fast');
            });
        });
        $('#boxclose').click(function() {
            $('#box').fadeOut('fast', function() {
                $('#starinsky-overlay').fadeOut('fast');
            });
        });
        VK.Widgets.Group("vk_groups", {mode: 0, width: "300", height: "281"}, 23128394);
    } catch (e) {
        // TODO: exception for disabled elements
    }
    // Sorry
});

function mainCarouselInit(c) {
	mainCarousel = c;
	$("#ms-prev").click(function() {
		c.prev();
	});
	$("#ms-next").click(function() {
		c.next();
	});
}

function thumbsCarouselInit(c) {
	thumbsCarousel = c;
	$("#thumbs-list li:first-child").addClass("act-item");
	
	$("#ms-prev").click(function() {
		c.prev();
		$("#thumbs-list li.act-item").removeClass("act-item").prev().addClass("act-item");
		changeLabel(c);
	});
	$("#ms-next").click(function() {
		c.next();
		$("#thumbs-list li.act-item").removeClass("act-item").next().addClass("act-item");
		changeLabel(c);
	});
	$("#thumbs-list .rol").click(function() {
		if (!$(this.parentNode).hasClass("act-item")) {
			var i = 1;
			var nItem = $(this.parentNode).prev();
			while (!nItem.hasClass("act-item")) {
				nItem = nItem.prev();
				i = i + 1;
			}
			mainCarousel.options.scroll = c.options.scroll = jQuery.jcarousel.intval(i);
			c.next();
			mainCarousel.next();
			$("#thumbs-list li.act-item").removeClass("act-item");
			$(this.parentNode).addClass("act-item");
			mainCarousel.options.scroll = c.options.scroll = jQuery.jcarousel.intval(1);
			
			changeLabel(c);
		}
	});
}

function rsCarouselInit(c) {
	$("#rs-prev").click(function() {
		c.prev();
	});
	$("#rs-next").click(function() {
		c.next();
	});
}
function asCarouselInit(c) {
	$("#rs-prev").click(function() {
		c.prev();
	});
	$("#rs-next").click(function() {
		c.next();
	});
}

function changeLabel(c) {
	$("#act-lbl").animate({bottom: "51px"}, 300).animate({bottom: "28px"}, 300).animate({bottom: "31px"}, 100);
	var items = $("#thumbs-list li.act-item a").attr("rel").split(";");
	$("#act-lbl .num").css({color: items[3]});
	$("#act-lbl .num em").text(items[0]);
	$("#act-lbl .num small").text(items[1]);
	$("#act-lbl .lbl").text(items[2]);
}

function showTabBlock(blockId) {
	$("#tabs-block .text").hide();
	$("#" + blockId).show();
	$("#tabs li").removeClass("act")
	$("#tabs li." + blockId).addClass("act");
}
function hideTabBlock(blockId) {
	$("#" + blockId).hide();
	$("#tabs li." + blockId).removeClass("act");
}

function getElementPosition(elem) {
    var w = elem.offsetWidth;
    var h = elem.offsetHeight;

    var l = 0;
    var t = 0;

    while (elem) {
        l += elem.offsetLeft;
        t += elem.offsetTop;
        elem = elem.offsetParent;
    }

    return { "left": l, "top": t, "width": w, "height": h };
}

(function(d){d.each(["backgroundColor","borderBottomColor","borderLeftColor","borderRightColor","borderTopColor","color","outlineColor"],function(f,e){d.fx.step[e]=function(g){if(!g.colorInit){g.start=c(g.elem,e);g.end=b(g.end);g.colorInit=true}g.elem.style[e]="rgb("+[Math.max(Math.min(parseInt((g.pos*(g.end[0]-g.start[0]))+g.start[0]),255),0),Math.max(Math.min(parseInt((g.pos*(g.end[1]-g.start[1]))+g.start[1]),255),0),Math.max(Math.min(parseInt((g.pos*(g.end[2]-g.start[2]))+g.start[2]),255),0)].join(",")+")"}});function b(f){var e;if(f&&f.constructor==Array&&f.length==3){return f}if(e=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(f)){return[parseInt(e[1]),parseInt(e[2]),parseInt(e[3])]}if(e=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(f)){return[parseFloat(e[1])*2.55,parseFloat(e[2])*2.55,parseFloat(e[3])*2.55]}if(e=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(f)){return[parseInt(e[1],16),parseInt(e[2],16),parseInt(e[3],16)]}if(e=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(f)){return[parseInt(e[1]+e[1],16),parseInt(e[2]+e[2],16),parseInt(e[3]+e[3],16)]}if(e=/rgba\(0, 0, 0, 0\)/.exec(f)){return a.transparent}return a[d.trim(f).toLowerCase()]}function c(g,e){var f;do{f=d.curCSS(g,e);if(f!=""&&f!="transparent"||d.nodeName(g,"body")){break}e="backgroundColor"}while(g=g.parentNode);return b(f)}var a={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0],transparent:[255,255,255]}})(jQuery);

function animateError(el){
	$("#"+el)
			.animate({ backgroundColor: "#ffccd4" }, 1000)
			.animate({ backgroundColor: "#fff" }, 1000)
			.animate({ backgroundColor: "#ffccd4" }, 1000)
			.animate({ backgroundColor: "#fff" }, 1000);
}

function formSubmit(form){
	var error = false
	
	if($('#name').val() == '' || $('#name').val() == 'Имя'){
		animateError('name');
		error = true;
	}
	
	if($('#email').val() == '' || $('#email').val() == 'E-mail'){
		animateError('email');
		error = true;
	}
	
	if($('#c').val() == '' || $('#c').val() == 'Цифры'){
		animateError('c');
		error = true;
	}
	
	if($('#message').val() == '' || $('#message').val() == 'Ваше сообщение'){
		animateError('message');
		error = true;
	}
	
	if(error){
		return false;
	}
	
	$.ajax({
		type: "POST",
		url: window.url + 'contacts/',
		data: $('#'+form).serialize(),
		success: function(msg){
			if( msg.indexOf( "form_success" ) !== -1 ){
				$('#'+form).fadeOut(800,function() {
					$('#success').fadeIn(800,function() {
						$('#' + form + " input").each(function(){
							if($(this).attr('type') != 'hidden'){
								$(this).val('');
							}
						});
						$('#' + form + " textarea").val('');
						window.setTimeout('location.reload()', 3000);
					});
				});
			}else if( msg.indexOf( "form_error" ) !== -1 ){
				animateError('c');
				return false;
			}
			
		}
	});
	 
	return false;
}

function openPopup(popId) {
	$("#overlay").show().height(getDocumentHeight());
	var popup = $("#" + popId);
	popup.append($("#pop-content").html()); 
	popup.show();
	var pw = popup.width();
	var ph = popup.height();
	popup.css({top: (getViewportHeight() - ph) / 2, marginLeft: -1 * pw / 2}); 
}

function closePopup(popId) {
	if (popId != null) {
		$("#overlay, #" + popId).hide();	
	}
	else {
		$("#overlay, .popup").hide();
	}
	$(".popup").html("<a class='close'></a>");
}


var ua = navigator.userAgent.toLowerCase();
var isOpera = (ua.indexOf('opera') > -1);
var isIE = (!isOpera && ua.indexOf('msie') > -1);

function getViewportHeight() {
	return ((document.compatMode || isIE) && !isOpera) ? (document.compatMode == 'CSS1Compat') ? document.documentElement.clientHeight : document.body.clientHeight : (document.parentWindow || document.defaultView).innerHeight;
}

function getDocumentHeight() {
	return Math.max(document.compatMode != 'CSS1Compat' ? document.body.scrollHeight : document.documentElement.scrollHeight, getViewportHeight());
}

function getBodyScrollTop() {
  return self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop);
}

