// initialisations
var timer;
var incomplete_request_callback=false;
$(document).ready(function(){
   //if($('object').length>0){
    //$('object').append('<param name="wmode" value="transparent" />');
  // }
});
$.fn.clearInputs = function(clear_hidden)  
{  
    return this.each(function()  
    {  
        var obj = $(this);  
          
        $(obj).find(':input').each(function()  
        {  
            switch(this.type)  
            {  
                case 'password':  
                case 'select-multiple':  
                case 'select-one':  
                case 'text':  
                case 'textarea':  
                    $(this).val('');  
                    break;  
                case 'checkbox':  
                case 'radio':  
                    this.checked = false;  
                    break;  
                case 'hidden':  
                    if (clear_hidden)  
                        $(this).val('');  
                    break;  
            }  
        });  
   });    
}
function doneAjax(response, callback){ 
    //After Ajax Executes
     if(response.loggedIn===false){ 
         incomplete_request=true;
         setTimeout("show_status_bar('It appears your session has ended. Please log in to continue.')", 1000); 
         login_popup(); 
         if(typeof(callback)!='undefined'){
             incomplete_request_callback=function(){ callback(); };             
         }
         $('#loading_gif').hide();
         return false; 
         
     }else if(response.loggedIn=='access'){
         remove_modal_window();
         hide_status_bar();
         create_modal_window('It appears you do not have permission to access this. Try <a href="logout.php">logging out</a>, then in again.');
         $('#loading_gif').hide();
         return false;
     }     
     
}

function login(refresh){    
    
    show_status_bar('Verifying log in information, please wait...');
    $.post("authenticate.php", $('#login').serialize(), function(response){               
        if (response.success === true){                       
            if(refresh==true){                  
                    if(response.redirect===false){
                        window.location='./';
                    }else{
                        window.location=response.redirect;//$('#redirect').val();     
                    }
                   
               }else{                    
                   show_status_bar('Success - Thank you');
                   if(incomplete_request_callback!=false){
                        //call the function that was interupted                        
                        incomplete_request_callback();                            
                        incomplete_request_callback=false;
                    }     
                   remove_modal_window();            
                   setTimeout("hide_status_bar()", 3000);
               }
           }else{
              hide_status_bar(show_status_bar(response.msg));    
           }     
    });
}


//shows a custom statusbar
//callback is optional
function show_status_bar(message, callback)
{
    hide_status_bar(function()
    {
        // add element to the dom
        $('body').append('<div id="status-bar">' + message + '</div>');
        $('#status-bar').slideDown("slow", function ()
        {
            // run optional callback
            if (callback)
            {
                callback();
            }
        });
    });
    setTimeout("hide_status_bar()", 15000);
}

//removes a status message of given name, if exists
//callback is optional
function hide_status_bar(callback)
{
    // if there is something to hide then hide it
    if ($('#status-bar').length > 0)
    {
        $('#status-bar').slideUp("fast", function ()
        {
            $('#status-bar').remove();
            
            // run optional callback
            if (callback)
            {
                callback();
            }
        });
    }
    // otherwise just do the callback
    else
    {
        // run optional callback
        if (callback)
        {
            callback();
        }
    }
}

// iterates through json array errors and highlights inputs + appends error text in the next cell to the right 
function show_errors(errors)
{
    // hide errors just in case they weren't already
    hide_errors();
    
    // loop through each returned error and handle it
    $.each(errors, function(element, error_text)
    {    
        // the other error means that something bigger than data validation has gone wrong. don't display other errors
        if (element == 'other')
        {
            show_status_bar(error_text);
            return false;
        }
        else
        {
            // add the error-input class to the bad input
            $('#' + element).addClass('error-input');
            
            // add the error message in the cell next to the input
            $('#' + element).parent().append('<p class="error-text" style="display: none">' + error_text + '</p>');
                        
        }
    });
    
    
    // scroll up to the first error if it's out of view
    if ($('.error-input:first').length != 0 && !is_in_view('.error-input:first'))
    {
        $('html, body').animate({scrollTop: $(".error-input:first").offset().top - 50 }, 700, function(){ 
            //focus cursor on item
            $(".error-input:first").focus(); 
            // show the error-texts
            $('.error-text').slideDown('slow');
    
        });
    }
}


// hides all error texts and unhighlights all error inputs
function hide_errors()
{
    // remove any error-input classes that may exist
    $('.error-input').removeClass('error-input');
    
    // hide any error texts that may exist
    $('.error-text').slideUp("fast", function ()
    {
        // remove the error-texts
        $('.error-text').remove();
    });
}

// creates a modal background and modal window
// callback is optional
function create_modal_window(contents, callback)
{
    // add modal background and modal window
    $('body').append('<div id="modal-background"></div><div id="modal-window">' + contents + '</div>');
        
    // fade the modal background
    $('#modal-background').fadeIn(300,function ()
    {
        // center modal window 
        $('#modal-window').css("left", $('#modal-background').outerWidth() / 2 - ($('#modal-window').outerWidth() / 2));
        $('#modal-window').css("top", $('#modal-background').outerHeight() / 2 - ($('#modal-window').outerHeight() / 2));
        $('#modal-window').draggable();
        // slide in the modal window
        $('#modal-window').show(0, function()
        {
            if (callback)
            {
                callback();
            }            
        });
    });
}
// removes the modal background and window
// callback is optional
function remove_modal_window(callback)
{
    // hide the modal window
    $('#modal-window').hide(0, function()
    {
        // fade away the modal background
        $('#modal-background').hide(0, function()
        {
            // remove the modal window and background
            $('#modal-window').remove();
            $('#modal-background').remove();
            
            // run optional callback
            if (callback)
            {
                callback();
            }
        });
    });
}

// redirects after a specified interval
function timed_redirect(seconds, where, element)
{
    // do the following every second
    timer = setInterval(function()
    {
        // update the text of element if given an element
        if (element)
        {
            $(element).text(seconds);
        }
        
        // if we reach 0 stop the timer and redirect
        if (seconds == 0)
        {
            clearInterval(timer);
            window.location = where;
        }
        
        // count down by 1
        seconds--;
        
    }, 1000);
}

// cancels the redirect timer
function cancel_timed_redirect()
{
    clearInterval(timer);
}

// checks if an item is out of view due to scrolling
function is_in_view(element)
{
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elementTop = $(element).offset().top;
    var elementBottom = elementTop + $(element).height();

    return ((elementBottom > docViewTop) && (elementTop < docViewBottom));
}

// limits the # of characters on an input. 
(function($){ 
    $.fn.extend({  
        limit: function(limit,element)
        {    
            var interval, f;
            var self = $(this);
                    
            $(this).focus(function(){
                interval = window.setInterval(substring,100);
            });
            
            $(this).blur(function(){
                clearInterval(interval);
                substring();
            });
            
            substringFunction = "function substring(){ var val = $(self).val();var length = val.length;if(length > limit){$(self).val($(self).val().substring(0,limit));}";
            if(typeof element != 'undefined')
                substringFunction += "if($(element).html() != limit-length){$(element).html((limit-length<=0)?'0':limit-length);}"
                
            substringFunction += "}";
            
            eval(substringFunction);
            
            substring();
       } 
   }); 
})(jQuery);

$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};


function get_html_translation_table (table, quote_style) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: noname
    // +   bugfixed by: Alex
    // +   bugfixed by: Marco
    // +   bugfixed by: madipta
    // +   improved by: KELAN
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Frank Forte
    // +   bugfixed by: T.Wild
    // +      input by: Ratheous
    // %          note: It has been decided that we're not going to add global
    // %          note: dependencies to php.js, meaning the constants are not
    // %          note: real constants, but strings instead. Integers are also supported if someone
    // %          note: chooses to create the constants themselves.
    // *     example 1: get_html_translation_table('HTML_SPECIALCHARS');
    // *     returns 1: {'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}
    
    var entities = {}, hash_map = {}, decimal = 0, symbol = '';
    var constMappingTable = {}, constMappingQuoteStyle = {};
    var useTable = {}, useQuoteStyle = {};
    
    // Translate arguments
    constMappingTable[0]      = 'HTML_SPECIALCHARS';
    constMappingTable[1]      = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';

    useTable       = !isNaN(table) ? constMappingTable[table] : table ? table.toUpperCase() : 'HTML_SPECIALCHARS';
    useQuoteStyle = !isNaN(quote_style) ? constMappingQuoteStyle[quote_style] : quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT';

    if (useTable !== 'HTML_SPECIALCHARS' && useTable !== 'HTML_ENTITIES') {
        throw new Error("Table: "+useTable+' not supported');
        // return false;
    }

    entities['38'] = '&amp;';
    if (useTable === 'HTML_ENTITIES') {
        entities['160'] = '&nbsp;';
        entities['161'] = '&iexcl;';
        entities['162'] = '&cent;';
        entities['163'] = '&pound;';
        entities['164'] = '&curren;';
        entities['165'] = '&yen;';
        entities['166'] = '&brvbar;';
        entities['167'] = '&sect;';
        entities['168'] = '&uml;';
        entities['169'] = '&copy;';
        entities['170'] = '&ordf;';
        entities['171'] = '&laquo;';
        entities['172'] = '&not;';
        entities['173'] = '&shy;';
        entities['174'] = '&reg;';
        entities['175'] = '&macr;';
        entities['176'] = '&deg;';
        entities['177'] = '&plusmn;';
        entities['178'] = '&sup2;';
        entities['179'] = '&sup3;';
        entities['180'] = '&acute;';
        entities['181'] = '&micro;';
        entities['182'] = '&para;';
        entities['183'] = '&middot;';
        entities['184'] = '&cedil;';
        entities['185'] = '&sup1;';
        entities['186'] = '&ordm;';
        entities['187'] = '&raquo;';
        entities['188'] = '&frac14;';
        entities['189'] = '&frac12;';
        entities['190'] = '&frac34;';
        entities['191'] = '&iquest;';
        entities['192'] = '&Agrave;';
        entities['193'] = '&Aacute;';
        entities['194'] = '&Acirc;';
        entities['195'] = '&Atilde;';
        entities['196'] = '&Auml;';
        entities['197'] = '&Aring;';
        entities['198'] = '&AElig;';
        entities['199'] = '&Ccedil;';
        entities['200'] = '&Egrave;';
        entities['201'] = '&Eacute;';
        entities['202'] = '&Ecirc;';
        entities['203'] = '&Euml;';
        entities['204'] = '&Igrave;';
        entities['205'] = '&Iacute;';
        entities['206'] = '&Icirc;';
        entities['207'] = '&Iuml;';
        entities['208'] = '&ETH;';
        entities['209'] = '&Ntilde;';
        entities['210'] = '&Ograve;';
        entities['211'] = '&Oacute;';
        entities['212'] = '&Ocirc;';
        entities['213'] = '&Otilde;';
        entities['214'] = '&Ouml;';
        entities['215'] = '&times;';
        entities['216'] = '&Oslash;';
        entities['217'] = '&Ugrave;';
        entities['218'] = '&Uacute;';
        entities['219'] = '&Ucirc;';
        entities['220'] = '&Uuml;';
        entities['221'] = '&Yacute;';
        entities['222'] = '&THORN;';
        entities['223'] = '&szlig;';
        entities['224'] = '&agrave;';
        entities['225'] = '&aacute;';
        entities['226'] = '&acirc;';
        entities['227'] = '&atilde;';
        entities['228'] = '&auml;';
        entities['229'] = '&aring;';
        entities['230'] = '&aelig;';
        entities['231'] = '&ccedil;';
        entities['232'] = '&egrave;';
        entities['233'] = '&eacute;';
        entities['234'] = '&ecirc;';
        entities['235'] = '&euml;';
        entities['236'] = '&igrave;';
        entities['237'] = '&iacute;';
        entities['238'] = '&icirc;';
        entities['239'] = '&iuml;';
        entities['240'] = '&eth;';
        entities['241'] = '&ntilde;';
        entities['242'] = '&ograve;';
        entities['243'] = '&oacute;';
        entities['244'] = '&ocirc;';
        entities['245'] = '&otilde;';
        entities['246'] = '&ouml;';
        entities['247'] = '&divide;';
        entities['248'] = '&oslash;';
        entities['249'] = '&ugrave;';
        entities['250'] = '&uacute;';
        entities['251'] = '&ucirc;';
        entities['252'] = '&uuml;';
        entities['253'] = '&yacute;';
        entities['254'] = '&thorn;';
        entities['255'] = '&yuml;';
    }

    if (useQuoteStyle !== 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';
    }
    if (useQuoteStyle === 'ENT_QUOTES') {
        entities['39'] = '&#39;';
    }
    entities['60'] = '&lt;';
    entities['62'] = '&gt;';


    // ascii decimals to real symbols
    for (decimal in entities) {
        symbol = String.fromCharCode(decimal);
        hash_map[symbol] = entities[decimal];
    }
    
    return hash_map;
}

function htmlentities (string, quote_style) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: nobbler
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Ratheous
    // -    depends on: get_html_translation_table
    // *     example 1: htmlentities('Kevin & van Zonneveld');
    // *     returns 1: 'Kevin &amp; van Zonneveld'
    // *     example 2: htmlentities("foo'bar","ENT_QUOTES");
    // *     returns 2: 'foo&#039;bar'

    var hash_map = {}, symbol = '', tmp_str = '', entity = '';
    tmp_str = string.toString();
    
    if (false === (hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style))) {
        return false;
    }
    hash_map["'"] = '&#039;';
    for (symbol in hash_map) {
        entity = hash_map[symbol];
        tmp_str = tmp_str.split(symbol).join(entity);
    }
    
    return tmp_str;
}

function fix_flash() {
    // loop through every embed tag on the site
    var embeds = document.getElementsByTagName('embed');
    for(i=0; i<embeds.length; i++)  {
        embed = embeds[i];
        var new_embed;
        // everything but Firefox & Konqueror
        if(embed.outerHTML) {
            var html = embed.outerHTML;
            // replace an existing wmode parameter
            if(html.match(/wmode\s*=\s*('|")[a-zA-Z]+('|")/i))
                new_embed = html.replace(/wmode\s*=\s*('|")window('|")/i,"wmode='transparent'");
            // add a new wmode parameter
            else
                new_embed = html.replace(/<embed\s/i,"<embed wmode='transparent' ");
            // replace the old embed object with the fixed version
            embed.insertAdjacentHTML('beforeBegin',new_embed);
            embed.parentNode.removeChild(embed);
        } else {
            // cloneNode is buggy in some versions of Safari & Opera, but works fine in FF
            new_embed = embed.cloneNode(true);
            if(!new_embed.getAttribute('wmode') || new_embed.getAttribute('wmode').toLowerCase()=='window')
                new_embed.setAttribute('wmode','transparent');
            embed.parentNode.replaceChild(new_embed,embed);
        }
    }
    // loop through every object tag on the site
    var objects = document.getElementsByTagName('object');
    for(i=0; i<objects.length; i++) {
        object = objects[i];
        var new_object;
        // object is an IE specific tag so we can use outerHTML here
        if(object.outerHTML) {
            var html = object.outerHTML;
            // replace an existing wmode parameter
            if(html.match(/<param\s+name\s*=\s*('|")wmode('|")\s+value\s*=\s*('|")[a-zA-Z]+('|")\s*\/?\>/i))
                new_object = html.replace(/<param\s+name\s*=\s*('|")wmode('|")\s+value\s*=\s*('|")window('|")\s*\/?\>/i,"<param name='wmode' value='transparent' />");
            // add a new wmode parameter
            else
                new_object = html.replace(/<\/object\>/i,"<param name='wmode' value='transparent' />\n</object>");
            // loop through each of the param tags
            var children = object.childNodes;
            for(j=0; j<children.length; j++) {
                if(children[j].getAttribute('name').match(/flashvars/i)) {
                    new_object = new_object.replace(/<param\s+name\s*=\s*('|")flashvars('|")\s+value\s*=\s*('|")[^'"]*('|")\s*\/?\>/i,"<param name='flashvars' value='"+children[j].getAttribute('value')+"' />");
                }
            }
            // replace the old embed object with the fixed versiony
            object.insertAdjacentHTML('beforeBegin',new_object);
            object.parentNode.removeChild(object);
        }
    }
}

$.fn.listHandlers = function(events, outputFunction) {
    return this.each(function(i){
        var elem = this,
            dEvents = $(this).data('events');
        if (!dEvents) {return;}
        $.each(dEvents, function(name, handler){
            if((new RegExp('^(' + (events === '*' ? '.+' : events.replace(',','|').replace(/^on/i,'')) + ')$' ,'i')).test(name)) {
               $.each(handler, function(i,handler){
                   outputFunction(elem, '\n' + i + ': [' + name + '] : ' + handler );
               });
           }
        });
    });
};
