
var bool_StopCycle = false;

$(document).ready(function()
{    
    jQuery_Homepage_Cycle(1, 0);

    $(window).resize(function() {
        jQuery_Setup_HomepageResize();
        jQuery_ContentCentre();
        jQuery_ContactCentre();
        jQuery_Setup_MenuResize();
    });

    jQuery_Setup_VideoLink();
    jQuery_Setup_VideoHover();
    jQuery_Setup_Search();
    jQuery_Setup_NewsHover();
    jQuery_Setup_MenuHover()
    jQuery_Setup_AboutHover();
    jQuery_Setup_MenuResize();
    jQuery_ContactCentre();
});

var arr_FancyBoxSettings = {
    'autoScale' : false,
    'autoCentre': false,
    'transitionIn': 'none',
    'transitionOut': 'none',
    'padding' : 0,
    'margin' : 0,
    'width' : 640,
    'overlayOpacity' : 0.8,
    'overlayColor' : '#333333',
    'autoDimensions' : true,
    'onStart'   : jQuery_Homepage_Stop, // stop the homepage cycling on opening
    'onClosed' : jQuery_Homepage_Start // restart it on closed
};

var arr_FancyBoxSettings_Upload = {
    'autoScale' : false,
    'autoCentre': false,
    'transitionIn': 'none',
    'transitionOut': 'none',
    'padding' : 0,
    'margin' : 0,
    'width' : 640,
    'height' : 220,
    'overlayOpacity' : 0.8,
    'overlayColor' : '#333333',
    'autoDimensions' : false
};

function jQuery_Tweet_Contact()
{
    $(".tweet").tweet({
        username: "absolute_post",
        join_text: "auto",
        avatar_size: 32,
        count: 2,
        auto_join_text_default: "",
        auto_join_text_ed: "we",
        auto_join_text_ing: "we were",
        auto_join_text_reply: "we replied to",
        auto_join_text_url: "we were checking out",
        loading_text: "Loading tweets..."
    });
}

function jQuery_Setup_MenuResize()
{
    if ($(window).width() <= 900)
    {
        $("#search_box input").css("width", $(window).width() / 9);
        $("#search-suggest").css("width", ($(window).width() / 9) - 10);
        if ($(window).width() <= 800)
            $("#bookmarks").hide();

    } else {
        $("#bookmarks").show();
        $("#menu").css("height", 28);
        $("#search_box input").css("width", 190);
        $("#search-suggest").css("width", 180);
    }
}

function jQuery_Setup_Preloader()
{
//    $('img.preload').each(function()
//    {
//       $(this).delay(Math.floor(Math.random()*2000)) .fadeIn(1000);
//    });
//
//    $('img.preload').each(function()
//    {
//        var obj_Image = this;
//        /* Bind the load to every image, just incase */
//        $(this).live('load', function() {
//              if (bool_StopCycle === false)
//               $(obj_Image).delay(Math.floor(Math.random()*2000)) .fadeIn(1000);
//        });
//        $(this).load(function() {
//            if (bool_StopCycle === false)
//               $(obj_Image).delay(Math.floor(Math.random()*2000)) .fadeIn(1000);
//        });
//    });
}

function jQuery_Homepage_Stop()
{
    bool_StopCycle = true;
    $("div#image_cont img,img.preload").hide();
}

function jQuery_Homepage_Start()
{
    $("*[id ^= 'st']").empty().remove();
    bool_StopCycle = false;
    jQuery_Setup_HomepageResize();
    jQuery_Homepage_Cycle(1, 0);
    $("img.preload").show();
}

function jQuery_Setup_Search()
{
    jQuery_Search_Handle("search_suggest", "input#input_searchbox", "/search/suggest", "div#search-suggest", 1);
    jQuery_Search_Handle("search", "input#input_searchbox", "/search", "div#main-container,div#image_cont,div#main-container-960", 0);
}

function jQuery_Search_Handle(str_Timer_Id, str_InputBox, str_URL, str_ResultsContainer, bool_HideOnEmpty)
{
    $(str_InputBox).keyup(function() {
        clearTimeout(jQuery.data(this, "timer_"+str_Timer_Id));
        var ms = 400; //milliseconds
        var val = this.value;
        var wait = setTimeout(function() {
            if (val.length == 0 && bool_HideOnEmpty == 1) {
                // Hide the suggestion box.
                $(str_ResultsContainer).hide();
            } else {
                $(str_InputBox).addClass("searchLoading");

                jQuery.ajax({
                    type	: "POST",
                    cache	: false,
                    url		: str_URL,
                    data	: "queryString="+ encodeURIComponent(val) ,
                    success: function(response) {
                        if(response.length > 0)
                        {
                            $(str_ResultsContainer).html(response).show();
                            $(str_InputBox).removeClass("searchLoading");
                        } else {
                            $(str_ResultsContainer).hide();
                            $(str_InputBox).removeClass("searchLoading");
                        }
                    }
                });
            }
        }, ms);
        jQuery.data(this, "timer_"+str_Timer_Id, wait);
    });
}

function jQuery_Setup_MenuHover()
{
    if((navigator.userAgent.match(/iPad/i)))
    {
        $("#menu ul li").click(function() {
            $("#menu ul li .menu-suggest-container:visible").hide();
            $('.menu-suggest-container', this).show();
        });
    } else {
        $("#menu ul li").hover(function() {
            $('.menu-suggest-container', this).show();
        }, function() {
            $('.menu-suggest-container', this).hide();
        });
    }
}

function jQuery_Homepage_Cycle(int_CountSequence, int_Frame)
{
    if (bool_StopCycle == true)
        return;
    
    var int_fadeIn = 800;

    var int_delay = (int_CountSequence == 1) ? 1000 :
    (((int_CountSequence - 1) % 4 == 0) ? 1000 : 50);

    var int_FrameToHide = (int_Frame <= 4) ?
    ($("div#image_cont").find("img").length) - (4 - int_Frame) : (int_Frame - 4);

    $("img[sequence="+(int_FrameToHide)+"]").css({
        'display':'none'
    });

    $("img[sequence="+int_CountSequence+"]").delay(int_delay).fadeIn(int_fadeIn, function(){

        int_Frame = int_CountSequence;
        int_CountSequence++;

        if (int_CountSequence > $("div#image_cont").find("img").length)
        {
            int_CountSequence = 1;
            int_Frame = 0;
        }

        jQuery_Homepage_Cycle(int_CountSequence, int_Frame);
    });
}

function jQuery_Setup_VideoLink()
{
    $("a.video_ajax_link").livequery("click", function () {
        jQuery_AJAXCall_FancyBox(this.href);
        return false;
    });
}

function jQuery_AJAXCall_FancyBox(str_URL)
{
    $.fancybox.showActivity();
    $.ajax({
        type	: "GET",
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        dataType: "html",
        cache	: false,
        url     : str_URL,
        success: function(data, status) {
            $.fancybox(data, arr_FancyBoxSettings);
        }
    });
}

function jQuery_AJAXCall_Fancybox_POST(str_FormName, str_Action, str_URL)
{
    $(str_FormName).bind(str_Action, function() {
        $.fancybox.showActivity();
        $.ajax({
            type : "POST",
            dataType: "html",
            cache	: false,
            url     : str_URL,
            data	: $(this).serializeArray(),
            success: function(data) {
                jQuery.fancybox(data, arr_FancyBoxSettings_Upload);
            }
        });
        return false;
    });
}

function jQuery_AJAXCall_FileUpload()
{
    jQuery_AJAXCall_Fancybox_POST('form#form_FileUpload', 'submit' ,'/cms/homeupload');
}

function jQuery_Setup_VideoHover()
{
    if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i)))
    {
        $(".video_hover").livequery(function () {
            $(this).click(function() {
                $("#"+$(this).attr('id')+"details").fadeIn('normal');
            });
        });
    } else {

        $(".video_hover").livequery(function () {
            $(this).hover(function() {
                $("#"+$(this).attr('id')+"details").fadeIn('normal');
            }, function() {
                $("#"+$(this).attr('id')+"details").fadeOut('normal');
                $("img", this).fadeIn('normal');
            });
        });
    }
}

function js_RGBtoHex(str_RGB)
{
    var parts = str_RGB.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/) ;
    // parts now should be ["rgb(0, 70, 255", "0", "70", "255"]

    delete (parts[0]);
    for (var i = 1; i <= 3; ++i) {
        parts[i] = parseInt(parts[i]).toString(16);
        if (parts[i].length == 1) parts[i] = '0' + parts[i];
    }
    var hexString = '#'. parts.join(''); // "0070ff"
    alert(hexString);
    return hexString;
}

function jQuery_Setup_NewsHover()
{
    jQuery_Setup_NewsHover_Do("a.news_hover.ldn", "#47C3D2");
    jQuery_Setup_NewsHover_Do("a.news_hover.nyc", "#936FB1");
    jQuery_Setup_NewsHover_Do("a.news_hover.both", "#91D8AE");
}

function jQuery_Setup_NewsHover_Do(str_Field, str_BG)
{
    $(str_Field).livequery(function () {
        $(this).hover(function() {
            $(".date,.context", this).animate({
                color: 'white'
            }, 'fast');
            $(".context", this).animate({
                backgroundColor: str_BG
            }, 'fast');
        }, function() {
            $(".context", this).animate({
                backgroundColor: 'white',
                color: 'black'
            }, 'fast');
            $(".date", this).animate({
                color: str_BG
            }, 'fast');
        });
    });
}

function jQuery_Setup_AboutHover()
{
    jQuery_Setup_AboutHover_Do("a.ldn_hover", "#47C3D2");
    jQuery_Setup_AboutHover_Do("a.nyc_hover", "#936FB1");
}

function jQuery_Setup_AboutHover_Do(str_Field, str_BG)
{
    $(str_Field).livequery(function () {
        $(this).hover(function() {
            $("div", this).animate({
                backgroundColor: str_BG
            }, 'fast');
        }, function() {
            $("div", this).animate({
                backgroundColor: 'white'
            }, 'fast');
        });
    });
}

function jQuery_ContentCentre()
{
    var winWidth = ($(window).width());
    var winHeight = ($(window).height());
    var elHeight = $("#liquidcentre").height();
   
    if (elHeight > winHeight && (winWidth % 240) == 0 )
    {
        winWidth = winWidth - 1;
    }

    var elCount = Math.floor(winWidth/240);
    var myMargin = Math.ceil((winWidth-(elCount*240))/2);
    
    $("#liquidcentre").css({
        'margin-left' : myMargin,
        'width' : (elCount * 240)
    });
}

function jQuery_Setup_HomepageResize()
{
    var winWidth = Math.floor($(window).width()/2);
    var winHeight = Math.floor($(window).height()/2) - ($("#menu").height() / 2);
    $('#top_left,#top_right,#bottom_right,#bottom_left').css({
        'height':winHeight +'px',
        'width':winWidth +'px'
    });
}

function jQuery_Setup_MenuHideShow()
{
    $('#menu').css({
        "bottom": "-"+ $("#menu").outerHeight(true) +"px"
        });
    $('#menu').delay(1000).animate({
        "bottom": 0
    }, 1000);
}

function jQuery_ContactCentre()
{
    
    var winHeight = Math.floor($(window).height() - $("#menu").height() );
    var contactPosition = ((winHeight) - $('.contact-container').height()) / 2  ;

    if (winHeight <= $('.contact-container').height())
        contactPosition = 0;
    
    $('.contact-container').css({
        "top": contactPosition + "px"
    });
}
