
function writeError(str, clear)
{
    var dbgObj = document.getElementById("debug_content_js");

    str = str.replace('\n', '<br />\n');

    if (clear) {
        dbgObj.innerHTML = '';
    } 

    var now = new Date();
    var ts = now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds();

    dbgObj.innerHTML += ts + ': ' + str + '<br />\n';
}

/* JS function for NAV menu */
startList = function() {
    if (document.all && document.getElementById) {
        navRoot = document.getElementById("nav_main");
        if (navRoot) {
            for (i=0; i<navRoot.childNodes.length; i++) {
                node = navRoot.childNodes[i];
                if (node.nodeName=="LI") {

                    node.onmouseover=function() {
                        this.className+=" over";
                    }
                    node.onmouseout=function() {
                        this.className=this.className.replace(" over", "");
                    }
                }
            }
        }
    }
}

function enroll(dealerid, language) {
	url = 'https://backoffice.youniquewealth.com/MemberToolsDotNet/EnrollmentNew/StartPublicEnrollment.aspx';
    if (dealerid) {
        url = url + '?referringdealerid=' + dealerid;
    }
    /*
    if (language) {
        url = url + '&countryid=' + language;
    }
    */
	opts = 'resizable=yes,status=yes,scrollbars=yes,width=1000,height=700';
	firstchild = window.open(url, 'enrollchild', opts);  
    return false;
}

function shop(dealerid, catid, prodid) {
    
    url = 'https://backoffice.youniquewealth.com/MemberToolsDotNet/ShoppingCartNew/StartPublicShopping.aspx';
    qs = '';
    if (dealerid) {
        qs += 'referringdealerid=' + dealerid;
    }
    if (catid) {
        if (qs != '') {
            qs += '&';
        }
        qs += 'CatalogueID=' + catid;
    }
    if (prodid) {
        if (qs != '') {
            qs += '&';
        }
        qs += 'ProductID=' + prodid;
    }
    if (qs != '') {
        url += '?' + qs;
    }
    return display_shop( url ); 
}

function display_shop( url )
{
    opts = 'resizable=yes,status=yes,scrollbars=yes,width=1000,height=700';
    firstchild = window.open(url, 'shopchild', opts);
    return false;
}

function display_ytvideo( url )
{
    opts = 'toolbar=0,location=0, directories=0,status=0,resizable=no,status=yes,scrollbars=no,width=440,height=400';
    firstchild = window.open(url, 'ytpopup_window', opts);
    
    return false;
}

function backoffice_login(language) {
	url = 'https://backoffice.youniquewealth.com/MemberToolsDotNet/FirestormLogin.aspx';
    /*
    if (language) {
        url = url + '?countryid=' + language;
    }
    */
	opts = 'resizable=yes,status=yes,scrollbars=yes,width=1180,height=700';
	firstchild = window.open(url, 'backofficechild', opts);  
}

function form_open(formname) {
	url = 'https://secure.anglofareast.com/form.php?page=' + formname;
	opts = 'resizable=yes,status=yes,scrollbars=yes,width=800,height=580';
	firstchild = window.open(url, 'formchild', opts);  
}

function pdf_open(pdfname, language) {
    if (!language) {
        language = "en";
    }
    url = language + '/pdf/' + pdfname;
	opts = 'resizable=yes,status=yes,scrollbars=yes,width=800,height=580';
	firstchild = window.open(url, 'pdfchild', opts);  
}

function window_open(url) {
	opts = 'resizable=yes,status=yes,scrollbars=yes,width=900,height=600';
	firstchild = window.open(url, '', opts);  
}

function popup_open(element, width, height) {
    if (! width) {
        width = 575;
    }
    if (! height) {
        height = 500;
    }
    url = 'popup.php?e=' + element;
	opts = 'resizable=no,status=no,scrollbars=yes,width=' + width + ',height=' + height;
	firstchild = window.open(url, '', opts);  
}

function popup_url(url, width, height) {
    if (!width) {
        width = 575;
    }
    if (!height) {
        height = 500;
    }

    opts = 'resizable=no,status=no,scrollbars=yes,width=' + width + ',height=' + height;
    firstchild = window.open(url, '', opts);  
}

function video_play(stream, mode, location, mywidth, myheight) {
    url = 'player/video_player.php?stream=' + stream;
    width = 550;
    height = 350;
        
    if (mode) { 
        url = url + '&mode=' + mode; 
    }
    if (location) { 
        url = url + '&location=' + location; 
    }
    if (mywidth) { 
        width = mywidth;
    }
    if (myheight) { 
        height = myheight;
    }
	opts = 'resizable=yes,status=no,scrollbars=no,width=' + width + ',height=' + height;
	firstchild = window.open(url, '', opts);  
}

function video_show( title, width, height, div )
{
    var win = dhtmlwindow.open('popupbox', 'div', div, title, 
        'width='+width+',height='+height+',resize=0,scrolling=0,center=1');
    return win;
}

function video_popup( url, width, height, video )
{
    url = url + '&video=' + video; 
    opts = 'resizable=yes,status=no,scrollbars=no,width='+width+',height='+height;
    firstchild = window.open(url, '', opts);  
}

function show_popup(div, title, width, height)
{
    var win = dhtmlwindow.open('popupbox', 'div', div, title, 
        'width='+width+',height='+height+',resize=1,scrolling=1,center=1');
    return win;
}

function hiddenDivShow( title, width, height, div )
{
    return show_popup(div, title, width, height);
}

function track_event(tag, arg1, arg2) {
    objXMLHttp = getXmlHttpObject();
    objXMLHttp.onreadystatechange = evalRespons;
    qs = 'tag=' + tag;
    if (arg1) {
        qs = qs + '&arg1=' + arg1;
    }
    if (arg2) {
        qs = qs + '&arg2=' + arg2;
    }
    objXMLHttp.open("GET","/track.php?"+qs, false);
    objXMLHttp.send(null);
}

function evalRespons(){
    if(objXMLHttp.readyState==4 ){
        eval(objXMLHttp.responseText)
    }
}

function getXmlHttpObject(){
    var objXMLHttp=null;
    if (window.XMLHttpRequest){
        objXMLHttp=new XMLHttpRequest();
    }
    else if (window.ActiveXObject){
        objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    return objXMLHttp;
}

function initall() {
     
     initDHTMLAPI();
     startList();
     if(typeof fadeDiv == 'function') { 
        fadeDiv( 'winners', 'prizes' );
     }
     
     if (typeof $('#slideshow1').cycle == 'function') {
         $('#slideshow1').cycle({
            timeout:       5000,  // milliseconds between slide transitions (0 to disable auto advance) 
            speed:         1000,  // speed of the transition (any valid fx speed value) 
            next:          null,  // id of element to use as click trigger for next slide 
            prev:          null,  // id of element to use as click trigger for previous slide 
            before:        null,  // transition callback (scope set to element to be shown) 
            after:         null,  // transition callback (scope set to element that was shown) 
            height:       'auto', // container height 
            sync:          1,     // true if in/out transitions should occur simultaneously 
            fit:           0,     // force slides to fit container 
            pause:         0,     // true to enable "pause on hover" 
            delay:         0,     // additional delay (in ms) for first transition (hint: can be negative) 
            slideExpr:     null   // expression for selecting slides (if something other than all children is required) 
         });
     }

     if (typeof $('#slideshow2').cycle == 'function') {
         $('#slideshow2').cycle({
            timeout:       5000,  // milliseconds between slide transitions (0 to disable auto advance) 
            speed:         1000,  // speed of the transition (any valid fx speed value) 
            next:          null,  // id of element to use as click trigger for next slide 
            prev:          null,  // id of element to use as click trigger for previous slide 
            before:        null,  // transition callback (scope set to element to be shown) 
            after:         null,  // transition callback (scope set to element that was shown) 
            height:       'auto', // container height 
            sync:          1,     // true if in/out transitions should occur simultaneously 
            fit:           0,     // force slides to fit container 
            pause:         0,     // true to enable "pause on hover" 
            delay:         0,     // additional delay (in ms) for first transition (hint: can be negative) 
            slideExpr:     null   // expression for selecting slides (if something other than all children is required) 
         });
     }
     
     if(typeof dealer_analytics == 'function') { 
        dealer_analytics();
     }
     if(typeof eventCountDown == 'function') { 
        eventCountDown();
     }
     if(typeof dateInYourTime == 'function') { 
        dateInYourTime();
     }
     if(typeof callInYourTime == 'function') { 
        callInYourTime();
     }
     if( typeof websettings == 'function') {
        websettings();
     }
     if( typeof youniquetube_play == 'function') {
        youniquetube_play();
     }
     if( typeof capture_shop_clicks == 'function') {
        capture_shop_clicks();
     }
     if( typeof youtube_video_popup == 'function') {
         youtube_video_popup();
     }
}

// This function is not used
function insertFlashVideo()
{
    $(document).ready(
        function () {
            $( '#videoplayer1' ).flash({
                swf: 'player/FLVPlayer_fcs.swf',
                expressInstaller: 'player/expressInstall.swf',
                params: {
                    wmode: 'transparent',
                    autoPlay: 'false',
                    autoRewind: 'true'
                },
                flashvars: {
                    bgColor: '0xffffff',
                    skinName: 'player/skins/haloSkin_3',
                    bufferTime: '3',
                    serverName: 'xstream.voice.net.au',
                    appName: 'anglofar',
                    streamName: 'GWV1.13_r18'
                },
                height: 350,
                width: 570
            });   
        }
    );
}

// global settings variable for the animation classes
var settings                             = Array(2);
    settings['fader']                    = Array(1);
    settings['fader']['winners']         = Array(1);
    settings['fader']['winners']['cur']  = 0;
    
    // global settings for the headline switcher
    settings['switch']             = Array(1);
    settings['switch']['headline'] = Array(4);
    
    settings['switch']['headline']['headline_count']    = null;
    settings['switch']['headline']['headline_interval'] = null;
    settings['switch']['headline']['current_headline']  = 0;
    settings['switch']['headline']['old_headline']      = 0;

    function fadeDiv(divName, className )
    {
        var boxes = Array(4);
            boxes[0] = 'box1';
            boxes[1] = 'box2';
            boxes[2] = 'box3';
            boxes[3] = 'box4'

        if( $('.'+className).length > 0 )
        {
            setInterval(function(){doAnimate( boxes , divName ); } , 3000);
        }
    }

    doAnimate = function( boxes, divName )
    {
        curr = settings['fader'][divName]['cur'];

        if( curr == 0 )
        {
            $('#'+boxes[curr]).fadeIn('fast');
        }
        $('#'+boxes[curr]).fadeOut('slow',function(){
            if( curr+1 < boxes.length )
            {
               $('#'+boxes[curr+1]).fadeIn('fast');
               settings['fader'][divName]['cur']++;
            }
            else
            {
               $('#'+boxes[0]).fadeIn('fast');
               settings['fader'][divName]['cur'] = 0;
            }
        });
    }
        
    function switchHeadline( className )
    {
        $(document).ready(function(){
        
        settings['switch'][className]['headline_count'] = $("li."+className).size();
        
        $("li."+className+":eq(" + settings['switch'][className]['current_headline'] + ")").css('top', '5px');
            settings['switch'][className]['headline_interval'] = setInterval(function(){
                headline_rotate(className);
                },3600);
        });
            
    }
    function headline_rotate( className )
    {
       settings['switch'][className]['current_headline'] = 
           (settings['switch'][className]['old_headline'] + 1) % settings['switch'][className]['headline_count'];
       $("li."+className+":eq(" + settings['switch'][className]['old_headline'] + ")").animate({top: -205},"slow");
       $("li."+className+":eq(" + settings['switch'][className]['old_headline'] + ")").animate({top: -205},"slow", function(){
            $(this).css('top', '210px');
        });

         $("li."+className+":eq(" + settings['switch'][className]['current_headline'] + ")").animate({top: 5},"slow"); 
            settings['switch'][className]['old_headline'] = settings['switch'][className]['current_headline'];
    }


function noop() 
{
}

var popup = null;

$(document).ready(
    function() {

        // Capture click events for all the elements that launch a dhtmlwindow

        $('.dhtml').click( 
            function() {
                var divId         = $(this).attr('jws:divid');
                var iframeURL     = $(this).attr('jws:iframeURL');
                var windowTitle   = $(this).attr('jws:windowtitle');
                var windowWidth   = $(this).attr('jws:width');
                var windowHeight  = $(this).attr('jws:height');
                var id            = $(this).attr('id');
                var retval        = $(this).attr('jws:retval');
                var optResizable  = $(this).attr('jws:resizable');
                var optScrollbars = $(this).attr('jws:scrollbars');
                var optCenter     = $(this).attr('jws:center');
                
                opts = '';
                if (optResizable) {
                    opts += ',resize=' + optResizable;
                }
                else {
                    opts += ',resize=1'
                }
                if (optScrollbars) {
                    opts += ',scrolling=' + optScrollbars;
                }
                else {
                    opts += ',scrolling=1'
                }
                if (optCenter) {
                    opts += ',center=' + optCenter;
                }
                else {
                    opts += ',center=1'
                }
                if (! windowTitle) {
                    // Fall back to standard HTML title attribute
                    windowTitle = $(this).attr('title');
                }
                if (windowWidth) {
                    opts += ',width=' + windowWidth + 'px';
                }
                if (windowHeight) {
                    opts += ',height=' + windowHeight + 'px';
                }

                if( divId )
                {
                    // display a hidden div in a dhtml window
                    dhtmlwindow.open('popupbox', 'div', divId, windowTitle, opts);
                }
                else
                {
                    if( iframeURL )
                    {
                        popup = dhtmlwindow.open( id+"newwindow", 'iframe', iframeURL, windowTitle, opts, 'recal');
                    }
                }
                
                if (retval > 0) {
                    return true;
                }
                else {
                    return false;
                }
            }
        );

        // Capture click events for all the elements that launch a new browser window

        $('.windowopen').click( 
            function() {
                var URL           = $(this).attr('jws:url');
                var windowWidth   = $(this).attr('jws:width');
                var windowHeight  = $(this).attr('jws:height');
                var windowName    = $(this).attr('jws:windowname');
                var windowTitle   = $(this).attr('jws:windowtitle');
                var optResizable  = $(this).attr('jws:resizable');
                var optScrollbars = $(this).attr('jws:scrollbars');
                var optStatus     = $(this).attr('jws:status');
                
                if( URL )
                {
                    opts = 'location=0';
                    if (optResizable) {
                        opts += ',resizable=' + optResizable;
                    }
                    if (optScrollbars) {
                        opts += ',scrollbars=' + optScrollbars;
                    }
                    if (optStatus) {
                        opts += ',status=' + optStatus;
                    }
                    if (windowWidth) {
                        opts += ',width=' + windowWidth;
                    }
                    if (windowHeight) {
                        opts += ',height=' + windowHeight;
                    }
                    child = window.open(URL, windowName, opts);  
                }
                
                return false;
            }
        );

        $('.hover').mouseover( 
            function() {
                var hoverMessage  = $(this).attr('jws:hovermessage');
                var hoverWidth   = $(this).attr('jws:hoverwidth');
                var hoverHeight  = $(this).attr('jws:hoverheight');
                
                if (! hoverWidth) {
                    hoverWidth = 220;
                }
                if (! hoverHeight) {
                    hoverHeight = 20;
                }

                if( hoverMessage )
                {
                    showtrail(hoverWidth, hoverHeight, hoverMessage);
                }
                
                return true;
            }
        );

        $('.hover').mouseout( 
            function() {
                var hoverMessage  = $(this).attr('jws:hovermessage');

                if( hoverMessage )
                {
                    hidetrail();
                }
                
                return true;
            }
        );

        // Handle hover events on filstrip images
        $('.video').mouseover( 
            function() {
                if ($(this).attr('jws:thumbnail')) {
                    var thumbnail = $(this).attr('jws:thumbnail');
                    $(this).css('background-image', 'url(../images/video/' + thumbnail + '_hover.jpg)');
                    return true;
                }
            }
        );

        $('.video').mouseout( 
            function() {
                if ($(this).attr('jws:thumbnail')) {
                    var thumbnail = $(this).attr('jws:thumbnail');
                    $(this).css('background-image', 'url(../images/video/' + thumbnail + '.jpg)');
                    return true;
                }
            }
        );

        /*
        $(".video").each( function(){
            if ($(this).attr('jws:thumbnail')) {
                var thumbnail = $(this).attr('jws:thumbnail');
                $(this).css('background-image', 'url(../images/video/' + thumbnail + '.jpg)');
            }
        });
        */

        /* Auto submit the language selector */
        $(document).ready(function() {
            $('.auto_submit > .submit ').css('display','none');
            $('.auto_submit > #language_select ').change(function(){
                $(this).parent().submit();
            });
        });
    }
);
    
// capture clicks to display shop links
capture_shop_clicks = function(){
  if( $('.shop').length > 0 )
  {
    $('.shop').click(function(){
        var href = $(this).attr('href');
        if( href )
        {
            display_shop( href );            
        }        
    });    
  }    
};


 
// capture clicks to display a country 
showCountry = function( cc ) {
            
   var y = $("dl#worldMap dd");

   y.each( function(){
       $(this).removeClass('selected'); 
       var p = $(this).children('a');
       p.removeClass('selected');
       p.children('span').removeClass('selected');
   });
    
    var x = $('dd#'+cc);
    x.focus();
    x.addClass('selected');
    $('a#'+cc+'link').addClass('selected');
    $('span#'+cc+'span').addClass('selected');
    $('a#'+cc+'link').focus( );
    $('a#'+cc+'link').css("z-index:999");

    y.each( function(){
        var p = $(this).children('a');
        p.css('z-index:999');
    }); 

    return false;
};


// capture clicks to display youtube links
// in a popup window
youtube_video_popup = function(){
    
    if( $('.ytpopup').length > 0 )
    { 
        $('.ytpopup').click(function(){
            var href = $(this).attr('href');

            // Get the youtube id from the link
            var regexp = new RegExp("v=(.*)");
            
            var ytid = regexp.exec( href );

            if( ytid[1] )
            {
                href = '/?page=video_popup&ytid='+ytid[1];
                display_ytvideo( href );
                return false;
            }
        });
    }
    return false;
};


youniquetube_play = function()
{
    
    if( $("div.yt_video").length > 0 )
    {
        $("div.yt_video > a").click(function() {
            if( $(".ytselected").length > 0 )
            {
                $(".ytselected").removeClass("ytselected");
                $(".ytselected_div").removeClass("ytselected_div");
            }
            var ytID = $(this).children("img").attr('id');
            var title = $(this).siblings("div.yt_caption").text();
            $(this).addClass("ytselected");
            $("div#container_"+ytID).addClass('ytselected_div');
            
            
            // get the youtube object
            ytplayer = document.getElementById("youniquetube_swf");            
            ytplayer.stopVideo();
            ytplayer.clearVideo();
            ytplayer.loadVideoById( ytID );            
            ytplayer.playVideo();
            
            $("#yt_top_title").text("Current Selection: " + title);
            
          return false;
        });
    }
    return false;
}

// Setup event handlers on the web settings page
websettings = function()
{   
    if( $("form#settings") )
    {
        $("input").change(function() { 
            // Let user know action is required
            $("input#settings_submit").addClass('needsaction');
        });

        $("div#bigday_themes > img").click(function() { 
            
            $(this).siblings().each( function() {
                if( $(this).hasClass('selected') )
                {
                    $(this).toggleClass('selected');
                }
            });

            var id = $(this).attr('id');
            
            $(this).addClass( "selected" );
        
            $("select#bigday_theme_selector option").each(function(){

                if( $(this).attr('value') == id )
                {
                    $(this).attr('selected', 'selected'); 
                }
            });

            // Let user know action is required
            $("input#settings_submit").addClass('needsaction');
        });
        
        $("#bigday_theme_selector > option").click(function(){
                var val;
                $(this).siblings().each( function(){
                    val = $(this).attr('value');
                    $('img#'+val).removeClass('selected');
                });
                if( $(this).attr('selected') )
                {
                    
                    val = $(this).attr('value');
                    $('img#'+val).toggleClass('selected');
                }
        });

        // Also show the submit button if user manually changes the select
        $("select#bigday_theme_selector").change(function(){
            // Let user know action is required
            $("input#settings_submit").addClass('needsaction');
        });

        $("div#bigday_text_options p").click(function() { 
            
            $(this).parent().siblings().each( function() {
                if( $(this).hasClass('selected') )
                {
                    $(this).toggleClass('selected');
                }
            });

            var id = $(this).attr('id');
            var regexp = new RegExp("[0-9]");
            var xyz = regexp.exec( id );
            
            $(this).parent().addClass( "selected" );
            
            $("select#bigday_text_selector option").each(function(){
                if( $(this).attr('value') == xyz )
                {
                    $(this).attr('selected', 'selected'); 
                }
            });

            // Let user know action is required
            $("input#settings_submit").addClass('needsaction');

        });

        // handle the situation where the user clicks on the dropdown button
        $("#bigday_text_selector > option").click(function(){
            var val;
            $(this).siblings().each( function(){
                val = $(this).attr('value');
                $('#wrapper'+val).removeClass('selected');
            });
            if( $(this).attr('selected') )
            {
                val = $(this).attr('value');
                $('#wrapper'+val).toggleClass('selected');
            }
        });

        // Highlight the submit button if user manually changes the select
        $("select#bigday_text_selector").change(function(){
            $("input#settings_submit").addClass('needsaction');
        });

        // Highlight the submit button if user manually changes the select
        $("input#bigday_active").change(function(){
            $("input#settings_submit").addClass('needsaction');
        });
    }
}            


$(document).ready(function(){
    // remove scrollbar
    var viewPort = $('#carousel');
    viewPort.css({overflow: 'hidden'});
    
    //enable nav buttons
    $('#navNext').removeClass('hidden');
    $('#navPrev').removeClass('hidden');
    
    
    // get viewport size        
    var viewPortSize = viewPort.width();
    
    // get total width of children
    var totalChildWidth = getWidthOfChildren();
    

    $('ul',viewPort).width(totalChildWidth);
  
    var count = 0;   
    $('#navNext').click(function(){

    
        $('#navPrev').removeClass('grey');
         
        // get pixels to the left of the viewport
        var totalLft = parseInt( viewPort.scrollLeft());

        
        // scroll to next image 
        var next = getWidth( $('#carousel ul li:first') );

        // get position of last element
        var lastPos = $( 'ul li:last', viewPort).position().left;
        
        // make sure that the last childs position still has enough room
        // left to scroll.
        if( lastPos > viewPortSize )
        {
            viewPort.scrollLeft( totalLft + next );
            count++;
            console.log( count + "left ");
        }
        else
        {        
            $(this).addClass('grey');        
        }

    });
    
    $('#navPrev').click(function(){

        
        $('#navNext').removeClass('grey');
         
        // get pixels to the left of the viewport
        var totalLft = parseInt( viewPort.scrollLeft());
    
        // this really should be dynamic.
        var next = getWidth( $('#carousel ul li:first') );

        // get position of last element
        var firstPos =  $( 'ul li:first', viewPort).position().left;
        
        // make sure that the last childs position still has enough room
        // left to scroll.
        if(count > 0 )
        {
            viewPort.scrollLeft( totalLft - next );
            count--;
            console.log( count + "left ");
        }
        else
        {        
            $(this).addClass('grey');        
        }

    });
    
});


    
/**
 * Get the entire width of an image
 *
 */
function getWidth( obj )
{
    return parseInt(obj.outerWidth(true));    
}

function getWidthOfChildren( ){
    var total = 0;    
    $('#carousel ul li img').each(function(){
        total += getWidth( $(this) );
        total += 2;
    });
    return total ;
}

window.onload = initall;
// window.onunload = dhtmlwindow.cleanup






