if ( $.browser.msie ){
    document.execCommand("BackgroundImageCache", false, true);
}

function bind_file_input()
{
    //append class cacheInitial to seperate log in form to allow value swap to work
    $('form.loginForm input').addClass('cacheInitial');
    
    //swap values of inputs dependant on focus and blur
    $.each($('input.cacheInitial'), function() {
        $(this).data('initial',$(this).val());
    });
    $('input.cacheInitial').focus(function() {
        if($(this).val() == $(this).data('initial')) {
            $(this).val('');
        }
    })
    .blur(function() {
        if($(this).val() == '') {
            $(this).val($(this).data('initial'));
        }
    });  
}

$(document).ready(function() {
    
    function on_document_ready()
    {
        var cssURL = "/files/static/css/";
        
        //browser sniffing makes the internet cry - specific style sheets
        if ($.browser.safari){
            $('head').append('<link rel="stylesheet" type="text/css" href="'+cssURL+'base-safari.css" />');
        }
        if ($.browser.opera){
            $('head').append('<link rel="stylesheet" type="text/css" href="'+cssURL+'base-opera.css" />');
        }
    
        // maintain highlighting of parent menu element
        $('div#topNav ul li ul').hover(function() {
            $(this).parent().addClass('hover');
        }, function() {
            $(this).parent().removeClass('hover');
        });
        
        $('#mainContent #header #topNav ul li ul li.subLast').hover(function(){
            $(this).children('a').addClass('hover');
        }, function() {
            $(this).children('a').removeClass('hover');
        });
        
        bind_file_input();
        
        //make external links open in new window without breaking the strict validation
        //$.each($('a[href^="http://"], a.newWindow'), function() {
        //    $(this).attr({'target': "_blank"});
        //    if ($(this).children('img').length == 0 && $(this).css('background-image') == 'none') {
        //        $(this).addClass('externalLink');
        //    }
        //});
    
        //attempt to force PDFs into new window    
        //$.each($('ul.press > li > a'), function(){
        //    $(this).attr({'target': "_blank"});
        //});
        
    
        //initiate FancyBoxes - also see defaults set in the bottom of fancybox/jquery.fancybox-1.2.1.js
        //Tell a Colleague
        if (jQuery.fn.fancybox)
        {
        
            $("a.tellColleague").fancybox({
                'callbackOnShow'        :   make_ajax_handlers('tellColleague', '/tell-a-colleague/'),
                'callbackOnClose'       :   function() {
                    // make sure we're not listening for form submissions still:
                    $('form#tellColleague').unbind('submit');
                }
            });
            
            $("a.sendFeedback").fancybox({
                //'frameHeight'			:	331,
                'callbackOnShow'        :   make_ajax_handlers('sendFeedback', '/send-feedback/'),
                'callbackOnClose'       :   function() {
                    // make sure we're not listening for form submissions still:
                    $('form#sendFeedback').unbind('submit');
                }
            });
        
        }
        $('li a[href^=/dashboard/profile_edit/]').hide();
    }
    //on_document_ready();
    if (running_ie6) {
        setTimeout(on_document_ready, 10);
    } else {
        on_document_ready();
    }
    
});

function make_ajax_handlers(classname, url)
{

    function on_loaded() {        
        /* callback to handle successful load of the tell a colleague box: */
        // set up handler for form submit:
        $('form#'+classname).submit(function(e) {            
            e.preventDefault();
            //$('form#tellColleague button').attr({'disabled':'disabled'}).addClass('disabled');
            // build field values into JSON to send to the server:
            var data = {};
            $(this).find(':input').each(function() {
                var inputName = $(this).attr('name');
                if (inputName != '') {
                    data[inputName] = $(this).val();
                }
            });            
            $.post(url, data, handle_post);
        });
    }
    
    function handle_post(html) {        
        /* callback to handle response from AJAX post for tell a colleague form */        
        $('#fancy_ajax').html(html);
        // if the form has been reloaded, there are errors, so handle this case:
        if ($('#fancy_ajax').find('form').length > 0) {
            on_loaded();
            return null;
        }
        // if the thank you message has been loaded, resize the fancy box to an
        // appropriate height
        if ($('div.thanks').length > 0) {
            $('#fancy_outer').height($('div.thanks').height() + 20 + 'px');
        }
        return null;
    }

    return on_loaded;

}
/*
Common generic routines that should be available for every page
*/

/* ============ Array methods ============ */
function contains(value) {
    /* A.contains(value) -> bool
    
    Return true if value is found in A, false otherwise.
    */
    for (var i=0; i<this.length; i++) {
        if (this[i] == value) {
            return true;
        }
    }
    return false;
}
Array.prototype.contains = contains;

/* ============ String methods ============ */
function join(array) {
    /* S.join(array) -> string
    
    Return a string which is the concatenation of the strings in the
    array.  The separator between elements is S.
    */
    if (typeof(array) !== typeof([])) {
        throw 'array must be iterable';
    }
    if (!array.length) return '';
    var joined = array[0];
    if (array.length==1) return joined;
    for (var item=1; item<array.length; item++) {
        joined += this + array[item];
    }
    return joined;
}

function strip(chars) {
    /* S.strip([chars]) -> string
    
    Return a copy of the string S with leading and trailing
    whitespace removed.
    If chars is given and not None, remove characters in chars instead.
    */
    if (chars === undefined) {
        return this.replace(/^\s+/,'').replace(/\s+$/,'');
    }
    var new_this = this;
    if (new_this.startswith(chars)) {
        new_this = new_this.substr(chars.length);
    }
    if (new_this.endswith(chars)) {
        new_this = new_this.substr(0, new_this.length - chars.length);
    }
    return new_this;
}
String.prototype.strip = strip;
String.prototype.join = join;


String.prototype.f = function(data){
    var template = this.toString();
    var rendered_template = template.replace( /{{\s*(.*?)\s*}}/g, function(m, n) {
        var node = data;
        $.each(n.split('.'), function(i, symbol){
            node = node[symbol] || '';
        });
        return node;

    });

    return rendered_template;
}

