var Menu = { };
var Dialog = { };
var Reports = { };
var User = { };
var Hudl = {
    openDropMenu: function(e, menu, dropFromElement) {
        menu = $(menu);
        var d = $(dropFromElement);
        if (menu.visible()) {
            Hudl.closeDropMenu.call(menu);
        } else {
            if (d) {
                menu.clonePosition(d, { setWidth:false, setHeight:false, offsetTop:d.getHeight() });
            }
            menu.show();
            menu.fire('hudl:open');
            Hudl.registerDropMenu(menu);
        }
        if (e) {
            Event.stop(e);
        }
    },

    registerDropMenu: function(menu) {
        menu = $(menu);
        if (!menu.autoHide) {
            menu.autoHide = Hudl.closeDropMenu.bind(menu);
        }
        document.observe('click', Hudl.closeDropMenu.bindAsEventListener(menu));
    },

    closeDropMenu: function(e) {
            //alert('this.id=' + this.id + ', Event.element(e) == document =' + (Event.element(e).innerHTML));
        if (e && !Object.isElement(e)) {
            var m = Event.element(e).up('#' + this.id);
            //alert('getting m==document = ' + (m == document));
        }
        if ((!m || m == document) && this.autoHide) {
            this.hide();
            this.fire('hudl:close');
            document.stopObserving('click', this.autoHide);
        }
    }
}
var Video = { enteredText:'', totalClips:0, pageSize:100 };
Video.Defaults = { fromIndex:0, toIndex:100 };
Object.extend(Video, Video.Defaults);

if (!window.console) {
    window.console = { log:function() { } };
}

Event.isDescendant = function(e, ancestor) {
    var elem = Event.element(e);
    while (elem && elem !== document) {
        if (elem === ancestor) {
            return true;
        }
        elem = elem.parentNode;
    }
    return false;
}

function Toggle(elem)
{
    if (!elem) return;
    elem = $(elem);
    
    if (!elem.visible()) {
        Event.observe(window, 'resize', ResizeBackground);
        Event.observe(window, 'scroll', ResizeBackground);
        ResizeBackground().show();
	
	    if (Hudl.VP) {
    	    Hudl.VP.enableKeyboardShortcuts('dialog', false);
        }    
        var center = $('a_CenterDiv');
        if (!center) {
            center = document.body;
        }
        elem.setStyle({ 'zIndex':100001, position:'absolute', left:((center.getWidth() - elem.getWidth()) / 2) + 'px', top:'120px', display:'' });
        if (document.viewport.getScrollOffsets().top > 100) {
            Effect.ScrollTo(elem, { duration:0.4, offset:-10 });
        }
        
        if (Dialog.Current) {
            Dialog.Current.fire('hudl:close');
            Dialog.Current.hide();
        }
        Dialog.Current = elem;
        elem.fire('hudl:open');
    } else {
        Event.stopObserving(window, 'resize', ResizeBackground);
        Event.stopObserving(window, 'scroll', ResizeBackground);
        elem.hide();
        $('modalBG').hide();
        elem.fire('hudl:close');
	    if (Hudl.VP) {
	        Hudl.VP.enableKeyboardShortcuts('dialog', true);
	    }
        var prog = $('dialogProgress');
        if (prog) prog.hide();
        Dialog.Current = null;
    }
}

function WriteDebug(msg)
{
    var s = $('status');
    if (s) { s.update(msg); }
}

function Confirm(dialogID, confirmationMessage, confirmedFunc)
{
    var dialog = $(dialogID);
    $('confirmDeleteMsg').update(confirmationMessage);
    var btn = $('deleteButton');
    if (!btn.isBound) {
        btn.isBound = true;
        Event.observe(btn, 'click', function(event) { confirmedFunc(event); Toggle(dialog); });
    }
    Toggle(dialog);
}

function SendError(error, eventName, eventHandler)
{
    var finalError = '';
    var etype = typeof(error);
    if (etype == 'object') {
        if (error.message) {
            finalError = 'Message=' + error.message + ' ';
        } else if (error.get_message) {
            finalError = 'Message=' + error.get_message() + ' ';
        }
        if (error.get_statusCode) {
            finalError += 'StatusCode=' + error.get_statusCode() + ' ';
        }
        if (error.get_exception) {
            finalError += 'Exception=' + error.get_exception() + ' ';
        }
        if (error.stack) {
            finalError += 'Stack=' + error.stack + ' ';
        } else if (error.get_stackTrace) {
            finalError += 'StackTrace=' + error.get_stackTrace() + ' ';
        } else {
            finalError += 'CallStack=' + GetCallStack() + ' ';
        }
        if (error.fileName) {
            finalError += 'File=' + error.fileName + ' ';
        }
        if (error.lineNumber) {
            finalError += 'LineNumber=' + error.lineNumber + ' ';
        }
    } else if (etype == 'string') {
        finalError = error + ' CallStack=' + GetCallStack() + ' ';
    }
    if (eventName) {
        finalError += 'Event=' + eventName + ' ';
    }
    if (eventHandler) {
        finalError += 'EventHandler=' + eventHandler.toString() + ' ';
    }
    var xmlRequest, ex;
    try {
        xmlRequest = new XMLHttpRequest();
    } catch(ex) {
        try {
            xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
        } catch(ex) { }
    }
    if (xmlRequest) {
        xmlRequest.open('GET', '/Services/WebErrorReporter.ashx?error=' + escape(finalError));
        xmlRequest.send(null);
    }
}

function GetCallStack()
{
    var f = GetCallStack.caller;
    if (!f) return '';
    var result = '';
    while ((f = f.caller) != null) {
        result += ParseFuncName(f);
    }
    return result;
}

function ParseFuncName(f)
{
    var line = f.toString().match(/.*/);
    line = line.length == 0 ? '' : line[0];
    var idx = line.indexOf('{');
    return (idx ? line.substring(0, idx) : line);
}

function ToggleDialogProgress(dialogID, bodyID)
{
    var elem = $(dialogID);
    if (!elem) return;
    var body = $(bodyID);
    if (!body) return;
    Dialog.Current.Body = body;

    var size = elem.getDimensions();
    var pos = elem.cumulativeOffset();
    $('dialogProgress').setStyle({ width:size.width + 'px', height:size.height + 'px', left:pos.left + 'px', top:pos.top + 'px' }).show();
    $('modalThrobber').style.marginTop = (size.height < 100 ? '10px' : '50px');
}

function TogglePopup(dlg)
{
    if (dlg) {
        dlg = $(dlg);
        if (dlg.visible()) {
            dlg.hide().fire('hudl:close');
            Menu.Current = null;
        } else {
            if (Menu.Current) {
                Menu.Current.hide().fire('hudl:close');
            }
            Menu.Current = dlg.show();
            dlg.fire('hudl:open');
        }
    } else if (Menu.Current) {
        Menu.Current.hide().fire('hudl:close');
    }
}

function ResizeBackground()
{
    var dim = $(document.body).getDimensions();
    var bg = $('modalBG');
    bg.setStyle({ width:dim.width + 'px', height:dim.height + 'px' });
    if (document.FixBackground) {
        FixBackground(bg);
    }
    
    if (Dialog.Current && Dialog.Current.Body) {
        var pos = Dialog.Current.Body.cumulativeOffset();
        $('dialogProgress').setStyle({ left:pos.left + 'px', top:pos.top + 'px' });
    }
    
    return bg;
}

function CompareTo(s1, s2)
{
    var x1 = s1.toUpperCase(), x2 = s2.toUpperCase();
    for (var j=0; j<x1.length; j++) {
        if (j === x2.length) {
            return 1;
        }
        var c1 = x1.charAt(j);
        var c2 = x2.charAt(j);
        if (c1 === c2) {
            continue;
        } else if (c1 > c2) {
            return 1;
        } else {
            return -1;
        }
    }
    return (s1.length === s2.length ? 0 : -1);
}

function AddToSortedList(list, newItem, comparator) {
    var children = list.childElements();
    for (var i=0; i<children.length; i++) {
        if (comparator(children[i], newItem) > 0) {
            list.insertBefore(newItem, children[i]);
            return;
        }
    }
    list.appendChild(newItem);
}

function UPKeyPressed(e)
{
    var key = e.which ? e.which : e.keyCode;
    // if the 'enter' key was pressed, attempt login
    if (key == 13) {
        Login();
    }
}

function GetSelection(obj, start)
{
    if (obj.createTextRange) {
        var range = document.selection.createRange();
        if (start) { // if we want the start of the selection
            if (range.text == '') { // if there is no 'selection', but just the caret
                range.moveStart('character', -obj.value.length);
                return range.text.length;
            } else // if there actually is a selection
                return obj.value.lastIndexOf(range.text);
        } else { // if we want the end of the selection
            if (range.text == '') { // if there is no 'selection', but just the caret
                range.moveEnd('character', obj.value.length);
                return obj.value.length - range.text.length;
            } else // if there actually is a selection
                return obj.value.lastIndexOf(range.text) + range.text.length;
        }
    } else if (obj.setSelectionRange) {
        return (start ? obj.selectionStart : obj.selectionEnd);
    }
    return 0;
}

function GetSelectionStart(obj) {
    if (obj.createTextRange) {
        var range = document.selection.createRange();
        if (range.parentElement() == obj) {
            elm = range.text;
            return obj.value.lastIndexOf(elm);
        }
    } else if (obj.setSelectionRange) {
        return obj.selectionStart;
    }
    return 0;
}

function ClearSelection() {
    if (document.selection) {
        document.selection.clear();
    } else {
        var sel = window.getSelection();
        if (sel) {
            sel.removeAllRanges();
        }
    }
}

// sets the caret of the given text input field to the start of the field
function ResetCaret(input) {
    try {
        if (input.createTextRange) {
            var r = input.createTextRange();
            r.move('character', 0);
            r.moveEnd('character', 0);
            r.select();
        } else {
            input.setSelectionRange(0, 0);
        }
    } catch (e) { }
}

function GetCookie(cookieName)
{
    var c = document.cookie;
    if (c.length > 0)
    {
        c_start = c.indexOf(cookieName + "=");
        if (c_start != -1)
        { 
            c_start = c_start + cookieName.length + 1;
            c_end = c.indexOf(';', c_start);
            if (c_end == -1) {
                c_end = c.indexOf('&', c_start);
            }
            if (c_end == -1) {
                c_end = c.length;
            }
            return unescape(c.substring(c_start, c_end));
        } 
    }
    return '';
}

function GetUserIdentity()
{
    return GetCookie('ident');
}

function Trim(str) {
    if (!str) return str;
	str = str.replace(/^\s+/, '');
	for (var i = str.length - 1; i >= 0; i--) {
		if (/\S/.test(str.charAt(i))) {
			str = str.substring(0, i + 1);
			break;
		}
	}
	return str;
}

String.prototype.WithMaxLength = function(maxLen) {
    if (!this.length || this.length < maxLen) {
        return this;
    } else {
        return this.substring(0, maxLen);
    }
};

function SmoothScroll(container, elem, options) {
    options = options || {};
    var offset = options.offset || 50, dur = options.duration || 0.4;
    var h = container.getHeight();
    if (elem.offsetTop > (container.scrollTop + h)) {
        // scroll down
        new Effect.Tween(container, container.scrollTop, (elem.offsetTop - h) + offset, {duration:dur}, 'scrollTop');
    } else if (elem.offsetTop < container.scrollTop) {
        // scroll up
        new Effect.Tween(container, container.scrollTop, elem.offsetTop - offset, {duration:dur}, 'scrollTop');
    }
}

function IsDigit(keyCode) {
   digit = !isNaN ( parseInt(String.fromCharCode(keyCode)) ) || 
      ( keyCode == 190 || keyCode == 110 ) || 
      ( keyCode >= 8 && keyCode <= 46 &&
      keyCode !=16 && keyCode !=32 );
   digit = digit || ( keyCode >= 96 && keyCode <=105 );
   return (digit);
}

function wheel(e) {
    var edit = $('editMedia');
    if (edit) edit.hide();
    
    var delta = 0;
    if (!e) // IE
        e = window.event;
    if (e.wheelDelta) { // IE/Opera
        delta = e.wheelDelta;
        if (window.opera)
            delta = -delta;
    } else if (e.detail) { // Mozilla
        // In Mozilla, sign of delta is different than in IE. Also, delta is multiple of 3.
        delta = -e.detail * 15;
    }
    
    /** If delta is nonzero, handle it.
     * Basically, delta is now positive if wheel was scrolled up,
     * and negative, if wheel was scrolled down.
     */
    if (delta) {
        var elem = FindScrollable(e);
        if (elem != null) {
            var ch = elem.clientHeight;
            var sh = elem.scrollHeight;
            if (ch >= sh) {
                // if the element is scrollable, but doesn't require scrolling, ignore it
                return;
            }
            if (delta < 0) {
                var scroll = ch + elem.scrollTop;
                if (scroll < sh) {
                    if (scroll - delta > sh) {
                        elem.scrollTop = sh - ch;
                    } else {
                        elem.scrollTop = elem.scrollTop - delta;
                    }
                }
            } else {
                if (elem.scrollTop > 0) {
                    var st = elem.scrollTop - delta;
                    elem.scrollTop = st < 0 ? 0 : st;
                }
            }
            Event.stop(e);
        }
    }
}

if (window.addEventListener) {
    Event.observe(window, 'DOMMouseScroll', wheel);
} else {
    window.onmousewheel = document.onmousewheel = wheel;
}

function FindScrollable(event)
{
    var e = Event.element(event);
    if (e == document || e == window) return null;
    while (e && e != document) {
        if (e.className && e.className.indexOf('scroll') != -1) {
            return e.clientHeight === e.scrollHeight ? null : e;
        }
        e = e.parentNode;
    }
    return null;
}

// msg should contain all HTML that is to be shown to the user including links.  WARNING: Do not wrap the message in any block
// options should be a class with a type value set to 'normal' for standard notification, 'warning' for a warning, 'error' for an error
// Sample call SetNotification('3 Clips Deleted <a href='~/undo'>Undo</a>', {type: 'normal'});
function SetNotification(msg, options)
{
    var notification = $('notification');
    if (!msg) {
        $('notificationinner').hide();
        return;
    }
    if (!options) { options = {} }
    if (!options.type) { options.type = 'normal' }
    notification.update(msg).className = options.type;
    Effect.Appear(notification.up(), {duration:0.15});
        
    if (options.duration !== -1) {
        setTimeout('CloseNotification()', options.duration ? options.duration * 1000 : 5000);
    }
}

function CloseNotification()
{
    Effect.Fade($('notificationinner'), {duration:0.4});
}

// Browser Detect  v2.1.6
// documentation: http://www.dithered.com/javascript/browser_detect/index.html
// license: http://creativecommons.org/licenses/by/1.0/
// code by Chris Nott (chris[at]dithered[dot]com)
function BrowserDetect() {
   var ua = navigator.userAgent.toLowerCase(); 

   // browser engine name
   this.isGecko       = (ua.indexOf('gecko') != -1 && ua.indexOf('safari') == -1);
   this.isAppleWebKit = (ua.indexOf('applewebkit') != -1);

   // browser name
   this.isSafari      = (ua.indexOf('safari') != - 1);
   this.isOpera       = (ua.indexOf('opera') != -1);
   this.isIE          = (ua.indexOf('msie') != -1 && !this.isOpera && (ua.indexOf('webtv') == -1) ); 
   this.isMozilla     = (this.isGecko && ua.indexOf('gecko/') + 14 == ua.length);
   this.isFirefox     = (ua.indexOf('firefox/') != -1 || ua.indexOf('firebird/') != -1);
   this.isNS          = ( (this.isGecko) ? (ua.indexOf('netscape') != -1) : ( (ua.indexOf('mozilla') != -1) && !this.isOpera && !this.isSafari && (ua.indexOf('spoofer') == -1) && (ua.indexOf('compatible') == -1) && (ua.indexOf('webtv') == -1) && (ua.indexOf('hotjava') == -1) ) );
   
   // spoofing and compatible browsers
   this.isIECompatible = ( (ua.indexOf('msie') != -1) && !this.isIE);
   this.isNSCompatible = ( (ua.indexOf('mozilla') != -1) && !this.isNS && !this.isMozilla);
   
   // rendering engine versions
   this.geckoVersion = ( (this.isGecko) ? ua.substring( (ua.lastIndexOf('gecko/') + 6), (ua.lastIndexOf('gecko/') + 14) ) : -1 );
   this.equivalentMozilla = ( (this.isGecko) ? parseFloat( ua.substring( ua.indexOf('rv:') + 3 ) ) : -1 );
   this.appleWebKitVersion = ( (this.isAppleWebKit) ? parseFloat( ua.substring( ua.indexOf('applewebkit/') + 12) ) : -1 );
   
   // browser version
   this.versionMinor = parseFloat(navigator.appVersion); 
   
   // correct version number
   if (this.isGecko && !this.isMozilla) {
      this.versionMinor = parseFloat( ua.substring( ua.indexOf('/', ua.indexOf('gecko/') + 6) + 1 ) );
   }
   else if (this.isMozilla) {
      this.versionMinor = parseFloat( ua.substring( ua.indexOf('rv:') + 3 ) );
   }
   else if (this.isIE && this.versionMinor >= 4) {
      this.versionMinor = parseFloat( ua.substring( ua.indexOf('msie ') + 5 ) );
   }
   else if (this.isSafari) {
      this.versionMinor = parseFloat( ua.substring( ua.lastIndexOf('safari/') + 7 ) );
   }
   else if (this.isOpera) {
      this.versionMinor = parseFloat( ua.substring( ua.indexOf('opera') + 6 ) );
   }
   
   this.versionMajor = parseInt(this.versionMinor); 
   
   // dom support
   this.isDOM1 = (document.getElementById);
   this.isDOM2Event = (document.addEventListener && document.removeEventListener);
   
   // css compatibility mode
   this.mode = document.compatMode ? document.compatMode : 'BackCompat';

   // platform
   this.isWin    = (ua.indexOf('win') != -1);
   this.isWin32  = (this.isWin && ( ua.indexOf('95') != -1 || ua.indexOf('98') != -1 || ua.indexOf('nt') != -1 || ua.indexOf('win32') != -1 || ua.indexOf('32bit') != -1 || ua.indexOf('xp') != -1) );
   this.isMac    = (ua.indexOf('mac') != -1);
   this.isLinux  = (ua.indexOf('linux') != -1);
   
   // specific browser shortcuts
   this.isNS4up = (this.isNS && this.versionMinor >= 4);
   this.isNS6x = (this.isNS && this.versionMajor == 6);
   this.isNS6up = (this.isNS && this.versionMajor >= 6);
   this.isNS7x = (this.isNS && this.versionMajor == 7);
   this.isNS7up = (this.isNS && this.versionMajor >= 7);
   
   this.isIE5up = (this.isIE && this.versionMajor >= 5);
   this.isIE6x = (this.isIE && this.versionMajor == 6);
   this.isIE6up = (this.isIE && this.versionMajor >= 6);
   this.isIE7up = (this.isIE && this.versionMajor > 6);
}
var browser = new BrowserDetect();


