//overlay code
var overlayState = false;
var currentElement = null;
var hasFlash = false; //used to hide video player
var star;

// function for rating update on Home TAB and MyAccount Rental History
function updateRating(mtype, movieId, newRating, url)
{
    var divElements = document.getElementsByTagName('div');
    for (var i = 0; i < divElements.length; i++){
        var idStr = divElements[i].id;
        if (idStr.substr(0,7) == 'rating-' && idStr.match(movieId) == movieId) {
            var rowId = idStr.substring(7);
            $('notInterested-' + rowId).hide();
            $('ratingIndicator-' + rowId).show();

            if (rowId.length > 0) {
                var updateUrl = url + '?newRating=' + newRating + '&uniqueId=' + rowId + '&mtype=' + mtype + '&itemId=' + movieId;
            }
            else {
                var updateUrl = url + '?newRating=' + newRating + '&mtype=' + mtype + '&itemId=' + movieId;
            }
            updateUrl += '&updatedRating=1';
            new Ajax.Updater(idStr, updateUrl, {asynchronous:true, evalScripts:true});
        }
    }
}

// function for rating on the main page, from a popup screen
function updateMainRating(idStr, url, newRating, uniqueId, mtype, movieId)
{
    var updateUrl = url + '?newRating=' + newRating + '&uniqueId=' + uniqueId + '&mtype=' + mtype + '&itemId=' + movieId;
    updateUrl += '&updatedRating=1';

    $('notInterested-' + uniqueId).hide();
    $('ratingIndicator-' + uniqueId).show();
    new Ajax.Updater(idStr, updateUrl, {asynchronous:true, evalScripts:true});
}

function updateQueueCount(numInQueue)
{
    var append = '';

    if (numInQueue > 1) {
        append = 's';
    }

    $('numInQueue').innerHTML = '<p id="queueNum">' + numInQueue + ' DVD' + append + ' in Queue</p>';
}

function removeFromQueueCount(inQueueNum)
{
    var total = 0;
    //var remove = document.updateQueueFrm.elements["remove[]"];
    var remove = document.getElementsByName("remove[]");
    var max = remove.length;

    for (var idx = 0; idx < max; idx++) {
    if (remove[idx].checked) {
        total += 1;
       }
    }

    nowInQueue = (inQueueNum - total);
    updateQueueCount(nowInQueue);
}

function updateToInQueueButtonMultiple(movieIdListString, queueCount, onClick)
{
    var i;
    var movieIdList = movieIdListString.split(",");
    for (i in movieIdList)
    {
        var movieId = movieIdList[i];
        updateToInQueueButton(movieId, queueCount, onClick);
    }
}

function updateToInQueueButton(movieId, queueCount, onClick)
{
    if($('addButton' + movieId)) {
        if (queueCount > 0) {
            $('addButton' + movieId).innerHTML = '<a class="btnInQSmall" href="javascript:void(0);" onClick="' + onClick + '"></a>';
        }
        else {
            $('addButton' + movieId).innerHTML = '<a class="btnInSglQSmall" href="javascript:void(0);" onClick="' + onClick + '"></a>';
        }
    }
    if($('addButtonLarge' + movieId)) {
        if (queueCount > 0) {
            $('addButtonLarge' + movieId).innerHTML = '<a title="In Queue" class="inQueueBtnLarge" href="javascript:void(0);" onClick="' + onClick + '"></a>';
        }
        else {
            $('addButtonLarge' + movieId).innerHTML = '<a title="In Queue" class="inSglQueueBtnLarge" href="javascript:void(0);" onClick="' + onClick + '"></a>';
        }
    }
    if($('addButtonHuge' + movieId)) {
        if (queueCount > 0) {
            $('addButtonHuge' + movieId).innerHTML = '<a title="In Queue" class="inQueueBtnHuge" href="javascript:void(0);" onClick="' + onClick + '"></a>';
        }
        else {
            $('addButtonHuge' + movieId).innerHTML = '<a title="In Queue" class="inSglQueueBtnHuge" href="javascript:void(0);" onClick="' + onClick + '"></a>';
        }
    }
}

function showBox(startElement){
    if(hasFlash==true){
        $('content-1').update('');
    }

    if(currentElement != null){
        $(currentElement).setStyle({backgroundPosition: 'top left'});
    }

    //currentElement = null;
    $('myQs').hide();
    $('inQs').hide();

    $('overlay').style.display = 'block';

    $('box').style.display  = '';
    var el = document.getElementById('overlay');
    bodyHeight = document.body.offsetHeight;

    containerHeight = document.getElementById('container').offsetHeight;
    if(bodyHeight > containerHeight){
        el.style.height = bodyHeight + "px";
    }else{
        el.style.height = containerHeight + "px";
    }

    //hide selects for IE

    var selects = $('moviesContent').getElementsBySelector('select');
    selects.each(function(select){
        select.hide();
    });


    $(startElement).show();
    //$('box').style.display  = 'block';

    center('box');
    overlayState = true;
    return false;
}

function hideBox(){
    $('overlay').hide();
    $('box').hide();
    $('myQs').hide();
    $('inQs').hide();
    if(hasFlash==true){
        makeFlash("flash/movie_trailer.swf", "movie_player", "512", "318", "8", "#FFF", "content-1", "true", "opaque");
    }
    overlayState = false;
    var selects = $('moviesContent').getElementsBySelector('select');
    selects.each(function(select){
        select.show();
    });
    return false;
}


window.onresize = function(){
    if(overlayState == true){
        var el = document.getElementById('overlay');
        bodyHeight = document.body.offsetHeight;
        containerHeight = document.getElementById('container').offsetHeight;
        if(bodyHeight > containerHeight){
            el.style.height = bodyHeight + "px";
        }else{
            el.style.height = containerHeight + "px";
        }
        center('box');
    }
}

window.onscroll = function(){
    if(overlayState == true){
        var el = document.getElementById('overlay');
        bodyHeight = document.body.offsetHeight;
        containerHeight = document.getElementById('container').offsetHeight;
        if(bodyHeight > containerHeight){
            el.style.height = bodyHeight + "px";
        }else{
            el.style.height = containerHeight + "px";
        }
        if($('added').style.display == 'none'){
            center('box');
        }
    }
}


function center(element){
    try{
        element = $(element);
    }catch(e){
        return;
    }

    var my_width  = 0;
    var my_height = 0;

    if ( typeof( window.innerWidth ) == 'number' ){
        my_width  = window.innerWidth;
        my_height = window.innerHeight;
    }else if ( document.documentElement &&
             ( document.documentElement.clientWidth ||
               document.documentElement.clientHeight ) ){
        my_width  = document.documentElement.clientWidth;
        my_height = document.documentElement.clientHeight;
    }
    else if ( document.body &&
            ( document.body.clientWidth || document.body.clientHeight ) ){
        my_width  = document.body.clientWidth;
        my_height = document.body.clientHeight;
    }

    element.style.position = 'absolute';
    element.style.zIndex   = 80;

    var scrollY = 0;

    if ( document.documentElement && document.documentElement.scrollTop ) {
        scrollY = document.documentElement.scrollTop;
    } else if ( document.body && document.body.scrollTop ){
        scrollY = document.body.scrollTop;
    } else if ( window.pageYOffset ) {
        scrollY = window.pageYOffset;
    } else if ( window.scrollY ) {
        scrollY = window.scrollY;
    }

    var elementDimensions = Element.getDimensions(element);

    var setX = ( my_width  - elementDimensions.width  ) / 2;
    var setY = ( my_height - elementDimensions.height ) / 2 + scrollY;

    setX = ( setX < 0 ) ? 0 : setX;
    setY = ( setY < 0 ) ? 0 : setY;

    if($('added') != null && $('added').style.display == '') {
        var p = Position.cumulativeOffset($('added'));
        setY = 40;
        scrollY = scrollY + 20;
        //Element.scrollTo('overlay');
    }

    element.style.left = setX + "px";
    if($('added') != null && $('added').style.display == '') {
        $(element).setStyle({top: scrollY+'px'});
    }else if($('collectCreditcardAndTermsAndConditions') != null && $('collectCreditcardAndTermsAndConditions').style.display == '') {
    //        Do not scroll
    }else{
        $(element).setStyle({top: setY+'px'});
    }

}



//"flash/moviesNav.swf", "movies_nav", "744", "116", "7", "#05070c", "flashNav"

function makeFlash(swf, name, w, h, v, c, t, fs, wm){
           var so = new SWFObject(swf, name, w, h, v, c);
           so.addParam("allowFullScreen", fs);
           if(wm == "transparent"){
               so.addParam("wmode", "transparent");
           }
           if(name == 'movies_nav'){
               so.addVariable("menu0URL", "/index.php");
               so.addVariable("menu1URL", "/news.php");
               so.addVariable("menu2URL", "/cinema.php");
               so.addVariable("menu3URL", "/downloads.php");
               so.addVariable("menu4URL", "search.php");
               so.addVariable("menu5URL", "/mobile.php");
           }
        so.write(t);
}


function changeTabs(n, t, flash){
    for(i = 0; i < t; i++){
        Element.setStyle('tab-'+i+'-text', {background:'#FFF url(/images/bpm/tab_off_bg.gif) repeat-x'} );
        Element.setStyle('tab-'+i+'-left', {background:'#FFF url(/images/bpm/tab_off_left.gif) repeat-x'} );
        $('tab-'+i+'-text').removeClassName('selected');
        Element.setStyle('tab-'+i+'-right', {background:'#FFF url(/images/bpm/tab_off_right.gif) right top repeat-x'} );
        $('content-'+i).hide();
    }
    Element.setStyle('tab-'+n+'-text', {background:'url(/images/bpm/tab_on_bg.gif) repeat-x'} );
    $('tab-'+n+'-text').addClassName('selected');
    Element.setStyle('tab-'+n+'-left', {background:'#FFF url(/images/bpm/tab_on_left.gif) repeat-x'} );
    Element.setStyle('tab-'+n+'-right', {background:'#FFF url(/images/bpm/tab_on_right.gif) right top repeat-x'} );
    $('content-'+n).show();
    if(flash == true){
        if(n==1){
            hasFlash = true;
            makeFlash("flash/movie_trailer.swf", "movie_player", "512", "318", "8", "#FFF", "content-1", "true", "opaque");
        }else{
            hasFlash = false;
            $('content-1').update('');
        }
    }
    return false;
}



//this is a dummy function to simulate an ajax call when a user adds a film to their queue
// this function should be replaced by your actual ajax calls.
function doDummyAJAX(){
    setTimeout("DoSomethingUseful()", 1000);
}
function DoSomethingUseful(){
    showBox('added');
}




var dist = 145;
var vertScrolling = false;

function vertFinish(obj){
    vertScrolling = false;
}

function scrollDown() {
    if(vertScrolling==false && returnCount < (totalReturns-4) ) {
        vertScrolling = true;
        var p = Position.positionedOffset($('scrollMe'));
        var smh = $('scrollMe').getHeight();
        var sch = $('scrollContent').getHeight();
        var offSet = -(smh - sch);
        var num = smh + p[1] - sch;

        if(p[1] > offSet) {
            if(num > dist) {
                new Effect.MoveBy( $('scrollMe'), -dist, 0, { afterFinish: vertFinish} );
            }
            else {
                new Effect.MoveBy( $('scrollMe'), -(num), 0, { afterFinish: vertFinish} );
                $('btnDown').className = 'downInactive';
            }
        }

        if(totalReturns - (returnCount+5) > 5) {
            returnCount+=5;
            $('pagination').update(returnCount + '-' + (returnCount+4) + ' of ' + totalReturns);
        }
        else {
            returnCount = (totalReturns - 4);
            $('pagination').update((totalReturns-4) + '-' + (totalReturns) + ' of ' + totalReturns);
        }
        $('btnUp').className = 'btnUp';
    }
}
function scrollUp(){
    //alert(returnCount);
    if(vertScrolling==false && returnCount > 1){
        vertScrolling = true;
        var p = Position.positionedOffset($('scrollMe'));
        var smh = $('scrollMe').getHeight();
        var sch = $('scrollContent').getHeight();
        var offSet = -(smh - sch);
        var num = smh + p[1] - sch;
        if(p[1] < 0 ){
            if(p[1] <= -dist){
                new Effect.MoveBy( $('scrollMe'), dist, 0 , { afterFinish: vertFinish} );
            }else{
                new Effect.MoveBy( $('scrollMe'), Math.abs(p[1]), 0 , { afterFinish: vertFinish});

            }
        }

        if(returnCount > 5){
            returnCount-=5;
            $('pagination').update(returnCount + '-' + (returnCount+4) + ' of ' + totalReturns);
        }else{
            returnCount = 1;
            $('pagination').update('1-5 of ' + totalReturns);
        }
        if(returnCount==1){
            $('btnUp').className = 'upInactive';
        }
        $('btnDown').className = 'btnDown';
    }
}




function highlightGenre(el){
    var siblings = $(el).siblings();
    var state = $(el).classNames();

    siblings.each(function(item){
        if(item.hasClassName('accordion-selected')){
            item.classNames().set('accordion-genre');
        }
    });
    if(state == 'accordion-selected'){
        $(el).classNames().set('accordion-genre');
    }else{
        $(el).classNames().set('accordion-selected');
    }
}



var xDist = 725;
var scrolling = false;


function myCallBackOnFinish(obj){
    scrolling = false;
}
function myCallBackOnStart(obj){
    scrolling  = true;
}

// ScrollRight for ajax carousels
function ACUpdateButtons(carouselId, lastPage) {

    $('btnLeft'+ carouselId).className =  'leftInactive';
    if($('pageLoaded_'+ carouselId).value > 1) {
        $('btnLeft'+ carouselId).className = 'btnLeft';
    }

    if ($('pageLoaded_'+ carouselId).value == lastPage) {
        $('btnRight'+ carouselId).hide();
        $('btnRight2'+ carouselId).show();
    }

    if($('pageViewed_'+ carouselId).value < lastPage) {
        $('btnRight'+ carouselId).className = 'btnRight';
        $('btnRight2'+ carouselId).className = 'btnRight';
    } else {
        $('btnRight'+ carouselId).className = 'rightInactive';
        $('btnRight2'+ carouselId).className = 'rightInactive';
    }

    $('myQs').hide();
    $('inQs').hide();
}


function ACScrollLeft(el, btn, carouselId) {
    var p = Position.positionedOffset($(el));

    if(p[0] < 0 && scrolling == false) {
        if(p[0] <= -xDist){
            new Effect.MoveBy( $(el), 0, xDist, { afterFinish: myCallBackOnFinish, beforeStart: myCallBackOnStart });

            if($('pageViewed_'+ carouselId).value > 1) {
                $('pageViewed_'+ carouselId).value =  $('pageViewed_'+ carouselId).value - 1;
                $('btnRight'+ carouselId).hide();
                $('btnRight2'+ carouselId).show();
                $('btnRight2'+ carouselId).className= 'btnRight';
            }
        } else {
            new Effect.MoveBy( $(el), 0, Math.abs(p[0]), { afterFinish: myCallBackOnFinish, beforeStart: myCallBackOnStart } );
        }

        $(btn).next(0).className = 'btnRight';
    }

    if(p[0] >= -725 ){
      $(btn).className = 'leftInactive';
    }
}

function ACscrollRight(el, btn, carouselId, lastPage)
{
    var p = Position.positionedOffset($(el));
    var sm = $(el).getDimensions();
    var smw = sm.width;

    var scw = xDist;
    var offSet = -(smw - scw);
    var num = smw + p[0] - scw;

    if(p[0] > offSet  && scrolling == false){
        if(num > xDist){
            new Effect.MoveBy( $(el), 0, -xDist, { afterFinish: myCallBackOnFinish, beforeStart: myCallBackOnStart } );
        }else{
            new Effect.MoveBy( $(el), 0, -(num), { afterFinish: myCallBackOnFinish, beforeStart: myCallBackOnStart } );
            $(btn).className = 'rightInactive';
        }

        // if we are not viewing the last page loaded
        if($('pageViewed_'+ carouselId).value < $('pageLoaded_'+ carouselId).value ) {
            $('pageViewed_'+ carouselId).value =  parseInt($('pageViewed_'+ carouselId).value) + 1;
        } else
        if($('pageViewed_'+ carouselId).value == $('pageLoaded_'+ carouselId).value) {
            $('pageLoaded_'+ carouselId).value =  parseInt($('pageLoaded_'+ carouselId).value) + 1;
            $('pageViewed_'+ carouselId).value =  parseInt($('pageViewed_'+ carouselId).value) + 1;
            $('nextId_'+carouselId).value = parseInt($('nextId_'+carouselId).value) +1
        }

        if($('pageViewed_'+ carouselId).value == $('pageLoaded_'+ carouselId).value && ($('pageLoaded_'+ carouselId).value != lastPage)  ) {
            $('btnRight'+ carouselId).show();
            $('btnRight2'+ carouselId).hide();
        }
        $('loading_'+carouselId).hide();
    }

    if(smw > 725){
      $('btnLeft'+ carouselId).className = 'btnLeft';
    }
    ACUpdateButtons(carouselId, lastPage);
}

function ACUpdateTitleCount(carouselId, titleCount) {
    $("numTitles_"+carouselId).innerHTML = titleCount;
}

function scrollRight(el, btn){

    var p = Position.positionedOffset($(el));
    var sm = $(el).getDimensions();
    var smw = sm.width;

    var scw = xDist;
    var offSet = -(smw - scw);
    var num = smw + p[0] - scw;
    if(p[0] > offSet  && scrolling == false){
        if(num > xDist){
            new Effect.MoveBy( $(el), 0, -xDist, { afterFinish: myCallBackOnFinish, beforeStart: myCallBackOnStart } );
        }else{
            new Effect.MoveBy( $(el), 0, -(num), { afterFinish: myCallBackOnFinish, beforeStart: myCallBackOnStart } );
            $(btn).className = 'rightInactive';
        }
        hideQList();
    }
    if(smw > 725){
        $(btn).previous(0).className = 'btnLeft';
    }
}

function scrollToLeft(el, btn){
    var p = Position.positionedOffset($(el));
    var sm = $(el).getDimensions();
    var smw = sm.width;
    var scw = xDist;
    var offSet = -(smw - scw);
    var num = smw + p[0] - scw;
    if(p[0] < 0 && scrolling == false){
        if(p[0] <= -xDist){
            new Effect.MoveBy( $(el), 0, xDist, { afterFinish: myCallBackOnFinish, beforeStart: myCallBackOnStart });
        }else{
            new Effect.MoveBy( $(el), 0, Math.abs(p[0]), { afterFinish: myCallBackOnFinish, beforeStart: myCallBackOnStart } );

        }
        $(btn).next(0).className = 'btnRight';
        hideQList();
    }

    if(p[0] >= -725 ){
        $(btn).className = 'leftInactive';
    }

}

//constructor for Scroller Object
function Scroller(){
}


function showQList(el){
    if(currentElement != el){
        $(el).setStyle({backgroundPosition: 'bottom left'});
        if(currentElement != null){
            $(currentElement).setStyle({backgroundPosition: 'top left'});
        }
        var p = Position.cumulativeOffset($(el));
        if(navigator.appName == 'Microsoft Internet Explorer'){
            $('myQs').setStyle({top: (p[1]-42)+'px', left: (p[0]-15)+'px'});
        }
        else{
            $('myQs').setStyle({top: (p[1]-42)+'px', left: (p[0]-15)+'px'});
        }
        $('myQs').show();
        currentElement = el;
    }else{
        $(el).setStyle({backgroundPosition: 'top left'});
        $('myQs').hide();
        currentElement = null;
    }
    $('inQs').hide();
}

function showInQList(el){

    if(currentElement != el){
        $(el).setStyle({backgroundPosition: 'bottom left'});
        if(currentElement != null){
            $(currentElement).setStyle({backgroundPosition: 'top left'});
        }
        var p = Position.cumulativeOffset($(el));
        if(navigator.appName == 'Microsoft Internet Explorer'){
            $('inQs').setStyle({top: (p[1]-42)+'px', left: (p[0]-15)+'px'});
        }
        else{
            $('inQs').setStyle({top: (p[1]-42)+'px', left: (p[0]-15)+'px'});
        }
        $('inQs').show();
        currentElement = el;
    }else{
        $(el).setStyle({backgroundPosition: 'top left'});
        $('inQs').hide();
        currentElement = null;
    }
    $('myQs').hide();
}

function hideQList() {
  if(currentElement != null) {
    $(currentElement).setStyle({backgroundPosition: 'top left'});
    $('myQs').hide();
    $('inQs').hide();
    currentElement = null;
  }
}

function showRollover(){
    var bodyWidth = document.body.offsetWidth;
    var p = Position.cumulativeOffset($(currentRollOver));
    if(p[0] < (bodyWidth/2)){
        $('roLgeLeft').show();
        $('roLgeLeft').setStyle({top: (p[1]-50)+'px', left: (p[0]+110)+'px'});
    }else{
        $('roLgeRight').show();
        $('roLgeRight').setStyle({top: (p[1]-50)+'px', left: (p[0]-320)+'px'});
    }
}

function hideRollover(el){
    var bodyWidth = document.body.offsetWidth;
    var p = Position.cumulativeOffset($(el));
    if(p[0] < (bodyWidth/2)){
        $('roLgeLeft').hide();
    }else{
        $('roLgeRight').hide();
    }
}

function clearRows(tr){
    var table = $(tr).up(0);
    if(table.classNames() == 'plan white'){
        var trs = $(table).getElementsBySelector('tr');
        trs.each(function(row){
            if(row.hasClassName('selected')){
                row.removeClassName('selected');
            }
        });



    }else{
        var orows = table.getElementsByClassName('odd');
        orows.each(function(item){
            item.removeClassName('confirm');
        });

        var erows = table.getElementsByClassName('even');
        erows.each(function(item){
            item.removeClassName('confirm');
        });
    }
}


var currentRollOver;
var t; //setTimout var
var s; //synopsis div element
var lo; //left position offset for synopsis
var to; //top position offset for synopsis

function setupRo(el, div, t, l){
    currentRollOver = el;
    st = div;
    to = t;
    lo = l;
}

function showSynopsis(){
    var p = Position.cumulativeOffset($(currentRollOver).up(0));
    var d = $(currentRollOver).getDimensions();
    $(st).show();
    if(st == 'roLgeLeft'){
        $(st).setStyle({top: p[1]-to+'px', left: (p[0]+d.width+lo)+'px'});
    }else{
        $(st).setStyle({top: p[1]-to+'px', left: (p[0]-lo)+'px'});
    }
}
function toggleOrder(){
    spans = $('moviesContent').getElementsByClassName('order');
    spans.each(function(s){
        s.toggle();
    });
    inputs = $('moviesContent').getElementsByClassName('orderInput');
    inputs.each(function(i){
        i.toggle();
    });
    $('buttons').toggle();
    $('btm').toggle();
}
function updateDialogue(el, txt){
    $(el).down('.replaceable').innerHTML = 'Remove: "' + txt + '"';
}

function clearText(thefield){
    if (thefield.defaultValue==thefield.value)
        thefield.value = ""
        $('who').className = "myacnameOn";
        $('date').className = "myacnameOn";
}


// Rewrite of showRollover to also update divs - Erhan

function showRolloverUpdateData(title, id, synopsis, directors, actors, genres, classification){
        var bodyWidth = document.body.offsetWidth;
        var p = Position.cumulativeOffset($(currentRollOver));
        if(p[0] < (bodyWidth/2)){
           updatePopupLeft(title, id, synopsis, directors, actors, genres, classification);
                $('roLgeLeft').show();
                $('roLgeLeft').setStyle({top: (p[1]-50)+'px', left: (p[0]+110)+'px'});
        }else{
           updatePopupRight(title, id, synopsis, directors, actors, genres, classification);
                $('roLgeRight').show();
                $('roLgeRight').setStyle({top: (p[1]-50)+'px', left: (p[0]-320)+'px'});
        }
        s.events = "event14";
        s.eVar35 = "Rollover"
        var s_code=s.t();
        if(s_code)document.write(s_code);
}

// Rewrite of showSynopsis to also update divs - Erhan
function showSynopsisUpdateData(title, id, synopsis, directors, actors, genres, classification){
        var p = Position.cumulativeOffset($(currentRollOver).up(0));
        var d = $(currentRollOver).getDimensions();
        $(st).show();
        if(s == 'roLgeLeft'){
           updatePopupLeft(title, id, synopsis, directors, actors, genres, classification);
                $(st).setStyle({top: p[1]-to+'px', left: (p[0]+d.width+lo)+'px'});
        }else{
           updatePopupRight(title, id, synopsis, directors, actors, genres, classification);
                $(st).setStyle({top: p[1]-to+'px', left: (p[0]-lo)+'px'});
        }
}

// Preferences Page:
// Validate the dvd limit above their plan
function validateLimit(thisform)
{
    // Run through dvdlimit radio buttons and find which one is checked
    for (i=thisform.dvdlimit.length-1; i > -1; i--) {
        if (thisform.dvdlimit[i].checked) {
            myOption = i; i = -1;
        }
    }
    // if dvdlimit value is 2, then we required a LIMIT
    if (thisform.dvdlimit[myOption].value == '2') {
        // If limit is empty, then give alert error and focus them back on the field.
        if (thisform.limit.value==null|| thisform.limit.value=="") {
            alert('You are required to supply a DVD limit for extra DVDs above your plan');
            thisform.limit.focus();
            return false;
        }
        else if (thisform.limit.value > 99) {
            alert('Please note the field for extra DVD to be sent above your plan must be a number between 1 and 99.');
            return false;
        }
        else {
            return true;
        }
    }
    else {
        return true;
    }
}

function toggleLayer(whichLayer, display)
{
    display = typeof(display) != 'undefined' ? display : '';

    if (document.getElementById)
    {
        // this is the way the standards work
        var style2 = document.getElementById(whichLayer).style;
    }
    else if (document.all)
    {
        // this is the way old msie versions work
        var style2 = document.all[whichLayer].style;
    }
    else if (document.layers)
    {
        // this is the way nn4 works
        var style2 = document.layers[whichLayer].style;
    }

    // If argument for display hasnt been set
    if (display == '') {
        style2.display = style2.display == "inline" ? "none" : "inline";
    }
    else {
        style2.display = display;
    }
}

// This will warn the user if they have a pending user request already
function warnPendingRequest(type)
{
    if (type.length > 0) {
        type = type.replace('_', ' ');
        return confirm('This will cancel your previous ' + type + ' request.\nAre you sure?');
    }
    else {
        return true;
    }
}

// This function will check to see if they will occur an ETC
// If they do they will be given a warning
function planWarn(thisform, currentType, requestType, str)
{
    for (i=thisform.change.length-1; i > -1; i--) {
        if (thisform.change[i].checked) {
            changeOption = i; i = -1;
        }
    }

    for (i=thisform.plan.length-1; i > -1; i--) {
        if (thisform.plan[i].checked) {
            planOption = i; i = -1;
        }
    }

    dealId = thisform.plan[planOption].value;
    if (changeOption) {
        change = thisform.change[changeOption].value;
    }
    planRequestType = document.getElementById('type' + dealId);

    // If they have selected a plan and a change type
    if (dealId && change) {
        if (change == 'changeNow' && currentType == 'contract' && planRequestType.value != 'contract')
        {
            rs = confirm(str);
            if (!rs)
                return false;
        } else {
            rs = true;
        }

        // If they clicked ok, warn about pending request, if there is on
        if (rs) {
            return warnPendingRequest(requestType);
        }
    }

    return true;
}

function updateAddress(frm)
{
    var tmp1 = frm.suggestions.value.split(', ');
    var cnt1 = tmp1.length;

    if (cnt1 > 1)
    {
        var tmp2 = tmp1[1].toString().split(' ');
        var cnt2 = tmp2.length;

        // Address
        frm.address.value = tmp1[0];
        frm.address2.value = '';

        // Postcode
        frm.postcode.value = tmp2[cnt2-1];

        // State
        frm.state.value = tmp2[cnt2-2];

        // Remove state and postcode so all we are left with is the suburb
        tmp2.splice(cnt2-2, 2);

        // Suburb
        suburb = tmp2.toString();
        frm.city.value = replaceChar(suburb, ',', ' ');

        updateField('qasUsed', 1);
    }
}

function updateField(name, value)
{
    $(name).value = value;
}

/* Replace a character in a string */
function replaceChar(str, chr, replace)
{
    var tmp = '';

    str = str.split('');
    for(i=0;i<str.length;i++)
    {
        if (str[i] == chr)
        {
            tmp += replace;
        } else {
            tmp += str[i];
        }
    }

    return tmp;
}


function movieReview(id) {
    $('reviewRatings').innerHTML = $('reviewRatings' + id).innerHTML
    $('reviewMovieTitle').innerHTML = $('reviewTitle' + id).innerHTML
    $('reviewDate').innerHTML = $('reviewDate' + id).innerHTML
    $('reviewBy').innerHTML = $('reviewBy' + id).innerHTML
    $('reviewText').innerHTML = $('reviewText' + id).innerHTML
    showBox('movieReview');
}

function handlePassword()
{
    $('pwd2').value = hex_md5($('pwd').value);
    $('pwd1').value = hex_sha1(hex_sha1($('pwd').value + $('salt').value) + $('salt2').value);
    $('pwd').value = '';
}

function searchChangeTab (t, n) {
    for(i = 1; i <= t; i++){
        $('tab'+i+'-left').className = 'left-tab';
        $('tab'+i+'-text').className = 'text';
        $('tab'+i+'-right').className = 'right-tab';
    }

    $('tab'+n+'-left').className = 'left-tab selectedLeft';
    $('tab'+n+'-text').className = 'text selected';
    $('tab'+n+'-right').className = 'right-tab selectedRight';

}

/* attention box - displayed when movie doesn't meet rental preferences
 * type         1 = Rental, 2 = Format, 3 = Both rental and format, 4 = type 3 + bonus
 * preference   movie preference to warn about
 */
function attention(rental, format, bonus, preference)
{
    var warning = '';
    var text    = '';

    // Warning message
    if (preference == null) {
        warning = "You have selected a disc that doesn't meet your rental preferences";
    }
    else {
        warning = 'You have selected a ' + preference;
    }

    // Text to go under warning message
    if (format) {
        text = 'This disc might not work properly on your Television / DVD player.<br />';
    }
    if (rental) {
        text += 'Check the movie details to find out more';
    }


    // if bonus aswe
    if ((rental || format) && (bonus)) {
        text += '<br /><span class="warning" style="font-size:14px; font-weight: bold; line-height: 1.4em;">This disc is also a bonus disc</span>';
    }

    $('attentionWarning').innerHTML = warning;
    $('attentionText').innerHTML    = text;
    showBox('attention');

}

document.getElementsByClassName = function(cl) {
    var retnode = [];
    var myclass = new RegExp('\\b'+cl+'\\b');
    var elem = this.getElementsByTagName('*');

    for (var i = 0; i < elem.length; i++) {
        var classes = elem[i].className;
        if (myclass.test(classes))  {
            retnode.push(elem[i]);
        }
    }
    return retnode;
};


function queueDisplay(id)
{
    var classNames = document.getElementsByClassName('priority' + id);

    for (i=0; i<classNames.length; i++) {
        var el = classNames[i];
        var currentDisplay = typeof($(el).style.display) != 'undefined' ? $(el).style.display : '';

        class_name = (currentDisplay == "" ? "Down" : "Up");

        $(el).style.display = (currentDisplay == "" ? "none" : "");
        $('queueLink' + id).className = 'FilterSelected' + class_name;
    }
}

/**
 * Marks all group movies for or not for removal according to the first movie in the list.
 * Only works when the list is collapsed.
 *
 */
function MarkForRemoval(id, flag)
{
    var classNames = document.getElementsByClassName('priority' + id);

    for ( i = 0; i < classNames.length; i++ ) {
        var el = classNames[i];

        var currentDisplay = typeof($(el).style.display) != 'undefined' ? $(el).style.display : '';
        class_name = (currentDisplay == "" ? "Down" : "Up");

        if ( class_name == 'Up') {
            var chk = el.getElementsByTagName('input');
            chk[0].checked = flag;
        }
    }
}

function scrollNext(direction, pageLoaded, numberOfComps) {
    var newPageLoaded = 1;
    if(direction == "forward") {
        if(pageLoaded < numberOfComps) {
            $("comp_" + pageLoaded ).style.zIndex="2";
            $("comp_" + (parseInt(pageLoaded) + 1) ).style.zIndex="1";
            Effect.Fade("comp_" + pageLoaded, { duration: 0.5 });
            Effect.Appear($("comp_" + (parseInt(pageLoaded) + 1) ), { duration: 0.5 });
            newPageLoaded = parseInt(pageLoaded) + 1;
        } else {
            $("comp_" + pageLoaded ).style.zIndex="2";
            $("comp_1").style.zIndex="1";
            Effect.Fade("comp_" + pageLoaded , { duration: 0.5 });
            Effect.Appear($("comp_1"), { duration: 0.5 });
             newPageLoaded = 1;
        }
    } else {
        if(pageLoaded == 1) {
            $("comp_" + pageLoaded).style.zIndex="2";
            $("comp_" + numberOfComps).style.zIndex="1";
            Effect.Fade("comp_" + pageLoaded, { duration: 0.5 });
            Effect.Appear($("comp_" + numberOfComps), { duration: 0.5 });
            newPageLoaded = numberOfComps;
        } else {
            $("comp_" + (parseInt(pageLoaded) - 1)).style.zIndex="2";
            $("comp_" + pageLoaded).style.zIndex="1";
            Effect.Fade("comp_" + pageLoaded, { duration: 0.5 });
            Effect.Appear($("comp_" + (parseInt(pageLoaded) - 1)), { duration: 0.5 });
            newPageLoaded = parseInt(pageLoaded) - 1;
        }
    }
    $('cPageLoaded').value = newPageLoaded;
}

function createPeriodicalExecuter(numberOfComps)
{
    compRefresh = new PeriodicalExecuter(function() { scrollNext('forward', $('cPageLoaded').value , numberOfComps)}, 3)
}
