// this function will modify the searchButton href attribute on searchButton mouseover
function searchQuery() {
    var q = $('#searchInput').val();
    // q = q.split(" ").join(",").replace(",,", " ").replace(",", " ");
    q = encodeURI(q);
    q = (q == null || q == "") ? "#" : ("/Search?query=" + q);
    $('#searchButton').attr("href", q);
    return true;
}

function stopReturnKey(evt) {
    var evt = (evt) ? evt : ((event) ? event : null);
    var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);

    if ((evt.keyCode == 13) && (node.type == "text")) {
        if (node.id == "searchInput") {
            searchQuery();
            $("#searchButton").click();
        }
        return false;
    }
}
document.onkeypress = stopReturnKey;




/** Function for all the play-mix-links and a-hrefs using class=" mixlink " **/
function returnMixUrl(mixid) {
    var href = location.href.split('#/')[0]; // current address including query and bookmark
    var deeplink = location.href.split('#/')[1];
    href = href.split('?')[0];
    if (deeplink && deeplink.length > 0) {
        deeplink = deeplink.split('?')[0];
        deeplink = "#/" + deeplink;
    } else {
        deeplink = "";
    }
    location.href = href + "?mixid=" + mixid + deeplink;
}




function theRotator() {
    setInterval('autoFlip()', 4500);
}

function autoFlip() {
    //Get the first image
    var current = ($('#campaignContainer li.show') ? $('#campaignContainer li.show') : $('#campaignContainer li:first'));
    //Get next image, when it reaches the end, rotate it back to the first image
    var next = ((current.next().length) ? ((current.next().hasClass('show')) ? $('#campaignContainer li:first') : current.next()) : $('#campaignContainer li:first'));

    flip(next);
}

function flip(active) {
    $(".campaign").fadeTo("medium", 0.0);
    $("#campaignContainer li").removeClass('show');
    $(active).addClass('show');
    $(".show .campaign").fadeTo("medium", 1);
}

$(document).ready(function() {

    $.history.init(ajaxRender);
    $('a').live('click', function() {
        var post_url = $(this).attr('href');
        var classdef = $(this).attr('class');
        

        post_url = post_url.replace("http://" + window.location.hostname, "");
        if (post_url != null) {
            if (post_url.indexOf("#", 0) == -1 && post_url.indexOf("http", 0) == -1 && post_url.indexOf("mailto:", 0) == -1 && classdef.indexOf('mixlink') == -1) {
                $.history.load(post_url);
                return false;
            }
        }

    });

    $("p.changeSize").live('click', function() {
        $(this).parent().toggleClass("open");
        $("#radioMargin").toggleClass("open");
        $('#pane1').jScrollPane();
    });


    $("p.changeSize").live('hover', function() {
        $(this).toggleClass("hover");
    });

    $("#campaignContainer li .campaignPaging").live('click', function(event) {
        $(document).stopTime();
        flip($(this).parent());
        return false;
        //theRotator();
    });

    $(document).everyTime(5000, "flipper", function() {
        autoFlip();
    }, 0);



    // BEGIN AVP
    jQuery(_avp).bind("too_young", function() {
        window.location = "http://www.pernod-ricard.com/en/pages/180/pernod/Corporate-responsibility/Responsible-consumption.html";
    });

    jQuery(_avp).bind("invalid_date", function() {
        alert("Please enter a valid date!");
    });

    jQuery(_avp).bind("drinking_banned", function() {
        alert("Drinking is completely banned in your country!");
    });

    jQuery(_avp).bind("displayed", function() {
        // hide flash
        jQuery("object").hide();
    });

    jQuery(_avp).bind("hidden", function() {
        // Show flash objects 
        jQuery("object").show();
    });

    _avp.init("http://www.absolut.com/avp/AVPService.aspx");

    // END AVP


    $('#spacer').height($('#filter').height());

    initFacebook();
    $('#pane1').jScrollPane();

});

function ajaxRender(post_url) {
    
    $('body').css('cursor', 'wait'); // changes the cursor to a wait symbol
//    if ($.browser.msie) { // if the browser is Internet Explorer
//        // jquery's $.load() function does't work when hash include special characters like едц.
//        post_url = encodeURIComponent(post_url); // removes special characters
//    }
   var post_url2 = post_url;
    
    if (post_url) { // checks that a URL is present

        googleTracking(post_url); //Track each click with Google
        
        if (post_url2.indexOf("?", 0) == -1)
                post_url2 += "?titleOnly=1";
            else
                post_url2 += "&titleOnly=1";

            ajaxPost(post_url2, true);

            if (post_url.indexOf("?", 0) == -1)
                post_url += "?bodyOnly=1";
            else
                post_url += "&bodyOnly=1";

            ajaxPost(post_url, false);       

    } else { // if there is no post_url, i.e. it's the home page
        $('body').css('cursor', 'default'); // put the cursor back to normal
    }

};

function ajaxPost(post_url,title) {
    
    $.ajax({ // start the AJAX request for content
        type: 'POST', // I'm sending it via POST, you can use GET if you're feeling dangerous
        url: post_url, // the URL we are retrieving
        data: null, // in this case we are not sending any data
        success: function(data) { // execute the below if the AJAX goes according to plan
        if (title == false)
                $('#page_content').html(data); // put the data retrieved from the AJAX request into the div container
            else
                //$('head').html(data);             
                document.title = data; // put the data retrieved from the AJAX request into the div container
            $('body').css('cursor', 'default'); // put the cursor back to normal
            
            $('#spacer').height($('#filter').height());

            
            refreshFacebook();   // refresh the facebook api due to reloading content without reloading page. see facebook.js
            scrollTo(0, 0);
            
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) { // execute this if it all goes tits up
            $('body').css('cursor', 'default');
            // alert(textStatus + ": " + errorThrown + "\nfor post_url: " + unescape(post_url));
            return false;
        }
    });

}


// Called for every Ajax navigation (see ajaxPost above)
var pageTracker = null;
function googleTracking(post_url) {
    try {
        // Make sure you use the proper code for specifik tracking version!!! (JW)
        if (pageTracker==null) pageTracker = _gat._getTracker("UA-7131242-4");
        pageTracker._trackPageview(post_url);

    } catch (Error) { }
}

// May be called on object.onClick - all other events that isn't navigation!
function googleClickTrack(category, action) {
    try {
        // Make sure you use the proper code for specifik tracking version!!! (JW)
        if (pageTracker==null) pageTracker = _gat._getTracker("UA-7131242-4");
        pageTracker._trackEvent(category, action); // each call must define category & action

    } catch (Error) { }
}



/** Try to reload the object-tag containing the flashplayer for the mix-player **/
function reloadPlayer(mixid) {
    //alert("reloadPlayer: " + $('music'));
    var p = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="400" height="74"><param name="movie" value="http://www.letsmix.com/content/flash/player/rmbbplayer.1.1.1.swf" /><param name="flashvars" value="mixID=' + mixid + '&format=Site&autoStart=0&skin=DEFAULT" /><object type="application/x-shockwave-flash" data="http://www.letsmix.com/content/flash/player/rmbbplayer.1.1.1.swf" width="400" height="74"><param name="flashvars" value="mixID=' + mixid + '&format=Site&autoStart=0&skin=DEFAULT" /></object></object>';
    $('music').html("p");
}




/* Client-side access to querystring name=value pairs
Version 1.3
28 May 2008
	
License (Simplified BSD):
http://adamv.com/dev/javascript/qslicense.txt
*/
function Querystring(qs) { // optionally pass a querystring to parse
    this.params = {};

    if (qs == null) qs = location.search.substring(1, location.search.length);
    if (qs.length == 0) return;

    // Turn <plus> back to <space>
    // See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
    qs = qs.replace(/\+/g, ' ');
    var args = qs.split('&'); // parse out name/value pairs separated via &

    // split out each name=value pair
    for (var i = 0; i < args.length; i++) {
        var pair = args[i].split('=');
        var name = decodeURIComponent(pair[0]);

        var value = (pair.length == 2)
			? decodeURIComponent(pair[1])
			: name;

        this.params[name] = value;
    }
}

Querystring.prototype.get = function(key, default_) {
    var value = this.params[key];
    return (value != null) ? value : default_;
}

Querystring.prototype.contains = function(key) {
    var value = this.params[key];
    return (value != null);
}

Querystring.prototype.toString = function() {
    var result = "?";
    for (var param in this.params) {
        result += param + "=" + this.params[param] + "&";
    }
    return result.substring(0, result.length - 1);
}

Querystring.prototype.set = function(key, value) {
    this.params[key] = value;
}


function getFlashPlayer() {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        if (window['Object0'] != null) return window['Object0'];
        return document['Object0'];
    }
    else {
        return document['Object1'];
    }
}


function playTrack(seconds) {
    // Track.Timestamp
    var fp = getFlashPlayer();
    var result = fp.setCurrentTimePosition(seconds);
    fp.sendToActionScript("play"); // str = 'play'|'pause'
}

function stopPlayer() {
    var fp = getFlashPlayer();
    fp.sendToActionScript("pause");
}

function getPlayerStatus() {
    var fp = getFlashPlayer();
    return fp.getCurrentPlayerStatus();
}


function getTrack() {
    var fp = getFlashPlayer();
    return fp.getCurrentTimePosition();
}