// Javascript Global Functions
function ShowDiv(idName) {
    var idObject = document.getElementById(idName);
    if (idObject) {
        idObject.style.display = "block";
    }
}
function HideDiv(idName) {
    var idObject = document.getElementById(idName);
    if (idObject) {
        idObject.style.display = "none";
    }
}
function ShowVisib(idName) {
    var obj = document.getElementById(idName);
    if (obj) {
        obj.style.visibility = "visible";
    }
}
function HideVisib(idName) {
    var obj = document.getElementById(idName);
    if (obj) {
        obj.style.visibility = "hidden";
    }
}
function ShowModal(idName) {
    ShowVisib("overlayBkgdDiv");
    ShowDiv(idName);
}
function HideModal(idName) {
    HideDiv(idName);
    HideVisib("overlayBkgdDiv");
}


/*------------------------------------------------------------------------------
Function: Open Window
Simple Popup Window

Parameters:
uri - string
width - number (of pixels)
height - number (of pixels)
options - string
name - string
------------------------------------------------------------------------------*/
var poppedWin = null;
function MM_openBrWindow(theURL, width, height, opt, name) {
    poppedWin = window.open(theURL, (name || "OutsideWindow"), "width=" + (width || 714) + ",height=" + (height || 536) + "," + (opt || "scrollbars=yes,menubar=yes,toolbar=yes,location=yes,status=yes,resizable=yes"));
}
/*
Example of popup link. 
This way the popup window will not get blocked by popup-blockers:

<a href="http://URL-Path-File-Name-Here.aspx" onclick="MM_openBrWindow(this.href, 640, 450, 'ShareThisPageWin'); return false;">Share This Page</a>

*/



function CloseNow() {
    if (poppedWin.closed) {
        self.location.href = "/Client-Access/DMP/My-Documents/My-Documents/Check-User-Status.aspx";
    } else {
        CloseAndRedirect();
    }
}
function CloseAndRedirect() {
    setTimeout("CloseNow()", 1000);
}

function CloseNowDD() {
    if ((poppedWin == null) || poppedWin.closed) {
        self.location.href = "/Client-Access/DMP/Deposits/Sign-up-for-DepositDirect/Check-Sign-Status.aspx";
    } else {
        CloseAndRedirectDD();
    }
}

function CloseAndRedirectDD() {
    setTimeout("CloseNowDD()", 1000);
}

function OpenWindow(url, width, height, opt, name) {
    window.open(url, (name || "OutsideWindow"), "width=" + (width || 714) + ",height=" + (height || 536) + "," + (opt || "scrollbars=yes,menubar=yes,toolbar=yes,location=yes,status=yes,resizable=yes")).focus();
}


// ---------------------------------------------------------------------------------------
// Predefined Popup Windows

function PopHowToPrint(url) {
    OpenWindow(url, 550, 230, "scrollbars=yes,menubar=no,toolbar=no,location=no");
}
function PopHowToPrintSave() {
    OpenWindow("/Templates/DMP/How-to-Print-and-Save.aspx", 550, 490, "scrollbars=yes,menubar=no,toolbar=no,location=no");
}
function PopCheck() {
    OpenWindow('/Templates/DMP/Check.aspx', 400, 400, 'scrollbars=no,menubar=no,toolbar=no,location=no')
}
function PopCoupon(url) {
    OpenWindow(url, 640, 480, 'scrollbars=no,menubar=no,toolbar=no,location=no')
}

// ---------------------------------------------------------------------------------------
// Get Query String
function getQuery() {
    return window.location.href.slice(window.location.href.indexOf('?') + 1);
}


// ---------------------------------------------------------------------------------------
// BEGIN: Show Specific Tab in a page using URL Query
function HideAllToggle() {
    $(".toggle_display").each(function() {
        if ($(this).html() == "Hide") {
            $(this).html("Show");
            $(this).parent().next().removeClass('showing');
        }
    });
}
function ShowMatchingQueryTab(QueryString) {
    if (QueryString) {
        $("#" + QueryString + " .toggle_display").html("Hide");
        $("#" + QueryString).next().addClass('showing');
        location.href = "#" + QueryString;
    }
}
// END: Show Specific Tab in a page using URL Query



// ---------------------------------------------------------------------------------------
// BEGIN: JW Player
function deletePlayer(theWrapper, thePlaceholder, thePlayerId) {
    swfobject.removeSWF(thePlayerId);
    var tmp = document.getElementById(theWrapper);
    if (tmp) { tmp.innerHTML = "<div id=" + thePlaceholder + "></div>"; }
}
function createPlayer(thePlaceholder, thePlayerId, theFile, width, height) {
    var flashvars = {
        file: theFile,
        autostart: "false"
        //type: "video" if type is set to video then youtube videos don't play.
    }
    var params = {
        allowfullscreen: "true",
        allowscriptaccess: "always",
        wmode: "transparent"
    }
    var attributes = {
        id: thePlayerId,
        name: thePlayerId
    }
    swfobject.embedSWF("/_JS/JWPlayer/player-licensed.swf", thePlaceholder, width, height, "9.0.115", false, flashvars, params, attributes);
}
function initPlayer(theFile, width, height) {
    deletePlayer('wrapper', 'placeholder1', 'player1');
    createPlayer('placeholder1', 'player1', theFile, width, height);
}
// END: JW Player

// ---------------------------------------------------------------------------------------
// BEGIN: Set unique radio button in repeater

function SetUniqueRadioButton(nameregex, current) {
    re = new RegExp(nameregex);
    for (i = 0; i < document.forms[0].elements.length; i++) {
        elm = document.forms[0].elements[i]
        if (elm.type == 'radio') {
            if (re.test(elm.name)) {
                elm.checked = false;
            }
        }
    }
    current.checked = true;
}
// END: Set unique radio button in repeater

// ---------------------------------------------------------------------------------------
/**
* hoverIntent is similar to jQuery's built-in "hover" function except that
* instead of firing the onMouseOver event immediately, hoverIntent checks
* to see if the user's mouse has slowed down (beneath the sensitivity
* threshold) before firing the onMouseOver event.
* 
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* hoverIntent is currently available for use in all personal or commercial 
* projects under both MIT and GPL licenses. This means that you can choose 
* the license that best suits your project, and use it accordingly.
* 
* // basic usage (just like .hover) receives onMouseOver and onMouseOut functions
* $("ul li").hoverIntent( showNav , hideNav );
* 
* // advanced usage receives configuration object only
* $("ul li").hoverIntent({
*	sensitivity: 7, // number = sensitivity threshold (must be 1 or higher)
*	interval: 100,   // number = milliseconds of polling interval
*	over: showNav,  // function = onMouseOver callback (required)
*	timeout: 0,   // number = milliseconds delay before onMouseOut function call
*	out: hideNav    // function = onMouseOut callback (required)
* });
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne <brian@cherne.net>
*/
(function($) {
    $.fn.hoverIntent = function(f, g) {
        // default configuration options
        var cfg = {
            sensitivity: 7,
            interval: 100,
            timeout: 0
        };
        // override configuration options with user supplied object
        cfg = $.extend(cfg, g ? { over: f, out: g} : f);

        // instantiate variables
        // cX, cY = current X and Y position of mouse, updated by mousemove event
        // pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
        var cX, cY, pX, pY;

        // A private function for getting mouse position
        var track = function(ev) {
            cX = ev.pageX;
            cY = ev.pageY;
        };

        // A private function for comparing current and previous mouse position
        var compare = function(ev, ob) {
            ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
            // compare mouse positions to see if they've crossed the threshold
            if ((Math.abs(pX - cX) + Math.abs(pY - cY)) < cfg.sensitivity) {
                $(ob).unbind("mousemove", track);
                // set hoverIntent state to true (so mouseOut can be called)
                ob.hoverIntent_s = 1;
                return cfg.over.apply(ob, [ev]);
            } else {
                // set previous coordinates for next time
                pX = cX; pY = cY;
                // use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
                ob.hoverIntent_t = setTimeout(function() { compare(ev, ob); }, cfg.interval);
            }
        };

        // A private function for delaying the mouseOut function
        var delay = function(ev, ob) {
            ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
            ob.hoverIntent_s = 0;
            return cfg.out.apply(ob, [ev]);
        };

        // A private function for handling mouse 'hovering'
        var handleHover = function(e) {
            // next three lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut
            var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
            while (p && p != this) { try { p = p.parentNode; } catch (e) { p = this; } }
            if (p == this) { return false; }

            // copy objects to be passed into t (required for event object to be passed in IE)
            var ev = jQuery.extend({}, e);
            var ob = this;

            // cancel hoverIntent timer if it exists
            if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }

            // else e.type == "onmouseover"
            if (e.type == "mouseover") {
                // set "previous" X and Y position based on initial entry point
                pX = ev.pageX; pY = ev.pageY;
                // update "current" X and Y position based on mousemove
                $(ob).bind("mousemove", track);
                // start polling interval (self-calling timeout) to compare mouse coordinates over time
                if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout(function() { compare(ev, ob); }, cfg.interval); }

                // else e.type == "onmouseout"
            } else {
                // unbind expensive mousemove event
                $(ob).unbind("mousemove", track);
                // if hoverIntent state is true, then call the mouseOut function after the specified delay
                if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout(function() { delay(ev, ob); }, cfg.timeout); }
            }
        };

        // bind the function to the two event listeners
        return this.mouseover(handleHover).mouseout(handleHover);
    };
})(jQuery);


// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Jquery
$(document).ready(function() {
    // ---------------------------------------------------------------------------------------
    // Browse Topic box HOVER
    $(".roundbox_active").hover(

	function() {
	    $(this).addClass("roundbox_type2");
	}, function() {
	    $(this).removeClass("roundbox_type2");
	});

    // ---------------------------------------------------------------------------------------
    // Browse Topic box HOVER
    $(".addhover").hover(
	function() {
	    $(this).addClass("over");
	}, function() {
	    $(this).removeClass("over");
	});

    // ---------------------------------------------------------------------------------------
    // Shows Calendar
    $(".datepicker").datepicker({ changeMonth: true, changeYear: true, yearRange: '-100:+10' });


    // ---------------------------------------------------------------------------------------
    // Open ups correct tab
    $(".tab_hd a").click(function() {
        if ($(this).attr('rel') != "") {
            $(this).parents(".tab_area").find(".tab_container").hide();
            $($(this).attr('rel')).show();
            $(this).parents(".tab_area").find(".tab_hd a.on").removeClass('on');
            $(this).addClass('on');
        }
    });


    // ---------------------------------------------------------------------------------------
    // BEGIN: Dropdown Menu
    function addHoverHide(linkClass, layerId, t) {
        $("." + linkClass).hover(function() {
            clearTimeout(t);
            $(".prinav_menu").each(function() {
                if ($(this) != $("." + layerId)) {
                    $(this).hide();
                }
            });
            $("." + layerId).show();
        }, function() {
            t = setTimeout(function() { $("." + layerId).hide() }, 600);
        });

        $("." + layerId).hover(function() {
            clearTimeout(t);
            $("." + layerId).show();
        }, function() {
            t = setTimeout(function() { $("." + layerId).hide() }, 200);
        });
    }

    function clearTimeoutAll() {
        clearTimeout(nav2timer);
        clearTimeout(nav3timer);
        clearTimeout(nav4timer);
        clearTimeout(nav5timer);
    }
    // END: Dropdown Menu

    // ---------------------------------------------------------------------------------------
    // BEGIN: Dropdown Menu Initialize
    var nav1timer; // Account Overview (no sub items)
    addHoverHide("nav1", "navmenu1", nav1timer);
    var nav2timer; // Creditor Accounts
    addHoverHide("nav2", "navmenu2", nav2timer);
    var nav3timer; // eStatements
    addHoverHide("nav3", "navmenu3", nav3timer);
    var nav4timer; // Deposits
    addHoverHide("nav4", "navmenu4", nav4timer);
    var nav5timer; // My Documents
    addHoverHide("nav5", "navmenu5", nav5timer);

    /* Utilities Menus */
    var utilnav1timer; // My Account
    addHoverHide("util1", "utilmenu1", utilnav1timer);
    var utilnav2timer; // My Account
    addHoverHide("util2", "utilmenu2", utilnav2timer);
    // END: Dropdown Menu Initialize



    // ---------------------------------------------------------------------------------------
    //form highlights
    $(".formcell").click(function() {
        $(".form_selected").removeClass('form_selected');
        $(this).addClass('form_selected');
    });



    // ---------------------------------------------------------------------------------------
    // BEGIN: add color to ODD rows in tables
    $(".tbl_data_rows").each(function() {
        $(this).find("tr:even").addClass('odd')
    });

    $(".tbl_alt_rows").each(function() {
        $(this).find("tr:even").addClass('odd')
    });
    // END: add color to ODD rows in tables


    // ---------------------------------------------------------------------------------------
    // BEGIN: toggle_display
    /* Clicks on link Hide/Show */
    $(".toggle_display").toggle(function() {
        if ($(this).html() == "Show") {
            $(this).html("Hide");
        } else {
            $(this).html("Show");
        }
        $(this).parent().next().slideToggle();
    }, function() {
        if ($(this).html() == "Show") {
            $(this).html("Hide");
        } else {
            $(this).html("Show");
        }
        $(this).parent().next().slideToggle();
    });

    /* Clicks on Header to Hide/Show */
    $(".toggle_display_hd").toggle(function() {
        if ($(this).parent().find(".toggle_display").html() == "Show") {
            $(this).parent().find(".toggle_display").html("Hide");
        } else {
            $(this).parent().find(".toggle_display").html("Show");
        }
        $(this).parent().next().slideToggle();
    }, function() {
        if ($(this).parent().find(".toggle_display").html() == "Show") {
            $(this).parent().find(".toggle_display").html("Hide");
        } else {
            $(this).parent().find(".toggle_display").html("Show");
        }
        $(this).parent().next().slideToggle();
    });

    /* Clicks on Header to Hide/Show */
    $(".expander_hd").click(function() {
        if ($(this).attr('class').split(' ').slice(-1) == "minus") {
            $(this).removeClass("minus");
        } else {
            $(this).addClass("minus");
        }
        $(this).next('.collapsable').slideToggle();
    });
    // END: toggle_display

    // ---------------------------------------------------------------------------------------
    // BEGIN: accordion
    /* Clicks on link Hide/Show */
    $(".accordion h3").click(function() {
        if ($(this).find(".hd_link").html() == "Show") {
            $(".accordion h3").find(".hd_link").html("Show");
            $(this).find(".hd_link").html("Hide");
            $(".accordion .collapsable").slideUp();
            $(this).next().slideDown();
        } else {
            $(this).find(".hd_link").html("Show");
            $(this).next().slideUp();
        }
    });
    // END: accordion

    // ---------------------------------------------------------------------------------------
    // BEGIN: Clear form input values
    $('.clear_button').click(function() {
        var $thisForm = $(this).parents('fieldset');
        $thisForm.find(':text').val('');
        $thisForm.find('textarea').val('');
        $thisForm.find('select').each(function() {
            $(this).find('option:first').attr('selected', 'selected').parent('select');
        });
        return false;
    });
    // END: Clear form input values

    // ---------------------------------------------------------------------------------------
    // BEGIN: Clear Header Search field's default text
    $(".headsearchtxt").focus(function() {
        //alert ($(this).val() == "Enter keywords");
        if (($(this).val() == $(this).attr("rel")) || ($(this).val() == $(this).attr("title"))) {
            $(this).val("");
            $(this).removeClass("off");
        }

    }).blur(function() {
        if ($(this).val() == "") {
            if ($(this).attr("rel")) {
                $(this).val($(this).attr("rel"));
            } else {
                $(this).val($(this).attr("title"));
            }
            $(this).addClass("off");
        }
    });
    // END: Clearn Header Search field's default text


    // ---------------------------------------------------------------------------------------
    // BEGIN: modal window
    function getDimensions() {
        winWidth = $(window).width();
        winHeight = $(window).height();

        pageWidth = $(document).width();
        pageHeight = $(document).height();

        wrapperWidth = $(".wrapper").width();

        modalWidth = $(".modal").outerWidth();
        modalHeight = $(".modal").outerHeight();
    }
    function sizeOverlay() {
        if (winWidth <= wrapperWidth) {
            $(".overlayBkgd").width(wrapperWidth);
        } else {
            $(".overlayBkgd").width(winWidth);
        }
        $(".overlayBkgd").height(pageHeight);
    }
    function positionModal() {
        /* Top */
        modalTop = ((winHeight - (modalHeight + 100)) / 2) / 2;
        if (modalTop <= 0) {
            modalTop = $(window).scrollTop() + 10;
        } else {
            modalTop = $(window).scrollTop() + 100;
        }
        $(".modal").css("top", modalTop + "px");

        /* Left */
        modalMarginLeft = modalWidth / 2;
        if (winWidth <= wrapperWidth) {
            $(".modal").css("margin-left", "-" + modalMarginLeft + "px");
            $(".modal").css("left", (wrapperWidth / 2) + "px");
        } else {
            $(".modal").css("margin-left", "-" + modalMarginLeft + "px");
            $(".modal").css("left", "50%");
        }
    }
    function modalInit() {
        getDimensions();
        sizeOverlay();
        positionModal();
    }
    $(window).resize(function() {
        var Mask = document.getElementById("overlayBkgdDiv");
        if (Mask) {
            if (Mask.style.visibility == "visible") {
                modalInit();
            }
        }
    });

    //select all the a tag with name equal to modal
    $('.modal_link').click(function() {
        modalInit();
    });
    // END: modal window

    // ---------------------------------------------------------------------------------------
    // BEGIN: select_all / unselect_all
    $('.select_all').click(function() {
        var $thisForm = $(this).parents('fieldset');
        $thisForm.find(':checkbox').attr("checked", "checked");
        return false;
    });
    $('.unselect_all').click(function() {
        var $thisForm = $(this).parents('fieldset');
        $thisForm.find(':checkbox').removeAttr("checked")
        return false;
    });
    // END: select_all / unselect_all



    // ---------------------------------------------------------------------------------------
    // BEGIN: checkboxdisabled
    /*$('.checkboxdisabled').click(function() {
    if ($(this).is(':checked')) {
    $(this).parents('.checkboxdisabled_group').find('.checkboxdisabled_field').removeClass('disabled');
    } else {
    $(this).parents('.checkboxdisabled_group').find('.checkboxdisabled_field').addClass('disabled');
    }
    });
    */


    // ---------------------------------------------------------------------------------------
    // BEGIN: dropnav: onclick and mouseleave
    $(".arrow").click(function() {
        // on click of arrow add class to <li> that turns on the drop nav

        $(this).parents("li").toggleClass("dropon")
    });

    $(".mmi li").mouseleave(function() {
        // dropnav is inside the <li>
        // on mouseout of <li> remove the class
        $(this).removeClass("dropon");
    });



    // ---------------------------------------------------------------------------------------
    // BEGIN: Accordion
    /* Accordion */
    function initMenu() {
        $('.acc_menu ul').hide();

        /* Show Sub links for Selected Tab */
        $('.acc_menu span.sel').siblings().show();
        $('.acc_menu span.sel').find("b").addClass("minus");

        /*$('#menu ul:first').show();*/
        $('.acc_menu li span b.expand').click(function() {
            /* Clears any initial Sel tab */
            /*$('.acc_menu li span.sel').removeClass("sel");*/

            var checkElement = $(this).parent().next();
            if ((checkElement.is('ul')) && (checkElement.is(':visible'))) {
                /* Clicking on selected tab - collapses tab */
                $('.acc_menu ul:visible').parent().find("b").removeClass("minus");
                $('.acc_menu ul:visible').slideUp('normal');


                /* Use this code if you do not want the accordion effect of hiding everything */
                /*$(this).parent().find("b").removeClass("minus");
                checkElement.slideUp('normal');
                */

                /*return false;*/
            }
            if ((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
                /* Clicking on other tabs - expand and change icon to "-" */

                /* Add sel style */
                /*$(this).addClass("sel");*/

                /* Comment next 2 lines if you do not want accordion effect of hiding everything */
                $('.acc_menu ul:visible').parent().find("b").removeClass("minus");
                $('.acc_menu ul:visible').slideUp('normal');

                $(this).parent().find("b").addClass("minus");
                checkElement.slideDown('normal');
                /*return false;*/
            }
        });
    }
    initMenu();
    // END: Accordion




    // ---------------------------------------------------------------------------------------
    // BEGIN: toc
    /* Section Nav - toc - automatically collapse as default */

    $('.toc div.on').each(function() {
        $(this).next().next().show();
    });

    // END: toc


    // ---------------------------------------------------------------------------------------
    // BEGIN: Add_Ellipsis - use ellipsis max characters
    function Add_Ellipsis(classname, maxchars, removehtml) {
        var slicePoint = (maxchars || 50);
        $(classname).each(function() {
            var allText = $(this).html();
            var editText;

            if (removehtml) {
                // This removes all HTML Tags
                editText = allText.replace(/<\/?[^>]+>/gi, '');
            } else {
                editText = allText;
            }

            if (editText.length > slicePoint) {
                // This cuts off after 65 characters but up to the word
                var startText = editText.slice(0, slicePoint).replace(/\w+$/, '');

                // Add ellipsis
                startText = startText + "...";
                $(this).html(startText);
            }
        });
    }
    // Initialize Ellipsis Here
    // Example - 
    // Add_Ellipsis(jQuery_class_name, maxCharacters, removeHTML?);
    // Add_Ellipsis('.result_title a', 90, false);

    // Template... Search-Results.aspx
    Add_Ellipsis('.result_title a', 90, false);
    Add_Ellipsis('.result_teaser', 200, true);

    // Banner Bread Crumb MMI page
    Add_Ellipsis('.banner_bc a', 30, false);
    Add_Ellipsis('.banner_bc b', 50, false);
    Add_Ellipsis('.banner2 h1 span', 50, false);


    // END: Add_Ellipsis - use ellipsis max characters



    // ---------------------------------------------------------------------------------------
    // BEGIN: Slide Down to Error Message
    if ($('.formgroup.error').length > 0) {
        var targetOffset = $('.error_popup:visible').offset().top - 6;
        $('html,body').animate({ scrollTop: targetOffset }, 1000);
    }
    // END: Slide Down to Error Message


    // ---------------------------------------------------------------------------------------
    // BEGIN: image resizing
    $('.flickr_post .img_holder img').each(function() {
        var imgwidth = $(this).width();
        var imgheight = $(this).height();
        // 240/160 = 1.5
        if ((imgwidth / imgheight) > 1.5) {
            $(this).height('160px');
        } else {
            $(this).width('240px');
        }
    });
    $('.tbl_thumb_large .thumb img').each(function() {
        var imgwidth = $(this).width();
        var imgheight = $(this).height();
        // 138/125 = 1.5
        if ((imgwidth / imgheight) > 1.104) {
            $(this).height('125px');
        } else {
            $(this).width('138px');
        }
    });
    // END: image resizing

});

// ---------------------------------------------------------------------------------------
// BEGIN: manipulate 3rd party captcha css styles
$(function() {
    $(".Captcha div").css({ marginLeft: "0px", textAlign: "left" });
    $(".Captcha div input").css({ borderColor: "#39658D" });

    $(".Captcha_Err div").css({ marginLeft: "0px", textAlign: "left" });
    $(".Captcha_Err div input").css({ borderColor: "#D60000" });
});


//BEGIN: hide or disable submit buttons on click event





//END

// Author: Brian Thopsey http://topcweb.com    - thanks to Rudi Shumpert
// Code for tracking of video player, Longtail - JWplayer on Omniture SC
// variables to help populate player
var currentBuffer = 0;
var currentPosition = 0;
var currentState = "NONE";
var defaultState = "NONE";
var currentLoad = 0;
var clipDuration = 0;
var player;
var playerLocation = "/_JS/JWPlayer/player-licensed.swf"; //--- Location of the JWplayer file

/* additional vars that are not neccessary */
var autoPlay;
var viralShare;
var captions;
var captionFile;

// Function for instatiating player
function playerReady(obj) {
    //alert('the videoplayer '+obj['id']+' has been instantiated');
    player = document.getElementById(obj['id']);
    addListeners()
};

function addListeners() {
    //load the JWplayer event listners
    if (player) {
        addAllModelListeners();
    }
}

function addAllModelListeners() {
    if (typeof player.addModelListener == "function") {
        player.addModelListener("BUFFER", "doNothing"); //{percentage,id,client,version}.
        player.addModelListener("ERROR", "doNothing"); //{message,id,client,version}.
        player.addModelListener("LOADED", "doNothing"); //{loaded,total,offset,id,client,version}.
        player.addModelListener("META", "doNothing"); //{variable1,variable2,variable3,...,id,client,version}.
        player.addModelListener("STATE", "stateListener"); //{newstate,oldstate,id,client,version}.
        player.addModelListener("TIME", "positionListener"); //{position,duration,id,client,version}.
    }
}

function doNothing(obj) { //nothing
}

function positionListener(obj) {
    //let's us know where we are in the video
    currentPosition = obj.position;
    clipDuration = obj.duration;
}

function stateListener(obj) {
    oldState = obj.oldstate;
    if (defaultState == "NONE") {
        defaultState = "started";
        getTimeValue();
    }

    currentState = obj.newstate;
    //currentTime = obj.position;

    //pass the event to Omniture
    if (currentState == "COMPLETED") {
        //alert('Video Tracking Test\n completed');    //testing
        omniMediaTrackingDone(videoFileName, currentPosition);
        //alert('Hello');
    }
    if (currentState == "PLAYING") {
        //alert('Video Tracking Test\n play');    //testing
        if (currentPosition != "0") {
            omniMediaTrackingResume(videoFileName, currentPosition);
        }
    }
    if (currentState == "PAUSED") {
        //alert('Video Tracking Test\n paused');      //testing
        //alert(videoFileName);      //testing
        //alert(currentPosition);      //testing
        omniMediaTrackingStop(videoFileName, currentPosition);
        //alert('Hello');
    }
}

// according to Rudi you can not combine the listener events, so the functions below are a workaround to get the length/pos of the video file
function getTimeValue() {
    if (currentPosition == "0") {
        //needed to allow the video to load in in order to capture the parameters
        setTimeout("getTimeValue()", 100);
    } else {
        omniInitMediaTracking(videoFileName, clipDuration, 'JWplayer');
    }
}