function toggle_tab(tab_id) {
    if(tab_id != ''){
        $("#" + tab_id).addClass('current');
    }
}

/*Note: js below is duplicated with utilities, need to refine later(as we still wait updated UI, so we don't change utilities.js).*/
function showFilmStripLightbox(stripTimeout, lightboxTimeout) {
    if ($('#filmStripContainer').is(':hidden')) {
        showFilmStrip(stripTimeout);
    }
    switchToStripLightbox(lightboxTimeout);
    if (typeof(s) != 'undefined') {
        s.tl(this, 'o', 'lpi : lightbox widget');
    }
}

function switchToStripLightbox(lightboxTimeout) {
    $("#filmStripCart").hide();
    $("#filmStripLightbox").show(lightboxTimeout);
    $("#stripLightboxTab").addClass('current');
    $("#stripCartTab").removeClass('current');
    setCookieOneYearUnderRoot("strip", "lightbox");
}

function showFilmStripCart(stripTimeout, cartTimeout) {
    if ($('#filmStripContainer').is(':hidden')) {
        showFilmStrip(stripTimeout);
    }
    switchToStripCart(cartTimeout);
    if (typeof(s) != 'undefined') {
        s.tl(this, 'o', 'lpi : cart widget');
    }
}

function switchToStripCart(cartTimeout) {
    $("#filmStripCart").show(cartTimeout);
    $("#filmStripLightbox").hide();
    $("#stripCartTab").addClass('current');
    $("#stripLightboxTab").removeClass('current');
    setCookieOneYearUnderRoot("strip", "cart");
}

function hideFilmStrip(timeout) {
    $('#filmStripContainer').fadeOut(timeout);
    $("#filmStripControls p a").removeClass('open').addClass('closed').html('Show');
    setPageWrapHeight(30);
    setCookieOneYearUnderRoot("showFilmStrip", "false");
}

function showFilmStrip(timeout) {
    $('#filmStripContainer').fadeIn(timeout);
    $("#filmStripControls p a").removeClass('closed').addClass('open').html('Hide');
    setPageWrapHeight(236);
    setCookieOneYearUnderRoot("showFilmStrip", "true");
}

function setPageWrapHeight(height) {
    $("#pageWrap").css("bottom", height + "px");
    if (isIE()) {
        adjustHeightForIE(height);
    }
}

var showingNum = 0;
var mousePosX;
var mousePosY;

function showAddConfirmation() {
    var offset_left = -5;
    var offset_top = 45;
    $('#addConfirmation').css('left', mousePosX + offset_left + 'px');
    $('#addConfirmation').css('top', mousePosY - offset_top + 'px');
    $("#addConfirmation").show();
    showingNum++;
    $(this).delay(3000, function() {
        if (showingNum == 1) {
            $("#addConfirmation").hide();
        }
        showingNum--;
    });
}

function isIE() {
    return $.browser.msie
}

function adjustHeightForIE(height) {
    $("#pageWrap").css("height", ($(window).height() - height) + "px");
}

function setCookieOneYearUnderRoot(c_name, value) {
    setCookie(c_name, value, 365, "/");
}

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

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

function getUrlParameter(name)
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function showPopupMessage(caption, url, height, width) {
    var options = {
        center_win: true,
        caption: caption,
        height: height || 500,
        width: width || 500,
        fullscreen: false,
        show_loading: true
    }
    var win = new GB_Window(options);
    return win.show(url);
}

function enableButton(elementId, enabled) {
    if (enabled)
    {
        $('#' + elementId).removeAttr('disabled');
        $('#' + elementId).attr('class', 'submitBtn');
    }
    else
    {
        $('#' + elementId).attr('disabled', true);
        $('#' + elementId).attr('class', 'disabled');
    }
}

function go_back() {
    var previousUrl = document.referrer
    if (previousUrl.match("^http[s]?://" + window.location.host) != null) {
        window.location.href = previousUrl;
    } else {
        window.location.href = "/search";
    }
}

function limit_textarea_input() {
    $("textarea[maxlength]").bind('input propertychange', function() {
        var maxLength = $(this).attr('maxlength');
        if ($(this).val().length > maxLength) {
            $(this).val($(this).val().substring(0, maxLength));
        }
    })
}

function limit_money_input() {
    $("input.money").bind("contextmenu", function() {
        return false;
    });

    $("input.money").css('ime-mode', 'disabled');

    $("input.money").bind("keydown", function(e) {
        var key = window.event ? e.keyCode : e.which;
        if (isFullStop(key)) {
            return $(this).val().indexOf('.') < 0;
        }
        return (isSpecialKey(key)) || ((isNumber(key) && !e.shiftKey));
    });
}

function isNumber(key) {
    return (key >= 48 && key <= 57) || (key >= 96 && key <= 105)
}

function isSpecialKey(key) {
    //8:backspace; 46:delete; 37-40:arrows; 36:home; 35:end; 9:tab; 13:enter
    return key == 8 || key == 46 || (key >= 37 && key <= 40) || key == 35 || key == 36 || key == 9 || key == 13
}

function isFullStop(key) {
    return key == 190 || key == 110;
}

function setupDatePicker(options) {
    $('.datepicker').attr('readonly', true);
    var default_options = {dateFormat: 'dd/mm/yy', showOn: 'button', buttonImageOnly: true, buttonImage: '/images/calendar.gif', buttonText: 'Please select a date'}
    if (options != null) {
        default_options = $.extend(default_options, options);
    }
    $('.datepicker').datepick(default_options);
}

function selectIEHack(selectId, fixedWidth) {
    if ($.browser.msie) {
        $("#" + selectId).mousedown(function() {
            $(this).css("width", "auto");
        });

        $("#" + selectId).change(function() {
            $(this).css("width", fixedWidth);
        });
    }
}


function commonTemplate(item) {
  return "<option value='" + item.Value + "'>" + item.Text + "</option>";
}

function commonMatch(selectedValue) {
  return this.When == selectedValue;
}

function cascade(parent_selector, children_selector, parent_children_list, fn) {
  $(children_selector).cascade(parent_selector, {
    list: parent_children_list,
    template: commonTemplate,
    match: commonMatch
  }).bind("loaded.cascade", ( fn==null ? function(e, parent) {} : fn ) );
};

function updateExcludedWords()
{
    var excludedWordsId = '#excluded_keywords';

    if ($.trim($('#exact_phrase').val()).length > 0 || $.trim($('#included_keywords').val()).length > 0) {
        $(excludedWordsId).attr("disabled", false);
    }
    else
    {
        $(excludedWordsId).attr("disabled", true);
        $(excludedWordsId).val('');
    }
}

function refreshWithParameter(name, value) {
    var reg = new RegExp(name + "=([^\\&]+)", "g");
    var currentLocation = window.location.href;
    var newLocation;
    var param = name + "=" + value;

    if (currentLocation.match(reg)) {
        newLocation = currentLocation.replace(reg, (param));
    }
    else {
        if (currentLocation.indexOf('?') == -1) {
            newLocation = currentLocation + '?' + param;
        } else {
            newLocation = currentLocation + '&' + param;
        }
    }

    window.location.href = newLocation;
}

function getNextImageUrl(image_id){
    var image = getImageId(image_id, 1)
    verifyPagingButtonsVisibility(image)
    return createImageUrl(image);
}

function getPrevImageUrl(image_id){
    var image = getImageId(image_id, -1)
    verifyPagingButtonsVisibility(image)
    return createImageUrl(image);
}

function createImageUrl(image){
    if(image){
        return '/images/' + image + '?group=' + getUrlParameter('group')
    }else{
        return window.location.href
    }
}

function getImageId(image_id, offset){
    var images = getImageIds();
    if(!images) return null;

    var img_index = findImageArrayIndex(images, image_id) + offset;

    return images[img_index];
}

function getImageIds(){
    var search_id = getUrlParameter('group');
    if(search_id == '') return null;

    if(!getCookie(search_id)) return null;
    var images = getCookie(search_id).split('+');
    return images;
}


function verifyPagingButtonsVisibility(image_id){
    var images = getImageIds();
    if(!images){
        displayNextButton(false);
        displayPrevButton(false)
    }

    if(image_id == images[0]) displayPrevButton(false);
    if(image_id == images[images.length-1]) displayNextButton(false);
}

function findImageArrayIndex(images, element){
    for(var i=0; i < images.length; i++ ){
        if(images[i] == element){
            return verifyIndex(i, images.length - 1);
        }
    }
    return null;
}

function verifyIndex(index, max_size){
    if(index < 0 ) index = 0;
    if(index > max_size) index = max_size;

    return index;
}

function displayNextButton(display){
    var show = '';
    if (!display) show = 'none';
    document.getElementById('btnNextSearchResult').style.display = show;
}

function displayPrevButton(display){
    var show = '';
    if (display==false) show = 'none';
    document.getElementById('btnPrevSearchResult').style.display = show;
}


//############ Hide Show ########################
$(function() {
    $(".showAdvanced").show();
    $(".showAdvanced").click(function() {
        var $this = $(this);
        if ($this.is('.closed')) {
            $("#searchBlock #simpleSearch").hide();
            $("#searchBlock .theHiddenContent").show();
            $this.removeClass('closed');
            $this.addClass('reveal');
            $('.showAdvanced a span').html('Hide a');

        }
        else {
            $("#searchBlock .theHiddenContent").hide();
            $("#searchBlock #simpleSearch").show();
            $this.removeClass('reveal');
            $this.addClass('closed');
            $('.showAdvanced a span').html('A');
        }
        return false;
    });

    $(".showImageHistory").show();
    $(".showImageHistory").click(function() {
        var $this = $(this);
        if ($this.is('.closed')) {
            $(".theHiddenContent").slideDown('500');
            $this.removeClass('closed');
            $this.addClass('reveal');
            $('.showImageHistory a').html('Licence history');

        }
        else {
            $(".theHiddenContent").slideUp('500');
            $this.removeClass('reveal');
            $this.addClass('closed');
            $('.showImageHistory a').html('Licence history');
        }
        return false;
    });

    $(".showLightBox").show();

    function showAddToLightboxForm() {
        $('.theHiddenLightbox').fadeIn('500');
        $('.showLightBox').removeClass('closed').addClass('revealLightBox');
        $('.showLightBox a span').html('Add to lightbox');
        $('#newLightbox').val('Create a new lightbox');
        $('#existingLightbox').val('Select a lightbox');
        $('#existingLightboxRadio').attr('checked', 'checked');
    }

    function hideAddToLightboxForm(instant) {
        if (instant === true) {
            $('.theHiddenLightbox').hide();
        } else {
            $('.theHiddenLightbox').fadeOut('500');
        }
        $('.showLightBox').removeClass('revealLightBox').addClass('closed');
        $('.showLightBox a span').html('cancel');
    }

    $('#cancelAddToLightbox').click(hideAddToLightboxForm);

    $('#existingLightbox').click(function() {
        $('#existingLightboxRadio').attr('checked', 'checked');
        $('#newLightbox').val('Create a new lightbox');
    });

    $('#newLightbox').click(function() {
        $('#newLightboxRadio').attr('checked', 'checked');
        $('#existingLightbox').val('Select a lightbox');
        $(this).val('');
    });

});

// ############ IE HOVER ########################

$(function() {
    $('#tabs li, .tableContainer tr').hover(function() {
        $(this).addClass('ieHover');
    }, function() {
        $(this).removeClass('ieHover');
    });

});

function generateTooltip(selector) {
    $(selector + "[tool_tip_title != '']").each(function() {
        $(this).attr('title', $(this).attr('tool_tip_title'));
        $(this).removeAttr('tool_tip_title');
    });
    $(selector + "[title != '']").tooltip({
        track: true,
        delay: 350,
        showURL: false,
        fixPNG: true,
        top: -5,
        left: 15,
        fade:200
    });
}

$(function() {
    generateTooltip(".showTip");
    generateTooltip(".showImageTip img");
});

// ############ DRAW CONTROLS ########################
$(function() {

    var theTrigger = $("#filmStripControls p a");
    var theFilmStrip = $('#filmStripContainer');

    $("#filmStripControls p a").click(function() {
        var theFilmStrip = $('#filmStripContainer');

        if (theFilmStrip.is(':hidden'))
        {
            showFilmStrip(500);
        }
        else
        {
            hideFilmStrip(500);
        }
        return false;
    });


    $("#filmStripControls li a").click(function() {
        var theTab = $(this);
        if (theTab.is('.lightbox')) {
            showFilmStripLightbox(0, 50);
        }
        if (theTab.is('.cart')) {
            showFilmStripCart(0, 50);
        }
        return false;
    });

});


// ############ BUTTON HOVER ########################
$(function() {
    $('button').hover(function() {
        $(this).addClass('ieHover');
    }, function() {
        $(this).removeClass('ieHover');
    });

});


// ############ Whole <TR> is clickable link ###########
$(function() {
    $('.tableContainer.wholeRowIsLink tr').each(function() {
        var tr = $(this);
        var href = tr.find('a').attr('href');
        tr.find('td').click(function() {
            document.location.href = href;
        });
        tr.find('.toolbar').click(function() {
            //Stop propagation if user clicks on button - don't redirect to edit page in this case.
            return false;
        });
    });
});

// ############ Popup messages ###########
function popupWarning(msg) {
    showPopupBack();
    $('#flashMessage').show().find('.warning').show().find('.head p').html(msg);
}

function popupWarningWithCallback(msg, func) {
    showPopupBack();
    $('#flashMessage').show().find('.warning').show().find('.head p').html(msg);

    $('#warning_close_button').click(function() {
        $('#warning_close_button').unbind('click');
        hidePopupBack();
        func(false);
        $('#warning_close_button').click(function() {
            hidePopupBack();
        });
    });
}

function hidePopupWarning() {
    $('#flashMessage_popupMessage_warning').hide();
    $('#flashMessage').hide();
    hidePopupBack();
}

function popupConfirmation(msg, func, params, with_yesno_button) {
    showPopupBack();
    showFlashMessageConfirmationWithMessage(msg, with_yesno_button);

    var ok_button_id = 'confirmation_ok_button';
    var yes_button_id = 'confirmation_yes_button';
    var no_button_id = 'confirmation_no_button';
    var cancel_button_id = 'confirmation_cancel_button';
    var button_ids = [ok_button_id, yes_button_id, no_button_id, cancel_button_id];

    $('#' + ok_button_id).click(function() {
        confirmation_button_click(button_ids, true, func, params);
    });
    $('#' + yes_button_id).click(function() {
        confirmation_button_click(button_ids, true, func, params);
    });
    $('#' + no_button_id).click(function() {
        confirmation_button_click(button_ids, false, func, params);
    });
    $('#' + cancel_button_id).click(function() {
        confirmation_button_click(button_ids, false, function(do_nothing) {
        });
    });
}

function showFlashMessageConfirmationWithMessage(msg, with_yesno_button) {
    if (with_yesno_button) {
        $('#confirmation_ok_div').hide();
        $('#confirmation_yes_no_div').show();
    } else { // false or undefined
        $('#confirmation_ok_div').show();
        $('#confirmation_yes_no_div').hide();
    }
    $('#flashMessage').show().find('.confirmation').show().find('.head p').html(msg);
}

function confirmation_button_click(button_ids, do_action, func, params) {
    unbind_all(button_ids);
    func(do_action, params);
    hidePopupConfirmation();
}

function unbind_all(button_ids) {
    var index;
    for (index in button_ids) {
        $('#' + button_ids[index]).unbind('click');
    }
}

function hidePopupConfirmation() {
    $('#flashMessage_confimation').hide();
    $('#flashMessage').hide();
    hidePopupBack();
}


function showPopupBack() {
    $('#flash_message_back').show();
    $('#flash_message_back').bgIframe();
}

function hidePopupBack() {
    $('#flash_message_back').hide();
}

function refresh() {
    window.top.location.href = window.top.location.href;
}