$(document).ready(function(){
    $(".jButton").button();
    $(".editaccordion").accordion({collapsible:true, active:false, autoHeight:false});
    $('.lightBox').lightBox();

    $.validator.addMethod('noForwardSlash',function (value,element){
        if (value.search("/") != -1){
            return false;
        }
        return true;
    },'No forwards slashes please');

    $.validator.addMethod('youTubeOrNothing',function(value){
        var valid = false;
        var matches = '';
        if (value == ''){
            return true;
        }
        matches = value.match(/[https?:\/\/]?[^\/]*\.]?youtube\.com\/watch\?v=([\w-_]*)[^&?.*]*/gi); // old pattern (https?:\/\/)?([^\/]*\.)?youtube\.com\/watch\?v=([\w-_]*)&(.*)*
        if (matches != null){
            valid = true;
        }
        matches = '';
        matches = value.match(/(?:https?:\/\/)?youtu.be\/([\w-_]*)/gi);
        if (matches != null) {
            valid = true
        }
        return valid;
    },'Not a Valid Youtube URL');

    $.validator.addMethod('requireIfFile',function(value,element){
       var fileInput = $(element).attr('file');
       if ($('input[name='+fileInput+']').val() == ''){
           return true;
       }
       var matches = value.match(/[\w ]*/gi);
       if (matches[0] == value){
           return true;
       }
       return false;
    },'Please give a filename if you include a file');

    $.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;
    };

    $.fn.scrollTo = function(topOffSet){
        if (typeof(topOffSet) == 'undefined'){
            topOffSet = 0;
        }
        var target = $(this);
        if (target.length == 0) return;
        $('html, body').animate({
            scrollTop: target.offset().top - topOffSet
        }, 1000);
    };
    
    $('#fscreen').click(function(){
       if ($(this).hasClass('noexit')) return;
       fadeScreen(false);
    });
    
    $.fn.toggleText = function (value1, value2) {
        return this.each(function () {
            var $this = $(this),
                text = $this.text();

            if (text.indexOf(value1) > -1)
                $this.text(text.replace(value1, value2));
            else
                $this.text(text.replace(value2, value1));
        });
    };

});

function error(text,callback){
    var output = '<div class="ui-state-error ui-corner-all" style="padding: 0.7em;z-index:1000000"><span class="ui-icon ui-icon-alert" style="float:left;margin-right: 0.3em;"></span><strong>Alert:</strong><br /><br />' + text + '</div>';
    $('<div><div>').html(output).dialog({
        title : 'Error Message',
        buttons : {
            "Ok" : function (){
                $(this).dialog('close');
                if (typeof(callback) == 'function'){
                    callback.call();
                }
            }
        }
    });
    
}

function message(text,callback){
    var output = '<div class="ui-state-highlight ui-corner-all" style="padding: 0.7em;z-index:1000000"><span class="ui-icon ui-icon-info" style="float:left;margin-right: 0.3em;"></span><strong>Alert:</strong><br /><br />' + text + '</div>';
    $('<div><div>').html(output).dialog({
        title : 'Information Message',
        buttons : {
            "Ok" : function (){
                $(this).dialog('close');
                if (typeof(callback) == 'function'){
                    callback.call();
                }
            }
        }
    });
}

function fadeScreen(hide){
        var showState = $('#fscreen').is(':visible');
        if (typeof(hide) == 'undefined'){
            hide = showState;
        }
        if (hide){
            $("#fscreen").fadeTo("normal",0, function(){
                    $(this).hide();
            });
        }
        else {
            $("#fscreen").fadeTo("normal",0.9);
        }
}

function setCookie(cookieName, value, expireDays){
    var expireDate = new Date();
    expireDate.setDate(expireDate.getDate() + expireDays);
    var cookieValue = escape(value) + ((expireDays==null) ? "" : "; expires="+expireDate.toUTCString());
    document.cookie = cookieName + '=' + cookieValue;
}

function getCookie(cookieName){
    var x,y,cookies = document.cookie.split(';');
    for (var i = 0; i< cookies.length; i++){
        x = cookies[i].substr(0,cookies[i].indexOf('='));
        y = cookies[i].substr(cookies[i].indexOf('=')+1);
        x = x.replace(/^\s+|\s+$/g,'');
        if (x == cookieName){
            if (unescape(y) == '') return false;
            return unescape(y);
        }
    }
    return false;
}

(function ($) {
    $.formPost = function (callerSettings){
        var settings = $.extend({
           url : location.href,
           target : 'formPostIframe',
           data : {},
           title : '',
           width : 640,
           height : 900
        }, callerSettings || {});
        if ($('#formPostIframe').length == 0){
            $('<iframe>').attr('id','formPostIframe')
                         .attr('name','formPostIframe')
                         .hide()
                         .appendTo($('body'))
        }
            
        var form = $('<form>').attr('method','post')
                              .attr('action',settings.url)
                              .attr('target',settings.target)
                              .hide()
                              .appendTo($('body'));
        
                              
        $.each(settings.data,function(index, value){
            if (value == '') return;
            $('<input>').attr('type','hidden')
                        .attr('name',index)
                        .val(value)
                        .appendTo(form);
        });
        
        if (settings.target == 'newWindow'){
            window.open('','_form',"width =" + settings.width + ",height=" + settings.height + ",status=no,resizable=yes,scrollbars=yes");
            form.attr('target','_form');
        } 
        form.submit();
        
    }
})(jQuery);

(function ($) {
    $.jsonPost = function(callerSettings){
        var settings = $.extend({
            async : true,
            url : absUrl + 'ajax',
            data : {},
            type : 'post',
            dataType : 'json',
            error : function(){
                error('ajax error');
            },
            callback : function(json){
                console.log(json);
            }
        }, callerSettings || {});
        
        settings.success = function (json){
            if (json == null) {
                console.log('no data returned');
                return;
            }
            if (json.logout) {
                location.href = absUrl
            }
            settings.callback.call(this,json);
        }
        
        $.ajax(settings);
    }
})(jQuery);

(function($){
    var settings;
    
    $.fn.popup = function(callerSettings){
        var settings = $.extend({
            width: '640px',
            height: '480px',
            marginTop: '20px',
            url : false,
            fade : true,
            action : 'open',
            close : null //we can specify a callback here.
        }, callerSettings || {});
        if (typeof settings.close == 'function'){
            if (typeof window.samurai == 'undefined') window.samurai = new Object();
            if (typeof window.samurai.popup == 'undefined') window.samurai.popup = new Object();
            window.samurai.popup.close = settings.close;
        }
        
        var closeButton = $('<div>');
        var myDiv = $(this);
        var blackScreen = $('#blackScreen');
        if (blackScreen.length != 1){
            blackScreen =  $('<div>').attr('id','blackScreen')
                                     .css('background-color','#111')
                                     .css('height','1000%')
                                     .css('position','absolute')
                                     .css('width','100%')
                                     .css('z-index','999')
                                     .css('opacity','0')
                                     .css('display','none')
                                     .prependTo($('body'))
                                     .click(function(){
                                         myDiv.popup({action:'close'});
                                     });
        }
        if (settings.action == 'open'){
            blackScreen.fadeTo("normal",0.9);
            closeButton.addClass('popupClose')
                       .html('&#x2718;')
                       .css('width','40px')
                       .css('height','40px')
                       .css('position','absolute')
                       .css('right','-20px')
                       .css('top','-20px')
                       .css('border','15px solid black')
                       .css('border-radius','40px')
                       .css('-moz-border-radius','40px')
                       .css('-webkit-border-radius','40px')
                       .css('color','black')
                       .css('text-align','center')
                       .css('line-height','40px')
                       .css('font-weight','bold')
                       .css('font-size','32px')
                       .css('background','white')
                       .css('cursor','pointer')
                       .css('z-index','1000')
                       .click(function(){
                            myDiv.popup({action:'close'});
                        });
            myDiv.css('width',settings.width)
                 .css('height',settings.height)
                 .css('position','fixed')
                 .css('background','white')
                 .css('z-index','1001')
                 .css('border','15px solid black')
                 .css('border-radius','10px')
                 .css('-moz-border-radius','10px')
                 .css('-webkit-border-radius','10px')
                 .css('margin-top',settings.marginTop)
                 .css('margin-left','-' + parseInt(settings.width)/2 + 'px')
                 .css('left','50%')
                 .show()
                 .prepend(closeButton)
                 .prependTo($('body'));
            
        }
        if (settings.action == 'close'){
            blackScreen.hide();
            myDiv.hide();
            if (!window.samurai) window.samurai = new Object();
            if (!window.samurai.popup) window.samurai.popup = new Object();
            if (!window.samurai.popup.close) window.samurai.popup.close = '';
            if (typeof window.samurai.popup.close == 'function'){
                window.samurai.popup.close.call(this);
            }
        }
        return $(this);
    }
        
})(jQuery);


function log(obj1,obj2,obj3,obj4){
    if (typeof console.log == 'Object') console.log(log);
}

function isInt(x) {
    var y=parseInt(x);
    if (isNaN(y)) return false;
    return x==y && x.toString()==y.toString();
} 
