$(function(){
    var clientsImgs = $('div.clientsHolder .clientsLogos img');
    var clientsImgs_l = clientsImgs.length;

    if(clientsImgs_l > 0){
        var clientsImgs_first = $('div.clientsHolder .clientsLogos img:first');
        var fadeTime = 600;
        var index = 0;
        var srcs = new Array();
        var i = 0;
        clientsImgs.each(function(){
            srcs[i] = $(this).attr('src');
            i++;
        });
 
        function doClientsLogosAnimation(){
            clientsImgs_first.animate({
                "opacity": 0
            },fadeTime, "quartEaseOut", function(){
                $(this).attr('src', srcs[index]).animate({
                    "opacity": 1
                },fadeTime, "quartEaseIn")
            })
            if(index >= clientsImgs_l-1){
                index=0;
            }else{
                index++;
            }
        }
        setInterval(doClientsLogosAnimation, 8000);
    }
});


var current_page = 1;
$(function(){
    $('.viewType a').click(function(e){
        e.preventDefault();
        if($(this).is('.active')) return;
        var type = $(this).attr('href').replace('#', '');
        if(type == 'list'){
            setCookie('prlt', 5, 7);
        }else if(type == 'grid'){
            setCookie('prlt', 3, 7);
        }
        window.location.reload()

    });
});

/* projects list grid animations and etc... */
$(function(){
    var opacityTime = 250;
    $('.portfolioElement a').live('click', function(e){
        e.preventDefault();
        var pid = $(this).attr('href').replace('#', ''); //picture num
        var li_portfolio = $('.portfolio_page_'+current_page);
        if(li_portfolio.length > 0){
            
            var old_big = li_portfolio.find('.mainWorkmainImg');
            var new_big = li_portfolio.find('.projectSphoto_'+pid);
            var old_small = li_portfolio.find('.mainWorklistImg');
            var new_small = li_portfolio.find('.projectLphoto_'+pid);

            var tmp_old_big = old_big.attr('src');
            var tmp_old_small = old_small.attr('src');

            new_small.fadeOut(opacityTime+2);
            old_big.fadeOut(opacityTime, function(){

                /* change photos */
                old_big.attr('src', new_big.attr('src'));
                old_small.attr('src', new_small.attr('src'));
                new_big.attr('src', tmp_old_big);
                new_small.attr('src', tmp_old_small);

                old_big.fadeIn(opacityTime);
                new_small.fadeIn(opacityTime);
            });
        }
    });
});

$(function(){
    var paginga = $('.pagging a');
    if(paginga.length == 0) {
        return;
    }

    var projectsSlider = $('#projectsSlider');
    var back = $('.pagging a.back');
    var next = $('.pagging a.next');
    //var current_page = 1; added this as super global
    var total_pages = (paginga.length / 2) - 2;
    var ttime = 400;
    var hwidth = 960; //css constant DO NOT CHANGE
    var preload_cpage = 2;
    var preload_counter = 20; //max pages and ajax requests
    var preloadTimer;
    var grid_layout = ($('.portfolio').length == 0) ? false : true;

    projectsSlider.css('width', hwidth*total_pages + 'px');

    var i = 0;
    setTimeout(function(){
        if(i == preload_counter){
            clearInterval(preloadTimer);
        }
        preloadTimer = setInterval(preloadProject, 200);
        i++;
    }, 100);

    paginga.live('click', function(e){
        e.preventDefault();
        if($(this).is('.disabled')) return;

        var pid = parseInt($(this).attr('href').replace('#', ''));
        if(pid > 0 && pid != current_page){
            var params = {};

            if(pid > current_page){
                params.action = 'next';
            }else if(pid < current_page){
                params.action = 'prev';
            }
            params.page = pid;
            params.pre_page = current_page;
            do_animation(params);

            /* manage back and next buttons */
            if(pid > 1){
                back.addClass('backActive');
                back.attr('href', '#'+(pid-1));
            }
            if(pid < total_pages){
                next.addClass('nextActive');
                next.attr('href', '#'+(pid+1));
            }
            if(pid == 1){
                back.removeClass('backActive');
            }
            if(pid == total_pages){
                next.removeClass('nextActive');
            }
            /* ; manage back and next buttons */
            $('.pgc_'+current_page).removeClass('active');
            $('.pgc_'+pid).addClass('active');
            current_page = pid;
        }
    });

    function preloadProject(){

        if(preload_cpage <= total_pages){
            var pos = preload_cpage-1;
            $.ajax({
                type: "POST",
                url: "modules/Products/aaction.php",
                data: {
                    pid: preload_cpage,
                    grid: grid_layout
                },
                dataType: 'json',
                async: false,
                success:function(data){
                    if(data['status'] == 3){
                        projectsSlider.find('li.lpg_'+pos).after('<li class="lpg_'+preload_cpage+'" style="float:left;">'+data['html']+'</li>');
                        $('a.pgc_'+preload_cpage).removeClass('disabled');
                        preload_cpage++;
                    }else if(data['status'] == 0){}
                },
                error:function(){
                    clearInterval(preloadTimer);
                }
            });
        }else{
            next.addClass('nextActive');
            next.removeClass('disabled');
            clearInterval(preloadTimer);
        }
    }

    function do_animation(params){

        var page_diff = page_diffrence(params);
        var px = page_diff * hwidth;

        if(params['action'] == 'next'){
            px = '-='+px+'px';
        }else if(params['action'] == 'prev'){
            px = '+='+px+'px';
        }
        projectsSlider.animate({
            left: px
        }, ttime);
    }

    function page_diffrence(params){
        var pages = new Array(params['page'], params['pre_page']);
        pages = pages.sort();
        return pages[1] - pages[0];
    }

});


/* some helper function */
function getCookie(c_name){
    if (document.cookie.length>0)
    {
        c_start=document.cookie.indexOf(c_name + "=");
        if (c_start!=-1)
        {
            c_start=c_start + c_name.length+1;
            c_end=document.cookie.indexOf(";",c_start);
            if (c_end==-1) c_end=document.cookie.length;
            return unescape(document.cookie.substring(c_start,c_end));
        }
    }
    return "";
}

function setCookie(c_name,value,expiredays){
    var exdate=new Date();
    exdate.setDate(exdate.getDate()+expiredays);
    document.cookie=c_name+ "=" +escape(value)+
    ((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
}

function log(mssg){
    if(typeof console == 'undefined'){
        return true;
    }else{
        console.log(mssg);
        return true;
    }
}


/* -------------- */

$('document').ready(function(){

    $('a[target="_blank"]').addClass('dif');
    var en = $('#map').is('.map_en');

    /* google maps - starts */

    function showMap() {
		var zoom_val = (en) ? 6 : 15;
        var myOptions = {
            zoom: zoom_val,
            center: new google.maps.LatLng(55.724403,21.127052),
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            scrollwheel: false
        }
        var map = new google.maps.Map(document.getElementById("map"), myOptions);

        setMarkers(map, offices);
    }

    var offices = [
    ['UAB "EMTN"', 55.724403,21.127052, 1]
    ];

    function setMarkers(map, locations) {
        var image = new google.maps.MarkerImage('images/icon.png',
            // This marker is 20 pixels wide by 32 pixels tall.
            new google.maps.Size(42, 51),
            // The origin for this image is 0,0.
            new google.maps.Point(0,0),
            // The anchor for this image is the base of the flagpole at 0,32.
            new google.maps.Point(10, 51));

        for (var i = 0; i < locations.length; i++) {
            var office = locations[i];
            var myLatLng = new google.maps.LatLng(office[1], office[2]);
            var marker = new google.maps.Marker({
                position: myLatLng,
                map: map,
                icon: image,
                title: office[0],
                zIndex: office[3]
            });
        }
    }

    if($('#map').length > 0){
        showMap();
    }

    /* google maps - starts */

    /* lightbox - starts */
    if($.browser.msie && $.browser.version < 7){
        e=$("body").height();
        $("div.black_overlay").css("height", e );
    }

    $("div.popupHeaderClose a").click(function() {
        $("div.white_content").css("display","none");
        $("div.black_overlay").css("display","none");
        return false;
    });

    /* lightbox - ends */


    /* mindaugas */
    $('.menuElement a.parent').click(function(e){
        e.preventDefault();
    });

    /* menu - starts */
    $("div#nav > ul > li").hover(
        function () {
            $(this).addClass("hover");
        },
        function () {
            $(this).removeClass("hover");
        }
        );
	
    /* menu - ends */

    /* promo - starts */

    promo_height=$("div.promo div.ecommerceAnalysis").height();
    $("div.promo div.ecommerceAnalysis div.ecommerceAnalysisLink").css("height", promo_height+32);
	
    /* promo - ends */
	
    /* works hover - starts */
    var title_black = 24;
    var title2_purple = -24;
    if($.browser.msie && $.browser.version < 8){
        title_black = 27;
    }
    if($.browser.msie && $.browser.version < 7){
        title2_purple = 140;
    }
    $("div.oneWork").hover(
        function () {
            $(".title", this).animate({
                "bottom": "-30px"
            },{
                queue:false,
                duration:300,
                easing:"quartEaseIn"
            });
			
            if($.browser.msie && $.browser.version < 7){
                e=140-parseInt($(".title2", this).height());
                $(".title2", this).animate({
                    "top": e+"px"
                    },{
                    queue:false,
                    duration:300,
                    easing:"quartEaseIn"
                });
            }else{
                e=24+parseInt($(".title2", this).height());
                $(".title2", this).animate({
                    "top": "-"+e+"px"
                    },{
                    queue:false,
                    duration:300,
                    easing:"quartEaseIn"
                });
            }
			
        },
        function () {
            $(".title", this).animate({
                "bottom": title_black+"px"
                },{
                queue:false,
                duration:300,
                easing:"quintEaseOut"
            });
            $(".title2", this).animate({
                "top": title2_purple+"px"
                },{
                queue:false,
                duration:300,
                easing:"quintEaseOut"
            });
        }
        );
	
    /* works hover - ends */

    /* view type - starts */
	
    $("div#content div.viewType a").hover(
        function () {
            if($(this).hasClass('active')){
                return;
            }else{
                $(this).parent().parent().addClass("hover");
            }
        },
        function () {
            if($(this).hasClass('active')){
                return;
            }else{
                $(this).parent().parent().removeClass("hover");
            }
        }
        );
	
    /* view type - ends */
	
    /* pagging - starts */
	
    pagging_width=$("div.paggingHolder").width();
    pagging_width=Math.round((260-pagging_width)/2);
    $("div.paggingHolder div.pagging").css("margin-left", pagging_width);
	
    /* pagging - ends */
	
    /* formos laukai - starts */
	
    $('div.contactsForm input[type="text"]').focus(function() {
        $(this).addClass("focusField");
        if (this.value == this.defaultValue){
            this.value = '';
        }
        if(this.value != this.defaultValue){
            this.select();
        }
    });
    $('div.contactsForm input[type="text"]').blur(function() {
        if ($.trim(this.value) == ''){
            this.value = (this.defaultValue ? this.defaultValue : '');
            $(this).removeClass("focusField");
        }
    });
	
    $('div.contactsForm textarea').focus(function() {
        $(this).addClass("focusField");
        if (this.value == this.defaultValue){
            this.value = '';
        }
        if(this.value != this.defaultValue){
            this.select();
        }
    });
    $('div.contactsForm textarea').blur(function() {
        if ($.trim(this.value) == ''){
            this.value = (this.defaultValue ? this.defaultValue : '');
            $(this).removeClass("focusField");
        }
    });
    
    /* spam filter */
    var abc = $('div.contactsForm input[name="abc"]');
    if(abc.length > 0){
		$('div.contactsForm input').keyup(function(){
			abc.val('abc13');
		});
	}
    

/* formos laukai - sends */	

//----------------------------------------------------------------------------------------------------------------------------------	
	
});

function load() {
    if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map"));
  
        point = new GLatLng(55.694616,21.141944);
        map.setCenter(point, 16);

        var myIcon = new GIcon(G_DEFAULT_ICON);
        myIcon.image = "images/ico_map.png";
        myIcon.shadow = "none";
        myIcon.iconSize = new GSize(70, 71);
 
        myIcon.iconAnchor = new GPoint(35, 71);

        // Set up our GMarkerOptions object
        markerOptions = {
            icon:myIcon
        };
       
        marker = new GMarker(point, markerOptions);
        map.addOverlay(marker);

        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());

    }
}


$('a[rel~="external"]').click(function(){$(this).attr({"target":"_blank"});});


