// JavaScript Document
var isIE;
var color;
var cssexist = false;
var openOverlay = false;


$(document).ready(function () {
    isIE = $.browser.msie;

    // Check cookie
    cookieCheck('FontSize', 'normal', null);

    // Hide Seo elements and actions on it
    hideEl();

    // top menu

    topmenu();

    // maimenu
    mainmenu();

    // Zooming font
    fontzoom();

    // Carousel function
    $('div#carousel ul').css('visibility', 'hidden');
    carousel();

    // Featurette
    if ($('.featurette').length) {
        featurette();
    }

    // Questions
    if ($('div.questions').length) {
        questions();
    }

    // Custom select, checkbox, radio
    customRC();

    // Cufon replace
    Cufon.replace('ul.mainNav > li > a', { fontFamily: 'Sari-Medium' });
    Cufon.replace('ul.mainNav > li.active > a', { fontFamily: 'Sari-Medium', textShadow: '1px 1px rgba(137, 143, 30, 0.4)' });
    Cufon.replace('.cufon', { fontFamily: 'Sari-Medium', hover: true });
    Cufon.replace('.inside h1, .inside h2', { fontFamily: 'Sari-Medium', hover: true });
})

function customRC() {
    $('input[type="radio"]').ezMark();
    $('input[type="checkbox"]').ezMark();
}

function refreshRC() {
    var $popupRC = $('.popup');
    $('input[type="radio"]', $popupRC).ezMark();
    $('input[type="checkbox"]', $popupRC).ezMark();
}

function carousel() {
    // custom
    var speedShow = 1; // sec
    var speedSlide = 1; // sec
    var speedSlideAuto = 4; // sec
    var slideTime = 3600; // sec
    var seeWidth = 40;

    // objects and data
    var indexEl;
    var direction;
    var left;
    var steps;
    var active;
    var $clone;
    var $new;
    var $dot;
    var $pagination = $('div.pagination');
    var $carouselContainer = $('#carousel');
    var $carousel = $('div#carousel ul');
    var $item = $('div#carousel ul li');
    var $prevBtn = $('a.previous');
    var $nextBtn = $('a.next');
    var $background = $('#carousel div.background');
    var $nextLink;
    var carouselWidthN;
    var carouselWidth;
    var count = $item.length;
    var widthItem;
    var seeWidth;
    var current;
    var margin;
    var fstep;
    var step;
    var mins;
    var timer;
    var rotateTimer;
    var stopRotate = false;

    // start carousel
    inputs();
    if ($('#carousel').length) { }
    else { return }
    resize();
    prepare();
    time();
    checkHover();
    

    function inputs() {
        var $default;
        $('input[type="text"]').each(function () {
            $default = $(this).data('default');
            if ($(this).val() != $default) {
                $(this).addClass('focus');
            }
            $(this).focus(function () {
                $default = $(this).data('default');
                if ($(this).val() == $default) {
                    $(this).val('').addClass('focus');
                }
                keyControl = false;
                $(document).unbind('keydown');
            });
            $(this).blur(function () {
                if ($(this).val() == '') {
                    $(this).val($default).removeClass('focus');
                }
                $(document).bind('keydown');
                if ($('#carousel').length) {
                    $(document).jkey('left', function () {
                        rotate(1);
                    });
                    $(document).jkey('right', function () {
                        rotate(2);
                    });
                }
            });
        });
    }


    // timer
    function time() {
        if (count != 1) {
            clearInterval(rotateTimer);
            rotateTimer = setInterval(function () {
                rotate(2);
            }, slideTime * 1000);
        }
    }

    // hover stop carousel
    function checkHover() {
        $item.hover(
			function () {
			    stopRotate = true;
			    clearInterval(rotateTimer);
			    clearInterval(timer);
			},
			function () {
			    stopRotate = false;
			    timer = setInterval(function () {
			        time();
			    }, slideTime * 1000);
			}
		);
    }

    function resize() {

        $item = $('div#carousel ul li');
        // all sizes for carousel work
        carouselWidthN = $carouselContainer.width();
        widthItem = $item.width();
        current = 1;
        margin = parseFloat((carouselWidthN - (seeWidth * 2 + widthItem)) / 2);
        if (count != 1) {
            fstep = parseFloat(-carouselWidthN + ((widthItem * 2) + (margin * 2) + seeWidth));
        }
        if (count == 1) {
            fstep = parseFloat(-carouselWidthN + ((widthItem) + (margin) + seeWidth));
        }
        step = parseFloat(widthItem + margin);  // Need refactoring
        carouselWidth = parseFloat(((count + 2) * widthItem) + ((count + 2) * margin));

        $carousel.css('width', carouselWidth);
        $background.css('width', carouselWidth);

        // margin for items
        $item.each(function () {
            indexEl = $(this).index();
            $(this).css('margin-right', margin);
        });
    };

    function prepare() {
        var $dotsr = '';
        // prepare carousel, adding clone items
        if (count != 1) {
            $clone = $('div#carousel ul li:eq(' + (count - 1) + ')');
            $new = $clone.clone().prependTo($carousel);
            $clone = $('div#carousel ul li:eq(1)');
            $new = $clone.clone().appendTo($carousel);
        }
        $carousel.css('left', (fstep * 5)).css('visibility', 'visible');

        // Generate dots
        for (var i = 0; i < count; i++) {
            $dotsr += '<span class="dot inline"><!-- --></span>'
        }
        $('div.pagination').append($dotsr);
        $('span.dot:nth-child(' + current + ')').addClass('active');

        // appearing of carousel
            $carousel.animate({
                left: -fstep
            }, speedShow * 1000, function () {
                $('li.item:nth-child(' + (current + 1) + ') span.help').fadeIn(500);

            });
            if (count != 1) {
                $prevBtn.fadeIn(speedShow * 1000);
                $nextBtn.fadeIn(speedShow * 1000);
            }
            $pagination.fadeIn(speedShow * 1000);

    }

    function rotate(direction, $dot) {
        if (stopRotate == true) { return }
        clearInterval(timer);
        if ($carousel.is(':animated')) {
            return
        }
        if (direction == 1) {
            left = $carousel.get(0).offsetLeft;
            if (current == 1) {
                $('li.item:nth-child(' + (count + 2) + ') span.help').show();
            }
            if (current == 1) {
                $carousel.css('left', left - step * count);
            }
            left = $carousel.get(0).offsetLeft;
            steps = left + step;
            dots(current, direction);
        }
        if (direction == 2) {
            if (current == count) {
                $carousel.css('left', (-fstep + step));
            }
            left = $carousel.get(0).offsetLeft;
            steps = left - step;
            dots(current, direction);
        }
        if (direction == 3) {
            indexEl = $dot.index() + 1;
            if (indexEl == current) { return }
            steps = indexEl - current;
            left = $carousel.get(0).offsetLeft;
            steps = left - (step * steps);
            current = indexEl;
            dots(current, direction);
        }
        $('span.help').each(function () {
            $(this).fadeOut(1000);
        });
        $background.animate({
            left: (steps / 4 - 200)
        }, speedSlide * 1000);
        $carousel.animate({
            left: steps
        }, speedSlide * 1000, function () {
            help(current, direction);
            clearInterval(rotateTimer);
            time();
        });
    }

    function help(current, direction) {
        $('li.item:nth-child(' + (current + 1) + ') span.help').fadeIn(500);
        if (current == count) {
            $('li.item:nth-child(1) span.help').fadeIn(500);
        }
    }

    function dots(active, direction) {
        if (direction == 1) {
            if (current == 1) { current = count; }
            else { current = current - 1; }
            $('span.dot').removeClass('active');
            $('span.dot:nth-child(' + current + ')').addClass('active');
            return
        }
        if (direction == 2) {
            if (current == count) { current = 1; }
            else { current++; }
            $('span.dot').removeClass('active');
            $('span.dot:nth-child(' + current + ')').addClass('active');
            return
        }
        $('span.dot').removeClass('active');
        $('span.dot:nth-child(' + current + ')').addClass('active');
    }

    // actions
    $('span.dot').click(function () {
        rotate(3, $(this));
    });
    $prevBtn.click(function () {
        rotate(1);
    });
    $nextBtn.click(function () {
        rotate(2);
    });
    $(window).resize(function () {
        resize();
    });

    // Key control
    $(document).jkey('left', function () {
    if ($('#carousel').length) {
        rotate(1);
    }
    });
$(document).jkey('right', function () {
        if ($('#carousel').length) {
            rotate(2);
        }
    });
    
}

function hideEl() {
    // hide
    $('.invisible').each(function () {
        $(this).hide();
    });

    // actions
    $('.text div.visible a').click(function () {
        $(this).parent().next().slideToggle();
        $(this).toggleClass('active');
    });
}

function mainmenu() {
    var $submenu;
    var $link;
    var $object;
    var $prevobject;
    var indexA;
    var exist = false;
    var active = false;
    var closes = false;
    var closesMain = false;
    var currentLink = $('ul.mainNav > li').index('li.active');
    var hoverLink;
    var counts;

    $('ul.mainNav > li').hover(
		function () {
		    hoverIt($(this));
		},
		function () {
		    unhoverIt($(this));
		}
	);

    function hoverIt($object) {
        if ($object.hasClass('active')) { active = true; }
        else { active = false; }
        if ($object.children('ul.subNav').length > 0) {
            counts = $object.children('ul.subNav').children().length;
            exist = true;
            $submenu = $object.children('ul.subNav');
            if (active == false) {
                $object.addClass('active');
                $link = $object.children('a').addClass('refresh');
            }
            Cufon.replace('ul > li.active > a.refresh', { fontFamily: 'Sari-Medium', textShadow: '1px 1px rgba(137, 143, 30, 0.4)' });
            $submenu.show();
            return
        }
        else { return }
    }

    function unhoverIt($object) {
        hoverLink = $('ul.mainNav > li').index($object);
        if (hoverLink != currentLink) {
            exist = false;
            Cufon.replace('ul > li.active > a.refresh', { fontFamily: 'Sari-Medium', color: '#272662' });
            $link = $object.children('a');
            $object.removeClass('active');
            $link.removeClass('refresh');
        }
        $submenu.hide();
    }

    // Key control
    $('ul.mainNav > li > a').focus(function () {
        $object = $(this).parent('li');
        hoverIt($object);
        closes = false;
    });

    $('ul.mainNav > li > a').blur(function () {
        if (closesMain == true && closes == false) {
            $object = $(this).parent('li');
            active = false;
            unhoverIt($object);
            closesMain = false;
        }
    });

    $('ul.subNav > li > a').focus(function () {
        closes = true;
        closesMain = false;
    });

    $('ul.subNav > li > a').blur(function () {
        closesMain = true;
        indexA = $(this).parent().index();
        if (indexA == 0) {
            closesMain = true;
        }
        if (indexA > 0) {
            closesMain = false;
        }
        if (indexA == counts - 1) {
            $object = $(this).parent().parent().parent('li');
            unhoverIt($object);
            closes = false;
            closesMain = false;
        }
    });
}

function topmenu() {
    var $topmenu = $('.topmenu');
    var $topObject;
    var leftPosition;
    var widthUl;
    var leftOff;
    var widthItemLi;

    widthUl = $($topmenu).width();

    $('.topmenu ul').each(function () {
        var itemLeft = $(this).parent('li').get(0).offsetLeft;
        leftPosition = itemLeft - 40;
        if (widthUl - 60 < itemLeft) {
            leftPosition = widthUl - 150;
        }
        $(this).css('left', leftPosition);
    });

    $('ul.topmenu > li').hover(
		function () {
		    showTop($(this));
		},
		function () {
		    hideTop($(this));
		}
	);

	function showTop($topObject) {
        $('ul', $topObject)
            .stop(true, true)
            .fadeIn();
    }

    function hideTop($topObject) {
        $('ul', $topObject)
            .stop(true, true)
            .fadeOut();
    }
}

function featurette() {
    var speedF = 1;

    var $featurette = $('div.featuretteContainer');
    var $images = $('ul.images', $featurette);
    var $tabs = $('ul.tabs', $featurette);
    var $content = $('ul.featuretteText');
    var indexTab;
    var $parent;
    var tab;
    var heightContainer = 0;
    var activetab;
    var breadCrumbs;
    var $objectF;
    var method;
    var indexFirst;
    var nowbreadCrumbs;
    var activeF = false;
    var firstClick = false;

    if ($('.featurette').hasClass('active')) {
        activeF = true;
    }

    startFeaturette();

    function startFeaturette() {
        indexFirst = $('li.active', $tabs).index();
        fadeFeaturette(indexFirst);
    }

    function fadeFeaturette(tab) {
        if ($('ul.images > li').is(':animated')) {
            return
        }
        if (tab == activetab) { return }
        if (activeF == true) {
            fade($('ul.images > li:eq(' + activetab + ')'), 1);
            $('ul.tabs > li:eq(' + activetab + ')').removeClass('active');
            fade($('ul.featuretteText > li:eq(' + activetab + ')'), 1);
        }

        color = $('ul.tabs > li:eq(' + tab + ') h2 a').attr('class');
        //changeColor(color);

        if (activeF == true) {
            breadCrumbs = $('ul.tabs > li:eq(' + tab + ') h2 a').text();
        }
        $('ul.tabs > li:eq(' + tab + ')').addClass('active');
        fade($('ul.images > li:eq(' + tab + ')'), 2);
        fade($('ul.featuretteText >  li:eq(' + tab + ')'), 2);
        if ($('.breadCrumbs li.last').prev().text() != breadCrumbs && activeF == true) {
            $('.breadCrumbs li.last').text('' + breadCrumbs + '');
        }
        if (firstClick || !heightContainer) {
           // heightContainer = $('ul.images li:eq(' + tab + ') img').height();
           // $featurette.css('height', '' + heightContainer + 'px');
            $('ul.images').addClass('ab');
        }

        $('ul.featuretteText > li > div').each(function () {
            if ($(this).height() > heightContainer) {
                heightContainer = $(this).height();
            }
        });

        $content.css('height', heightContainer);
        $('ul.tabs > li:eq(' + tab + ')').addClass('active');

        Cufon.replace('ul.tabs li h2 a', { fontFamily: 'Sari-Medium' });

        activetab = tab;
    }

    function fade($objectF, method) {
        if (method == 1) {
            $objectF.fadeOut(speedF * 1000);
        }
        if (method == 2) {
            $objectF.fadeIn(speedF * 1000);
        }
    }
    $('a', $tabs).click(function () {
        if (activeF == true) {
            firstClick = true;
            $parent = $(this).parent().parent();
            indexTab = $parent.index();
            fadeFeaturette(indexTab);
        }
    });
}

function cookieCheck(cook, value, existCookie) {
    var result;
    if ($.cookie('' + cook + '') == null) {
        $.cookie('' + cook + '', '' + value + '', { path: '/', expires: 7 });
        return false
    }
    if (existCookie == 2) {
        result = $.cookie('' + cook + '');
        return result;
    }
    if (existCookie == 3) {
        $.cookie('' + cook + '', '' + value + '', { path: '/', expires: 7 });
        return
    }
}

function fontzoom() {
    var standart = 'normal';
    var nowsize;
    var $objectFont;

    nowsize = cookieCheck('FontSize', null, 2);

    if (nowsize != standart) {
        $('body').addClass(nowsize);
    }
    $('.fontSize a.' + nowsize + '').addClass('active');

    $('.fontSize a').click(function () {
        changeFont($(this));
    });

    function changeFont($objectFont) {
        if ($objectFont.hasClass('active')) { return }
        $('.fontSize a').removeClass('active');
        $objectFont.addClass('active');
        $('body').removeClass('' + nowsize + '');
        nowsize = $objectFont.data('size');
        cookieCheck('FontSize', '' + nowsize + '', 3)
        if (nowsize == standart) { return }
        $('body').addClass('' + nowsize + '');
    }

    // Key control
    $('.fontSize a').jkey('enter', function () {
        changeFont($(this));
    });
}

function changeColor(color) {
    var $css = $('head').children('.color');
    if (!$css.length) {
        $css = $('<link />').addClass('color')
                            .attr({
                                rel: 'stylesheet',
                                type: 'text/css'
                            }).appendTo('head');
    }
    $css.attr({
        href: color ? '/Content/Styles/' + color + '.css' : '',
        disabled: !(color)
    });
}

function questions() {
    $('li > a', 'div.questions').click(function () {
        $(this).next().slideToggle(100);
        $(this).toggleClass('open');
    });
}

function popup() {
    var $overlay = $('div.overlay');
    var $close = $('a.close');

    var heightOverlay;
    if (openOverlay) return;
    
    openOverlay = true;    
    heightOverlay = $('body').outerHeight();
    $overlay.css('height', heightOverlay);
    fadePopup(true);

    $close.click(function () {
        fadePopup(false);
    });
    
    /*
    $overlay.click(function () {
        fadePopup(false);
    });
    */
}

function fadePopup(show) {
    var $popup = $('div.popup');
    var $overlay = $('div.overlay');

    if ($popup.is(':animated')) {
        return;
    }
    if (show) {
        $overlay.fadeIn();
        $popup.fadeIn(500);
        var heightPopup = $('.popup').outerHeight();
        var marginTop = heightPopup / 2;
        $('.popup').css('margin-top', -marginTop);
        $('input', $popup).focus();
        BindCustomValidation('div.popup', true);
    }
    else {
        $popup.fadeOut(500);
        $overlay.fadeOut(500);
        openOverlay = false;
    }
}

function SetFocusToControl(selector) {
    jQuery(selector).focus();
}

function checkDate(sender, args) {
    if (sender._selectedDate < new Date()) {
        alert($('#DateIsIncorectErrorMsg').text());
        sender._selectedDate = new Date();
        sender._textbox.set_Value(sender._selectedDate.format(sender._format))
    }
}
