var DD_belatedPNG = null;
var _bgimg, _bgimg2;
var backgrounds = [ '2', '3' ];
var caseNav = false;
var countval = 153728329823;
var ctrinterval, lasthref, ctr, bgWaitStart, currBg;

setBackgroundImage();

var firstrun = true;
$(function () {
    $.fx.interval = 32;
    if (!firstrun) return false;
    firstrun = false;
    if ($('#ticker-wrapper').length > 0) slider = new sliderClass("#ticker-wrapper", "li");
    $(window).bind("resize", resizeBg);
    $('ul#tabs li a').click(showPanel);
    $('div#caselogin').click(caseLoginPanel);
    $('div#caseloginpanel input[type="image"]').click(caseLoginCheck);
    $('a#caseloginreset').click(caseLoginReset);
    $('#casepassword').bind('keypress', function (e) {
        if (e.keyCode == 13)  caseLoginCheck();
    });

    $('div.videobutton').click(playVideo);
    $('html.js body.cases div#curentcases.panel div.case div.headbar').live('click', function (ev) {
        ev.preventDefault();
        loadCase("" + $(this).find('a.caseinfo').attr('href'));
    });
    $('a.caseinfo').live('click', function (ev) {
        ev.preventDefault();
        //loadCase(""+$(this).attr('href'));
    });
    $('div#caseholder a.back_left').live('click', function () {
        setTimeout(function () {
            if (caseNav) {
                hideCase();
            } else {
                window.history.back();
            }
        }, 20);
        return false;
    });
    $(window).keyup(function (e) {
        try {
            if (e.keyCode == 27) {
                clearPopups();
                e.preventDefault();
            }
        } catch (err) {
        }
    });

    $('.statuscta').hover(
        function (ev) {
            var tt = ttc($(this).next('.statusdesc').html(), $(this).offset().left + 85, $(this).offset().top - 18, 280);
            $(this).data('ttid', tt.id);

        },
        function (ev) {
            ev.preventDefault();
            var id = $(this).data('ttid');
            if (id.length == 0) return;
            tta[id].el.fadeOut('fast', function () {
                $(this).remove();
            });
            tta[id] = null;
            $(this).data('ttid', '');
        }
    );


    sidebar = $("#sidebar");
    sidebar_oh = sidebar.parent().outerHeight();
    if (sidebar.length == 1) {
        sidebartop = sidebar.offset().top;
        $(window).scroll(function () {
            var newtop = ($(window).scrollTop() ) - 320;
            if (newtop > sidebar_oh) return;
            if (newtop < 0) {
                sidebar.css({"position":"absolute"});
            } else {
                sidebar.css({"position":"fixed", 'top':24 });
            }
        });
    }

    $(document).on('click', '.bio_expand', function () {
        $(this).hide().next('.bio_rest').show();

    });
    $(document).on('click', '.bio_contract', function () {
        $(this).parent().hide().prev('.bio_expand').show();
    });

    deadlines_init();

});

var sidebar_oh;
var sidebartop = 0;
var sidebar = null;
var dl_count = 0;
var dl_curr = 0;
var dl_items = [];

function deadlines_init() {
    $('div.deadline').each(function () {
        dl_items.push($(this));
        dl_count++;
    });
    if (dl_count > 1) {
        deadlines_swap();
        timers.addInterval('deadlines', deadlines_swap, 5000);
    } else {
        if (dl_count == 1) dl_items[0].fadeIn(300);
    }
}
function deadlines_swap() {

    var lastdl = dl_curr;
    if (++dl_curr >= dl_count) dl_curr = 0;
    var len = 400;
    dl_items[lastdl].fadeOut(len);
    dl_items[dl_curr].delay(len).fadeIn(len);


}


function clearPopups() {
    if ($('#videocloak').is(':visible')) exitVideo();
}

function incCounter() {
    countval += Math.round(Math.random() * 200);
    ctr.text("$" + countval.toString().replace(/(\d)(?=(\d\d\d)+$)/g, "$1,"));
}


function setBackgroundImage() {
    currBg = rndel(backgrounds);
    if ($('body').hasClass('questionnaire')) currBg = '4';
    bgWaitStart = (new Date()).getTime();
    _bgimg = new Image();
    $('div.background.top').append(_bgimg);
    $(_bgimg).hide();
    if ($('body').not('.default')) {
        _bgimg2 = new Image();
        _bgimg2.src = '/images/bg/' + currBg + '_low.jpg';
        _bgimg2.timer = setInterval(bgLoaded, 100, _bgimg2);
        $(_bgimg2).hide();
        $('div.background.bottom').append(_bgimg2);
    }
    _bgimg.src = '/images/bg/' + currBg + '_low.jpg';
    _bgimg.timer = setInterval(function () {
        bgLoaded(_bgimg);
    }, 100);
    bgLoaded(_bgimg);
    bgLoaded(_bgimg2);
}

function bgLoaded(_o) {
    if (_o == null) return;
    if (_o.complete) {
        clearInterval(_o.timer)
    } else {
        return;
    }
    _o.onload = null;
    bgWaitEnd = (new Date()).getTime();
    resizeBg(0);
    _o.src = '/images/bg/' + currBg + '.jpg';
    if (bgWaitEnd - bgWaitStart > 1000) {
        $(_o).fadeIn();
    } else {
        $(_o).show();
    }
}


function resizeBg() {
    var _css, _w, _h, _mw, _mh;
    var _ww = $(window).width();
    var _wh = $(window).height();
    $("div#main, div#main_wrapper").css('min-height', _wh - 312 - 169);
    var _iw = $(_bgimg).width();
    var _ih = $(_bgimg).height();
    var hr = _wh / _ih;
    var wr = _ww / _iw;
    _w = ((wr > hr) ? _iw * wr : _iw * hr);
    _h = ((wr > hr) ? _ih * wr : _ih * hr);
    _css = { width:_w, height:_h };
    $(_bgimg).css(_css);
    _css.marginTop = "-312px";
    if (!$('body').hasClass('default')) $(_bgimg2).css(_css);
}

function rndel(X) {
    return X[Math.floor(Math.random() * X.length)];
}

function showPanel() {
    $(this).parent().addClass('active');
    $(this).parent().siblings().removeClass('active');
    var panel = $(this).attr('data-panel');
    panel = $('div#' + panel);
    panel.siblings().hide();
    panel.show();
    return false;
}
function caseLoginPanel() {
    var clp = $("#caseloginpanel");
    if (clp.is(":visible")) {
        $("#caseloginpanel").hide();
        $(this).removeClass('active');

    } else {
        $(this).addClass('active');
        $("#caseloginpanel").slideDown(200);
        $("#casepassword").focus();
    }
}
function caseLoginCheck() {
    var clp = $("#caseloginpanel");
    var pass = $('#casepassword').val();
    $.ajax({
        url:"/php/caseLoginCheck.php",
        data:{'password':pass},
        cache:false,
        dataType:"text",
        success:caseLoginResult
    });
}
function caseLoginResult(data) {
    if (data != 0) {
        var ts = (new Date()).now;

        $.postGo(data, {"_ts":ts});
    } else {
        var clp = $("#caseloginpanel");
        clp.children('.step1').hide();
        clp.children('.step2').show();
    }
}
function caseLoginReset(ev) {
    ev.preventDefault();
    var clp = $("#caseloginpanel");
    $('#casepassword').val("");
    clp.children('.step2').hide();
    clp.children('.step1').show();
}


function loadCase(caseurl) {
    caseNav = true;
    //var oloc = document.location.
    //if(oloc.indexOf("#")>-1) { oloc = oloc.split('#')[0]; }
    window.location.hash = "#" + caseurl.split('cases/')[1];
    var _url = caseurl;
    $.ajax({
        type:'POST',
        url:_url,
        data:{ajax:1},
        success:showCase,
        error:function (data, m, msg) {
            alert(msg + "\n" + _url);
        }
    });
}

function showCase(data) {
    $('div#container div#main div#panels div.panel.active').fadeOut('fast');

    var casediv = $(data);
    //casediv.hide();
    casediv.children('.casepage').fadeOut(10);
    $('div#container div#main div#panels').prepend(casediv);
    casediv.children('.casepage').fadeIn('fast');
}
function hideCase(data) {
    $('div#caseholder').fadeOut('fast', function () {
        $(this).remove();
        $('div#container div#main div#panels div.panel.active').show();
    });

    //casediv.fadeIn('fast');
}


function formSubmit() {

    var options = {
        //  target:		 '#output',	  // target element(s) to be updated with server response
        url:'php/submitEmail.php',
        beforeSubmit:function () {
        },
        success:function (data, statusText) {
            $("#sending").fadeOut('fast');

            if (data == 1) {
                $('#success').fadeIn("slow");
                $('#contactForm').resetForm();
            }
            else {
                $("#contactForm").fadeIn('fast');
                $('#badinput').fadeIn();
                if (data.indexOf(2) > -1) {
                    $('#badserver').fadeIn("slow");
                }
                if (data.indexOf(3) > -1) {
                    $('#bademail').fadeIn("slow");
                    $('#email').css("background-color", "#ffffdd");
                }
                if (data.indexOf(4) > -1) {
                    $('#badfirstname').fadeIn("slow");
                    $('#txtFirstName').css("background-color", "#ffffdd");
                }
                if (data.indexOf(5) > -1) {
                    $('#badsubject').fadeIn("slow");
                }
                if (data.indexOf(6) > -1) {
                    $('#badcomment').fadeIn("slow");
                    $('#txtComments').css("background-color", "#ffffdd");
                }
            }

        }
    };


    $("#badserver,#bademail,#badfirstname,#badsubject,#badcomment,#badinput").hide();
    $("#contactForm input").css('backgroundColor', '#ffffff')

    $("#contactForm").ajaxSubmit(options);
    $("#contactForm").fadeOut('fast');
    $("#sending").show();

    return false;
}


/* SWITCHER VIDEO */
var videoshowing = false;
function playVideo() {
    videoshowing = true;
    var me = $(this);
    var videoloc = "../" + me.attr('data-video');
    var randid = "vid" + (new Date()).getTime();
    // build the cloak / video area
    var altcontent = 'FLASH PLAYER IS REQUIRED TO VIEW THIS CONTENT.<br><a target="_blank" href="http://www.adobe.com/go/getflashplayer"><img src="/images/fpr.jpg" width="158" height="39" border=0></a>';
    var videodiv = $('<div id="videocloak"><div class="cloakbackground"></div><div class="videohold"><div class="videodiv" id="' + randid + '"><p id="fpr">' + altcontent + '</p></div><div class="exit"></div></div></div>');
    videodiv.children().hide();
    $("body").append(videodiv);
    if (DD_belatedPNG != null) DD_belatedPNG.fix('div.exit');
    // build the swfobject, call showVideo once the swf is loaded
    var flashvars = { video:videoloc, autoStart:true };
    var params = { wmode:'transparent'  };
    var attributes = {};
    swfobject.embedSWF("/swf/HomepageVideoPlayer.swf", randid, "640", "360", "10.0.0", null, flashvars, params, attributes, showVideo);
}

var cloakbackground = null;
var videoanimoffset = 16; // top offset when animating the video in or out
function showVideo() {
    if (slider != null)slider.stop();
    // show the video area, these are all animation steps
    var videodiv = $('div#videocloak');
    var vh = $('div#videocloak div.videohold');
    cloakbackground = videodiv.find('div.cloakbackground');
    $('div.cloakbackground, div#videocloak div.exit').click(exitVideo);
    cloakbackground.animate({opacity:0}, {duration:0, queue:false});
    videodiv.find('div.exit').hide();
    cloakbackground.show();
    setTimeout(function () {
        cloakbackground.animate({opacity:0.8}, {duration:100, queue:false})
    }, 0);
    setTimeout(function () {
        vh.fadeIn();
        $('div.exit').show();
        $('#videodiv *').css({filter:'none'});
    }, 300);
}
function videoDone() {
    exitVideo();
}
function exitVideo() {
    if (slider != null)slider.start();
    videoshowing = false;
    // hide the video area
    var vh = $('div.videohold');
    $('div#videocloak div.exit').fadeOut(200, function () {
        vh.animate({opacity:0, top:vh.position().top + videoanimoffset}, {duration:200, queue:false});
        setTimeout(function () {
            $('div.cloakbackground').fadeOut(500, function () {
                $('div#videocloak').remove();
            })
        }, 200);
    });
}

function isArray(obj) {
    if (obj.constructor.toString().indexOf("Array") == -1)
        return false;
    else
        return true;
}


(function ($) {
    $.extend({
        getGo:function (url, params) {
            document.location = url + '?' + $.param(params);
        },
        postGo:function (url, params) {
            var $form = $("<form>");
            $form.attr("method", "post")
            $form.attr("action", url);
            $.each(params, function (name, value) {
                var $in = $("<input type='hidden'>");
                $in.attr("name", name);
                $in.attr("value", value);
                $in.appendTo($form);
            });
            $form.appendTo("body");
            $form.submit();
        }
    });


})(jQuery);


var timers = {
    coll:{},
    methods:{
        clear:{
            i:function ($ref) {
                return clearInterval($ref);
            },
            t:function ($ref) {
                return clearTimeout($ref);
            }
        },
        start:{
            i:function ($func, $delay, $args) {
                return setInterval($func, $delay, $args);
            },
            t:function ($func, $delay, $args) {
                return setTimeout($func, $delay, $args);
            }
        }
    },
    addInterval:function ($id, $func, $timeout) {
        timers.add('i', $id, $func, $timeout);
        timers.start($id);
    },
    addTimeout:function ($id, $func, $timeout) {
        timers.add('t', $id, $func, $timeout);
        timers.start($id);

    },
    add:function ($type, $id, $func, $time) {
        if (timers.coll[$id] != null) throw "Timer '" + $id + "' exists!";
        timers.coll[$id] = { type:$type, ref:null, func:$func, delay:$time};

    },
    clearAll:function () {
        for (var t in timers.coll) timers.clear(t);
    },
    startAll:function () {
        for (var t in timers.coll) timers.clear(t);
        for (var t in timers.coll) timers.start(t);
    },
    clear:function ($id) {
        if (timers.coll[$id] == null) return;
        var t = timers.coll[$id];
        timers.methods.clear[t.type].apply(this, [t.ref]);
    },
    start:function ($id) {

        if (timers.coll[$id] == null) return;
        timers.clear($id);
        var t = timers.coll[$id];
        t.ref = timers.methods.start[t.type].apply(this, [t.func, t.delay]);
    }
};
var isIE = (navigator.appName == "Microsoft Internet Explorer");
$(function () {
    if (isIE) {
        $(document).bind('onfocusin', timers.startAll);
        $(document).bind('onfocusout', timers.clearAll);
    } else {
        $(window).bind('focus', timers.startAll);
        $(window).bind('blur', timers.clearAll);
    }
});

