var siteActions = {};
siteActions.jq= jQuery.noConflict();

(function($) {
    siteActions.jq(document).ready(function() {


        var mt = $('meta[name=SKYPE_TOOLBAR]');
        mt = mt.length ? mt : $('<meta name="SKYPE_TOOLBAR" />').appendTo('head');
        mt.attr('content', 'SKYPE_TOOLBAR_PARSER_COMPATIBLE');
        
        var mainErrorMessage = "- privalu pateikti";

        $('.listSelectorArrow').live('click', showSList);
        $('ul.listSelector li').live('mouseover mouseout', function(event){hoverSList(event, $(this) )});

        function hoverSList(event, listObjItem ){


            if( event.type =='mouseover' ){
                
                var listObj = listObjItem.parent('ul');
                //alert(listObj.length);
                if( listObj.hasClass('listSelectorActive') && listObjItem.index()>0 ){
                    listObjItem.addClass('hover');
                }

            }else{
                listObjItem.removeClass('hover');
            }
            
        }

        function showSList(){

            var listObj = $(this).parent().find('ul');
            var listItemsCount = listObj.children('li').length;

            if(listItemsCount>1){

                if( !listObj.hasClass('listSelectorActive') ){
                    listObj.addClass('listSelectorActive');
                    listObj.children('li').each(
                        function(){

                            if(!$(this).hasClass('active') ){
                                $(this).addClass('visible');
                            }
                        }
                    );
                }else{
                    hideSList();
                }
            }


        }

        function hideSList(){

            var listItemsCount = $('.listSelector').children('li').length;
            if(listItemsCount>1 && $('.listSelector').hasClass('listSelectorActive') ){
                $('.listSelector').removeClass('listSelectorActive');
                $('.listSelector').children('li').each(

                    function(){
                        if($(this).hasClass('visible') ){
                            $(this).removeClass('visible');
                        }
                    }

                );
            }

        }


        $('.bannerAreaInner').live('mousemove', function(event){moveSlider(event,$(this))});


        function moveSlider(event, obj){


            var width = 0;

            obj.children().children('a').each(function() {
                width += $(this).outerWidth( true ) + parseInt($(this).css('marginRight'));
            });

            //width = parseInt(width/2);

            var left = (event.pageX - obj.offset().left) * (width-obj.width()) / obj.width();

            
            obj.scrollLeft(left);

    }


        setInnerSlider();

        function setInnerSlider(){

            var sliderObj = $('ul.pageInnerSlider');
            if( sliderObj.length!=0 ){
                setInterval( function() {
                    var bClass = document.body.className;

                    if( bClass!='blurred'){
                        loopSlider(sliderObj);
                    }
                }, 3000);
            }
        }
        
        function onBlur() {
            document.body.className = 'blurred';
        };
        function onFocus(){
            document.body.className = 'focused';
        };

        if (/*@cc_on!@*/false) { // check for Internet Explorer
            document.onfocusin = onFocus;
            document.onfocusout = onBlur;
        } else {
            window.onfocus = onFocus;
            window.onblur = onBlur;
        }

        function loopSlider(listObj){

            var currentSlide = listObj.find('li.active');
            var currentSlideIndex = currentSlide.index();
            var sliderLength = listObj.children('li').size();
            var nextSlide = (currentSlideIndex+1)<sliderLength?currentSlideIndex+1:0;

            listObj.children('li').each(
                function (){
                    if( $(this).index()==nextSlide ){                  
                        var nextSlideObj = $(this);

                        nextSlideObj.css('opacity',0);
                        nextSlideObj.addClass('active');
                        
                        currentSlide.stop(true,true).animate({                            
                            opacity: 0
                        }, 2000, null, function(){
                            currentSlide.removeClass('active');                             
                        });
                        
                        nextSlideObj.stop(true,true).animate({
                            opacity: 1
                        }, 2000);

                        

                    }

                }

            );

        }


        var is_active = false;

        $('.contentBlocksTitle').live('mouseover', function(event){
            moveBlock(event, $(this) )
        });

        $('.contentListBlocks').live('click', function(){
            $(window.location).attr('href', $(this).find('input[name="link"]').val());
        });

        $('.leftArrow, .rightArrow').live('click', slideServices);

        $("a[rel^='prettyPhoto']").prettyPhoto({
            theme: 'facebook',
            slideshow:5000,
            autoplay_slideshow:false
        });

        $('.zoomBtn').live('click', function(event){event.preventDefault();});
        $('.registerForm, .contactsForm').live('submit', function(event){sendFormData(event, $(this) )});

        $('.registrationBtn').live('click', function(event){registrationPopup(event, $(this))});        
        
        $('.optionSelectorArrow').live('click', showOptionsList);
        $('.optionSelectorList li.active').live('click', hideOptionsList);
        $('.optionSelectorList li.visible').live('click', selectOption);          

        function selectOption(){
           
            var ulObj = $(this).closest('ul');
            var oldItem = ulObj.find('li.active');
            var inputObj = $(this).closest('.optionSelector').find('input[type="hidden"]');
            inputObj.val($(this).text());
            
            oldItem.removeClass('active');
            oldItem.addClass('visible');
            
            $(this).removeClass('visible');
            $(this).addClass('active');
            $(this).index(0);
            
            var cloneObj = $(this).clone();            
            ulObj.find('li:first-child"').before(cloneObj);
            
            $(this).hide();
            
            hideOptionsList();
        }

        function hideOptionsList(){
            
            var listItemsCount = $('.optionSelectorList').children('li').length;
            
            if(listItemsCount>1 && $('.optionSelectorList').hasClass('optionSelectorListActive') ){
                $('.optionSelectorList').removeClass('optionSelectorListActive');
                $('.optionSelectorList').children('li').each(

                    function(){
                        if($(this).hasClass('visible') ){
                            $(this).removeClass('visible');
                        }
                    }

                    );
            }
        }


        function showOptionsList(){
           
            var listObj = $(this).parent().find('ul');
            var listItemsCount = listObj.children('li').length;
            
            if(listItemsCount>1){

                if( !listObj.hasClass('optionSelectorListActive') ){
                    listObj.addClass('optionSelectorListActive');
                    listObj.children('li').each(
                        function(){
                            if(!$(this).hasClass('active') ){
                                $(this).addClass('visible');
                            }
                        }
                        );
                }else{
                    hideOptionsList();
                    
                }
            }
        }
        
        function registrationPopup(event, linkObj){
            
            event.preventDefault();

            params = {
                type: 'registrationPopup'
            };
            
            data = _sendAjax(ajaxURI, params);

            if(data.regPopup.length!=0 ){
                registrationScreen(data.regPopup);
            }
            
        }

        initDefaults();

        function initDefaults(){

            setTitles();
            setContactsForm();
        }

        function setTitles(){

            var titleHeight, titleParentHeight, offsetTop;

            $('.contentBlocksTitleText').each(
                function(){
                    titleHeight =  parseInt($(this).height());
                    titleParentHeight =parseInt($(this).parent().height())+parseInt($(this).parent().css('paddingTop'))+parseInt($(this).parent().css('paddingBottom'));
                    offsetTop = (titleParentHeight - titleHeight)/2;
                    $(this).css('top',offsetTop+'px');
                }
            );

        }

        function setRegistrationForm(){

            if( $('.registerForm').length!=0 ){
                $('.registerForm').validate({

                    onkeyup: false,
                    onfocusin: false,
                    onfocusout: false,
                    onclick: false,
                    errorElement: "div",
                    errorPlacement: function(error, element) {
                            error.appendTo( element.parent("div") );
                    },
                    rules: {
                        name:{
                            required: true
                        },
                        phone: {
                            phonecheck: true,
                            required: true
                        },
                        email:{
                            email: true,
                            required: true
                        },
                        date: {
                            required: true
                        },
                        time: {
                            required: true
                        },
                        is_consultation: {
                            required: true
                        },
                        service: {
                            required: true
                        },
                        doctor: {
                            required: true
                        }
                    },
                    messages: {
                        name:{
                            required: mainErrorMessage
                        },
                        phone: {
                            required: mainErrorMessage
                        },
                        email:{
                            email: mainErrorMessage,
                            required: mainErrorMessage
                        },
                        date: {
                            required: mainErrorMessage
                        },
                        time: {
                            required: mainErrorMessage
                        },
                        is_consultation: {
                            required: mainErrorMessage
                        },
                        service: {
                            required: mainErrorMessage
                        },
                        doctor: {
                            required: mainErrorMessage
                        }
                    }
                });
            }
         }

        servicesOverflow();

        function setContactsForm(){

            if( $('.contactsForm').length!=0 ){
                $('.contactsForm').validate({
                    invalidHandler:function(e, validator) {
                        var errors = validator.numberOfInvalids();
                        if (errors) {
                            var message = errors == 1? 'Jūs neteisingai užpildėte vieną lauką. Jis pažymėtas apačioje': 'Jūs neteisingai užpildėte ' + errors + ' laukus(-ų). Jie pažymėti apačioje';
                            $(".contactFormMessage").html(message);
                            $(".contactFormMessage").show();
                        } else {
                            $(".contactFormMessage").hide();
                        }
                    },
                    showErrors: function(){
                        if (this.settings.highlight) {
                            for (var i = 0; this.errorList[i]; ++i) {
                                this.settings.highlight.call(this, this.errorList[i].element,
                                    'red', this.settings.validClass);
                            }
                        }
                        if (this.settings.unhighlight) {
                            for (var i = 0, elements = this.validElements(); elements[i]; ++i) {
                                this.settings.unhighlight.call(this, elements[i],
                                    'red', this.settings.validClass);
                            }
                        }
                    },
                    onkeyup: false,
                    onfocusin: false,
                    onfocusout: false,
                    onclick: false,
                    rules: {
                            name: {
                                    required:true,
                                    minlength:3,
                                    maxlength:15
                            },
                            surname: {
                                    required: true
                            },
                            email: {
                                    required: true,
                                    email: true
                            },
                            phone: {
                                    phonecheck: true

                            }

                    }
                });

            }
        }




        function sendFormData(event, form){

            event.preventDefault();
            
            params = form.serialize();
            data = _sendAjax(ajaxURI, params);

            msgObj = form.find('.formMsg');            
     
            msgObj.removeClass('red');

            if(data.success){   
                form[0].reset();               
            }else{
                msgObj.addClass('red');                               
            }
            msgObj.text(data.text); 
        }

        function _sendAjax(url, params){
            var responseData = {};
            $.ajax({
                url: url + '?lang=' + siteLANG + '&' + new Date().getTime(),//prevent cache,
                type: "POST",
                async: false,
                data: params,
                datatype:"html",
                success: function(response){
                    if( isStrJSON(response) ){
                        var data = $.parseJSON(response);
                        responseData = data;
                    }else{

                    }
                },
                error: function(){

                }
            });
            return responseData;
        }





        function servicesOverflow(){

            var servicesObj = $('.floatContent').find('.services');
            var floatObj = $('.floatContent').find('.servicesInner');

            if(floatObj.length!=0){

                var widthLimit = 680;
                var widthCurrent = 0;
                var widthMax = 0;
                var count = 0;
                var showMax = 4;

                floatObj.find('.floatContentBlocks').each(function(){
                    if(showMax > count){
                        widthMax += parseInt($(this).outerWidth());
                    }
                    widthCurrent += parseInt($(this).outerWidth());
                    count++;
                });

                if(widthCurrent > widthLimit){
                    servicesObj.css('width',widthMax+'px');
                    floatObj.css('width',widthCurrent+'px');
                }else{
                    floatObj.css('width',widthLimit+'px');
                }
            }
        }

        function slideServices(){

            var floatObj = $(this).closest('.floatContent').find('.services');
            var floatWidth  = floatObj.find('.floatContentBlocks').outerWidth();

            if($(this).hasClass('leftArrow')){

                floatObj.animate({scrollLeft: '-='+floatWidth*4},1000);

            }else if($(this).hasClass('rightArrow')){

                floatObj.animate({scrollLeft: '+='+floatWidth*4},1000);
            }
        }

        function moveBlock(event, obj){

            if(is_active){
                return;
            }else{
                is_active = true;
            }

            var contentBlock = obj.closest('.contentListBlocksInner');
            var contentZoom =contentBlock.find('.openBlock');
            var details = contentBlock.find('.detailsBlock');
            var height = details.outerHeight();

            obj.find('.contentBlocksTitleText').toggleClass('textUnderline');

            if(details.css('display')=='block'){
                contentZoom.removeClass('closeBlock');
                details.fadeOut({
                    duration:800,
                    easing: 'easeOutBounce',
                    complete: function(){
                        contentBlock.animate({
                            marginTop: 0
                        }, {
                            duration:700,
                            easing: 'easeOutBounce'
                        } );
                        is_active = false;
                    }
                });
            }else{
                contentZoom.addClass('closeBlock');
                contentBlock.animate({
                    marginTop: '-=' + height
                }, {
                    duration:800,
                    easing: 'easeOutBounce',
                    complete: function(){
                        details.css('display','block');
                        
                        is_active = false;
                    }
                });
            }

        }



        var total = $('#slider img').length;
        var rand = Math.floor(Math.random()*total); 

        $('#slider').nivoSlider({
            pauseTime: 5000, // default: 3000. How long each slide will show
//            startSlide: rand, // default: 0. Set starting Slide (0 index)
            directionNav: false, // default: true. Next & Prev navigation
            directionNavHide: false, // default: true. Only show on hover
            keyboardNav: false, // default: true. Use left & right arrows
            effect:'boxRain',
            beforeChange: function(){
                $('#slider').css('background', 'none repeat scroll 0 0 transparent'); 
                
                $('.blueMainText').find('.activeLeft').removeClass('activeLeft');
                
                var currSlide = $('#slider').data('nivo:vars').currentSlide;
                var countEl = $('.blueMainText').find('img');
                
                countEl.each(function(index){                    
                    if((index == 0) && (currSlide == countEl.length - 1)){
                        $(this).addClass('activeLeft');
                    }else if(index == currSlide + 1){
                        $(this).addClass('activeLeft');
                    }
                });
            },
            afterChange: function(){
                $('#slider').css('background', 'none repeat scroll 0 0 transparent');                
            } 
        });


        /* SPLASH / MAP SCREEN BEGIN*/

        function showSplash( title, text){

            var textContainer = $(".splashScreen").find(".splashScreenText");

            textContainer.children('h2').html(title);
            textContainer.children('div').html(text);

            $(".splashScreen").overlay({
                top: 0,
                mask: {
                    color: '#000000',
                    loadSpeed: 1000,
                    opacity: 0.7,
                    zIndex: 9998
                },
                closeOnClick: true,
                effect: 'drop',
                load: true
            }).load();

        }
        
        function registrationScreen( html ){

            var innerBlock = $(".registrationScreen").find(".registrationScreenInner");

            innerBlock.html(html);

            $(".registrationScreen").overlay({
                top: 0,
                mask: {
                    color: '#777777',
                    loadSpeed: 1000,
                    opacity: 0.7,
                    zIndex: 9998
                },
                onLoad: function(){
                    
                    $('.dateInput').datepicker();                                      
                     
                    setRegistrationForm();
                    
                    $('.optionSelector').each(function (i) {
                        $(this).find('input[type="hidden"]').val($(this).find('li.active').text());                        
                    });
                },                
                closeOnClick: true,
                effect: 'drop',
                load: true
            }).load();

        }


        $.easing.drop = function (x, t, b, c, d) {
            return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
        };

        $.tools.overlay.addEffect("drop", function(css, done) {

            var conf = this.getConf(),
            overlay = this.getOverlay();
            if (conf.fixed)  {
                css.position = 'fixed';
            } else {
                css.top += $(window).scrollTop();
                css.left += $(window).scrollLeft();
                css.position = 'absolute';
            }

            overlay.css(css).show();

            overlay.animate({
                top: '+=70',
                opacity: 1,
                width: '+=10'
            }, 800, 'drop', done);

        }, function(done) {
            this.getOverlay().animate({
                top:'-=70',
                opacity:0,
                width:'-=10'
            },100, 'drop', function() {
                $(this).hide();
                done.call();
            });
        }
        );

    /* SPLASH SCREEN END*/




    function isStrJSON(str) {


         if ($.trim(str) == '') return false;
         str = str.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, '');
         return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);
    }

    });

    $.validator.addMethod("phonecheck", function( value, element ) {
        var result = validatePersonPhone(value);
        return result;
    }, "Neteisingai įvestas tel. nr, formatas +370 XXXXXXXX");

    function validatePersonPhone(phone){

        var is_valid = false;

        phone = phone.replace(/ /g,'');

        var firstNum = phone.substr(0,4);
        var lastNums = phone.substr(4,12);

        if(
            firstNum=='+370' && phone.length==12 && parseInt(lastNums)
        ){
            is_valid = true;
        }

        return is_valid;
    }

})(jQuery);
