var currentPage = null;
var defaultMenu;
var resizeTimer = 500;
var timerId = 0;
var resizeTimer = 100;

//news announcer
var newsList;
var blockList;
var newsHeight;
var newsTop;
var minTop, maxTop;
var newsScrollCfg = {
        step: 2,
        timeout: 30,
        easing: 'easeOutQuad'
};
var dir = {
        UP: 1,
        DOWN: 2
};
var iterations = 0;


$(document).ready(function() {
    $.historyInit(websiteNavigation, "");
    $('a').fixURL();

    //init languages dropdown
    var languages = $('#languages');
    $('#lang-select').hover(
            function(){
                    $(this).addClass('lang-active');
                    $('#languages').show();
            },
            function(){
                    $(this).removeClass('lang-active');
                    $('#languages').hide();
            }
    );

    defaultMenu = $('#nav').html();

    /*News announcer*/
    setTimeout(function(){
            newsList = $('.jcarousel-list');
            blockList = parseInt($('.jcarousel-clip-vertical').height());
            newsHeight = newsList.height();
            newsTop = parseInt(newsList.css('top'));
            minTop = -(newsHeight - blockList);
            maxTop = 0;
    }, 200);

    var scrollTimer;
    var iter;

    $('.jcarousel-next').hover(function(){
            iter = 0;
            scrollTimer = window.setInterval(function() {
                    slideNews(dir.DOWN, iter++);
            }, newsScrollCfg.timeout);
    }, function() {
            iter = 0;
            window.clearInterval(scrollTimer);
            slideNewsBack(dir.DOWN);
    });


    $('.jcarousel-prev').hover(function() {
            iter = 0;
            scrollTimer = window.setInterval(function() {
                    slideNews(dir.UP, iter++);
            }, newsScrollCfg.timeout);
    }, function() {
            iter = 0;
            window.clearInterval(scrollTimer);
            slideNewsBack(dir.UP);
    });
});

function websiteNavigation(hash) {
    identify(arguments);
    var oldPage = currentPage ? currentPage : '';
    currentPage = hash;
    if (currentPage == ''){
        showFrontPage();
    }
    else {
        showStaticPage();
    }
    //show default top menu if not TOP
    base = currentPage.split(".")[0].split('?')[0].split('/')[0];
    if(pages[base]!='Top'){
        if($('#nav').html()!=defaultMenu){
            $('#nav').show().html(defaultMenu);
            $('#breadcrumps').html('');
        }
    }
    else{
       $('#nav').hide();
       $('#breadcrumps').hide();
    }
}

function showFrontPage(){
    $('#main').hide(0, function(){$('#main-frontpage').fadeIn('slow')});
    initBgSlide();
}

function showStaticPage(){
    $("#background").hide();
    $('#background-slideshow img').remove();
    $('#main-frontpage').hide(0, function(){$('#main').show()});
    $("#main").html( "<div style='position: absolute; top: 50%; left: 50%; text-align: center; font-size: 12px;'><img src='images/Progressbar.gif'/></div>" );

    if(currentPage.split('/')[0] == 'shopfinder')
        $("#main").load(addAjax('shopfinder?country='+currentPage.split('/')[1]+'&city='+currentPage.split('/')[2]), "", pageLoaded);
    else
        $("#main").load(addAjax(currentPage.replace("/",".")), "", pageLoaded);

    //PAGE TRACKER!!!
    pageTracker._trackPageview(currentPage.replace("/","."));
}

function pageLoaded(responseText, textStatus, XMLHttpRequest) {
    identify(arguments);
    if(textStatus=='error'){
        $("#main").html( "<div style='position: absolute; top: 50%; width:85%; text-align: center; font-size: 15px; color: #ffffff;'>"+responseText+"</p></div>" );
        exit;
    }
    //forms issues
    $("form.ajaxSubmit").each(function() {
         _initClearOnFocus(jQuery);


        $('input[type=checkbox], input[type=radio]').each(function() {
                if ($(this).attr("checked")) {
                        $(this).parent().addClass('checked');
                }
                if($(this).attr('type') == 'radio') {
                        $(this).click(function() {
                                $(this).parents('form').find('input[type=radio]').each(function() {$(this).parent().removeClass('checked');});
                                if ($(this).attr("checked")) {
                                        $(this).parent().addClass('checked');
                                }
                        });
                }
                else if ($(this).attr('type') == 'checkbox') {
                        $(this).click(function() {
                                if ($(this).attr("checked")) {
                                        $(this).parent().addClass('checked');
                                } else {
                                        $(this).parent().removeClass('checked');
                                }
                        });
                }
        });

        $('.password-replacer input.input-text').focus(function(){
                var input = $(this);
                input.hide();
                input.next().show().focus();
        });

        $(this).find('a.submit').click(function(){
            var form = $(this).parents('form');
            var url = $(this).parents('form').attr("action");
            if(url == '') url = currentPage;

            var params = {};
            form.find('input:not([type=checkbox],[type=radio],[type=submit]), input[type=radio][checked=true], input[type=checkbox][checked=true], select, textarea, input.submitClicked[type=submit]').each( function() {
                    if($(this).attr('title') == $(this).val() ) $(this).val('');
                    if($(this).attr('type') == 'radio' || $(this).attr('type') == 'checkbox') {
                            params[String($(this).attr('name')).trim()] = $(this).attr('value');
                    }
                    else params[String($(this).attr('name')).trim()] = $(this).val();
            });
            if(form.attr('method').toUpperCase() == 'POST'){
                    $("#main").load(addAjax(url), params, pageLoaded);
            }
            else $("#main").load(addAjax(url+'?'+params), "", pageLoaded);

            return false;
        });
    });

    $('#login-popup-btn').click(function(){
        $('#login-popup').fadeIn('slow');
        return false;
    });

    $('#popup-close-button').click(function(){
        $('#login-popup').fadeOut('slow');
        return false;
    });

    $("#main a").fixURL();
}

jQuery.fn.fixURL = function() {
	identify(null, "fixURL");
	$(this).each(function() {
		//do not rewrite links in text content
                if($(this).parents('div').filter(':first').attr('id') == 'content')
                    return;
                var href = $(this).attr("href");
		var base = $('base').attr('href');
                var oldHref = href;
			if (href.indexOf("#") > -1) return;
			if (href.substr(0,6).toLowerCase() == "mailto") return;

			if (href.substr(0,4).toLowerCase() != "http") {
				// remove window.location from href's -- for IE
				href = href.replace(base, '');
				$(this).attr("href", "#"+href);
			}
			else {
			      if(href.replace(base, '') == oldHref) {
			      	if(href.substr(0,5) != 'https') $(this).attr('target', '_blank');
				}
			      else $(this).attr("href", "#"+href.replace(base, '') );
			}
	});
        $(this).unbind('click', noClick);
};

String.prototype.trim = function() {
	identify(null, "string.trim");
	return this.replace(/^\s+|\s+$/g,"");
}

function addAjax(url) {
	if (url.indexOf("?") > -1) {
		return url+"&ajax";
	} else {
		return url+"?ajax";
	}
}

function shopFinderChangeCountry(selCountry) {
	identify(arguments);
	var country = encodeURI(selCountry.replace(" ", "+"));
	var url = currentPage.split('?')[0].split('/')[0]+'/'+country;
	$.historyLoad(url);
}

function shopFinderChangeCity(selCity) {
	identify(arguments);
 	var country = encodeURI($('#shfCountry a:first').html().replace(" ", "+"));
        var city = encodeURI(selCity.replace(" ", "+"));
	var url = currentPage.split('?')[0].split('/')[0]+'/'+country+'/'+city;
	$.historyLoad(url);
}

function initClearOnFocus() { _initClearOnFocus(jQuery); }
function _initClearOnFocus($) {
        function blurr(elem){
                if(!(elem.value) || (elem.value == elem.title)) {
                        elem.value = elem.title;
                        $(elem).removeClass('ClearOnFocus-Active');
                }
        }
        function focuss(elem){
                if(elem.value == elem.title) {
                        elem.value = '';
                        $(elem).addClass('ClearOnFocus-Active');
                }
        }
        var inputClearOnFocus = $('input.ClearOnFocus, textarea.ClearOnFocus');
        inputClearOnFocus.each(function() {
                var input = this;
                blurr(input);
                if (input.value != input.title) $(input).addClass('ClearOnFocus-Active');
                input.prepareForSubmit = function() { focuss(input); };
                $(input).parents('form').submit(function(){ focuss(input); });
        });
        inputClearOnFocus.focus(function() { focuss(this); });
        inputClearOnFocus.blur(function() { blurr(this); });
}

function resizeCarousel() {
        var itemWidth = 242;
        var itemMargin = 61;
        var itemTotalWidth = itemWidth + itemMargin;
        var mainAreaWidth = $('#main').width() - $('#content').width()-10;
        mylog($('#content').width());
        var reminder = mainAreaWidth % itemTotalWidth;
        var itemsCount = (mainAreaWidth - reminder) / itemTotalWidth;
        var containerWidth = itemsCount*itemTotalWidth - itemMargin;
        $('div.jcarousel-container').width(containerWidth);

        var minItemHeight = 390;
        var maxItemHeight = 450;
        var carouseleElements = $('.jcarousel-skin-dyrbergkern-horizontal ul li a.item');
        var carouseleElementsHolders = $('.jcarousel-skin-dyrbergkern-horizontal ul li a.item').parent();
        otherAssetsHeight = $('#header').height() + $("#main h2").height() + $("#main h2").height()
                             + parseInt($("#main h2").css('margin-bottom'),10)
                             + parseInt($('#main').css('padding-bottom'),10);
        carouseleHeight = $('.jcarousel-skin-dyrbergkern-horizontal ul li a.item:first').height();
        allowedHeight = $(window).height() - otherAssetsHeight;

        if (allowedHeight >= maxItemHeight){
            carouseleElements.height(maxItemHeight);
            carouseleElementsHolders.height(maxItemHeight + 5);
        }
        else if (allowedHeight <= minItemHeight){
            carouseleElements.height(minItemHeight);
            carouseleElementsHolders.height(minItemHeight + 5);
        }
        else {
            carouseleElements.height(allowedHeight);
            carouseleElementsHolders.height(allowedHeight + 5);
        }
};

function setcarouselHoverEffect(){
    $('#news-carousel-horizontal a ').hover(
        function(){
                var image = $(this).find('img');
                image.stop().animate({
                        'height':'450px',
                        'top':'0px',
                        'left':'0px'
                });
        },
        function(){
                var image = $(this).find('img');
                image.stop().animate({
                        'height':'550px',
                        'top':'-50px',
                        'left':'-26px'
                });
        }
    );
}

jQuery.fn.mousehold = function(timeout, f, fout) {
        if (timeout && typeof timeout == 'function') {
                fout = f;
                f = timeout;
                timeout = 100;
        }
        if (f && typeof f == 'function') {
                var timer = 0;
                var fireStep = 0;
                return this.each(function() {
                        jQuery(this).mousedown(function() {
                                fireStep = 1;
                                var ctr = 0;
                                var t = this;
                                timer = setInterval(function() {
                                        ctr++;
                                        f.call(t, ctr);
                                        fireStep = 2;
                                }, timeout);
                        })

                        clearMousehold = function() {
                                clearInterval(timer);
                                if (fireStep == 1) {
                                        f.call(this, -1);
                                }
                                if(fireStep > 0) {
                                        if(fout && typeof fout == 'function') {
                                                fout.call(this);
                                        }
                                }
                                fireStep = 0;
                        }

                        jQuery(this).mouseout(clearMousehold);
                        jQuery(this).mouseup(clearMousehold);
                })
        }
}

function MoveNews(i, method, timeout) {
        if(typeof timeout == "undefined") {
                timeout = newsScrollCfg.timeout;
        }
        if(i > maxTop) {
                i = maxTop;
        }
        if(i < minTop) {
                i = minTop;
        }
//					if (newsTop < maxTop && newsTop > minTop) {
                var curTop = parseInt(newsList.css('top'), 10);
                var delta = Math.abs(curTop - i);

                if(delta < 10) {
                        newsList.css('top', i + 'px');
                } else {
                        newsList.stop();
                        newsList.animate( { top: i+'px' }, timeout, method);
                }
//					}
}


function slideNews(direction, iteration, repeated) {
        var remainDist = 0;
        if(iteration != -1) {
                iterations = iteration;
        }
        if(direction == dir.UP) {
                remainDist = -newsTop;
        } else {
                remainDist = -(minTop - newsTop);
        }
        if(remainDist < 1) {
                return;
        }
        var remainPct = (remainDist * 100)/(-minTop);
        var mult = 1;
        /*
        if(remainPct > 95 && iteration <= 5) {
                mult = 1/(remainPct - 95);
        } else if(remainPct < 5 && iteration <= 5) {
                mult = 1/(5 - remainPct);
        } else if(iteration > 10) {
                if(remainPct > 15) {
                        mult = 1.2 * Math.sqrt(('' + iteration).length * 1.025);
                        if(mult > 2.5) {
                                mult = 2.5;
                        }
                }
        }
        */
        var timeout = newsScrollCfg.timeout;
        if(typeof repeated != "undefined" && repeated) {
                mult *= repeated;
                timeout *= repeated;
        }

        var delta = (mult * newsScrollCfg.step).toFixed(0);
        if(delta < 1) {
                delta = 1;
        }
        if(direction == dir.UP) {
                newsTop += 1 * delta;
        } else {
                newsTop -= 1 * delta;
        }

        if(newsTop > maxTop) {
                newsTop = maxTop;
        } else if(newsTop < minTop) {
                newsTop = minTop;
        }

        MoveNews(newsTop, newsScrollCfg.easing, timeout);
};

function slideNewsBack(direction) {
        if(iterations > 10) {
                slideNews(direction, iterations + 1, 30);
        }
};

function notifyIE6() {
	identify(arguments);
	isIE6 = true;
        showBlackOverlay( function() {
                $box = $("<div class='IE6'></div>");
                $('body').prepend($box);
                $box.append( $("<h3>Sorry</h3>") );
                $box.append( $("<p>The interactiveness of this website cannot be fullfilled by the abilities of MS Internet Explorer version 6 or earlier.</p>") );
                $box.append( $("<p>In order to get the full experience of browsing this website, you should upgrade to a newer version or use another browser.</p>") );
                $box.append( $("<p>You can get the latest version of MS Internet Explorer by following <a id='ie'>this link</a></p>") );
                $box.append( $("<p>Or you can check out other browsers if you don't have one yet:<ul id='others'></ul></p>") );
                $ul = $box.find('ul#others');
                $ul.append( $("<li><a id='ff'>Firefox</a></li>") );
                $ul.append( $("<li><a id='ch'>Google Chrome</a></li>") );
                $ul.append( $("<li><a id='op'>Opera</a></li>") );
                $ul.append( $("<li><a id='sa'>Safari</a></li>") );
                //$box.append( $("<p>You can stay and browse this site with your current browser, if you like. Click <a id='close'>here</a> to close this popup</p>") );

                $box.find('#ie').attr('href', "http://www.microsoft.com/windows/internet-explorer/worldwide-sites.aspx");
                $box.find('#ff').attr('href', "http://www.getfirefox.com/");
                $box.find('#ch').attr('href', "http://www.google.com/chrome");
                $box.find('#op').attr('href', "http://www.opera.com/browser/");
                $box.find('#sa').attr('href', "http://www.apple.com/safari/");
                $box.find('#close').attr('href', "#").click( function(){ $('.IE6').hide(1,hideBlackOverlay); } );
        });
}

function showBlackOverlay(listener) {
	identify(arguments);
        $("#BlackOverlay").hide();
	if ($("#BlackOverlay").css("display").toLowerCase() != "block") {
		$("#BlackOverlay").css("opacity", 0).css('left', '0').css('top', '0').css('height', '100%');
		$("#BlackOverlay").css("display", "block");
                $("#BlackOverlay").css('opacity', 0.8);
                $("#BlackOverlay").show(1, function() {
                        try {listener();} catch (e) {}
                });
	} else {
		try {listener();} catch (e) {}
	}
}

function hideBlackOverlay(listener) {
	identify(arguments);
	if ($("#BlackOverlay").css("display").toLowerCase() == "block") {
		$("#BlackOverlay").hide(1, function() {
			try {listener();} catch (e) {}
		});
	} else {
		try {listener();} catch (e) {}
	}
}

function mylog(str) {
	try{ console.log(str); }
	catch(e) { }
}

function identify(obj, name) {
	return false;
	if(obj != null) {
		if(jQuery.browser.msie) mylog(obj.callee.toString().split('(')[0]);
		else mylog(obj.callee.name);
	}
	else mylog(name+"");
}



