// Start the init functions here
$(document).ready(function() {
    removeGoButton();
    dateInYourTime();
    dhtmlHandler();
    windowopenHandler();
    youniquetube_play();
    showCountry();
    eventCountDown();
    dateInYourTime();
    carousel();
    websettings();
	slideshow1();
    googleAnalytics();
    flowplayer_init();
    sevensteps_clear();

    if ($('.tooltip').length) {
        $('.tooltip').tipsy({html: true });
    }
});

function removeGoButton()
{
   $('.auto_submit > .submit ').css('display','none');
   $('.auto_submit > #language_select ').change(function(){
        $(this).parent().submit();
   });
}
//Landing Page slideshow
function slideshow1(){
			$('#slideshow').slideshow({
				timeout: 5000,
				type: 'sequence',
				pauselink: 'pause1',
				pausecallback: function(self){
					self.html('Play')
				},
				playcallback: function(self){
					self.html('Pause');
				}
			});	
	}

function dhtmlHandler() {
    // 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 )
                {
                    iframeURL = $(this).attr('href');
                }
                popup = dhtmlwindow.open( id+"newwindow", 'iframe', iframeURL, windowTitle, opts, 'recal');
            }
            
            if (retval > 0) {
                return true;
            }
            else {
                return false;
            }
        }
    );
}

function windowopenHandler() {
    
    // Capture click events for all the elements that launch a new browser window
    $('.windowopen').click( 
        function() {
            var URL           = $(this).attr('jws:url');
            
            // if we don't have it try the regular href
            if( !URL ){
                URL = $(this).attr('href');
            }
            
            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');
            
            // set a fallback width
            if( !windowWidth ) {
                windowWidth = '575';
            }
            if(!windowHeight ) {
                windowHeight = '500';
            }
            // scroll by default
            if(!optScrollbars ) {
                optScrollbars = 'yes';
            }
            
            
            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;
        }
    );
}

/**
* Capture clicks to display youtube links
* in a popup window
* 
*/
function youtube_video_popup(){
    
    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;
};

// capture clicks to display a country 
function showCountry( e ) {
     
     $('a.showcountry').mouseover( function(){
        var id    = $(this).attr('id');
        var parts = id.split( '-' ,2);
        var cc    = parts[1];
        
        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');
        var tmp = $('a#link-'+cc+'');
        tmp.addClass('selected');
        $('span#'+cc+'span').addClass('selected');
        tmp.focus( );
        tmp.css("z-index:999");

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

    return false;
};


/**
 * Play a youtube video 
 * 
 */
function youniquetube_play()
{
    
    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();
            
            $("h4#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');
        });

        $("textarea").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');
                }
        });

        $("div#ibo_style > img").click(function() {
            
            $(this).siblings().each( function() {
                if( $(this).hasClass('selected') )
                {
                    $(this).toggleClass('selected');
                }
            });
            
            var id = $(this).attr('id');
            
            $(this).addClass( "selected" );
            
            $("select#ibo_style_selector option").each(function(){
                
                if( $(this).attr('value') == id )
                {
                    $(this).attr('selected', 'selected');
                }
            });
            
            // Let user know action is required
            $("input#settings_submit").addClass('needsaction');
        });
        
        $("#ibo_style_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');
        });
    }
}            

function carousel(){
    var noToScroll = 3;

    // Animation speed
    var speed  = 200; // 0 will disable animation
    var easing = 'linear';
    
    // Remove scrollbar
    var viewPort = $('#carousel');
    viewPort.css({overflow: 'hidden'});

    // Enable nav buttons
    $('#navNext').removeClass('disabled');
    $('#navPrev').removeClass('disabled');

    // get viewport size        
    var viewPortSize = viewPort.width();

    // get total width of children
    var totalChildWidth = getWidthOfChildren();

    // the 2 is just some padding. This is just here 
    // so we know when to stop
    $('ul',viewPort).width(totalChildWidth);

    // Make sure the selected item is always in view
    
    $('#navNext').click(function(){
        
        $('#navPrev').removeClass('disabled');
        
        // get pixels to the left of the viewport
        var totalLft = parseInt( viewPort.scrollLeft());
        
        // scroll to next image 
        var next = getWidth( $('#carousel ul li:first') )*noToScroll;
        
        // get position of last element
        var lastPos = $( 'ul li:last', viewPort).position().left;
        
        var totalRight = (totalChildWidth - ( totalLft + viewPortSize ) );

        if( totalRight >= 0 )
        {
            var current = $(this);
            
            // make sure that the last childs position still has enough room
            // left to scroll.
            if( !current.hasClass('disabled') )
            {
                viewPort.animate({ scrollLeft: '+='+parseInt(next)}, speed,easing,function(){
                    totalLft = parseInt( viewPort.scrollLeft());
                    
                    // calculate again so we can work out if the next button should be grey
                    next = getWidth( $('#carousel ul li:first') );
                                    lastPos = $( 'ul li:last', viewPort).position().left;
                                    totalRight = (totalChildWidth - ( totalLft + viewPortSize ) );
                                    
                                    if( totalRight <= next )
                                    {
                                        current.addClass('disabled');
                                    }
                });                
            }

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

        $('#navNext').removeClass('disabled');
        
        // get pixels to the left of the viewport
        var totalLft = parseInt( viewPort.scrollLeft());
        
        // scroll to next image 
        var next = getWidth( $('#carousel ul li:first') )*noToScroll;
        
        // get position of last element
        var lastPos = $( 'ul li:last', viewPort).position().left;
        
        var totalRight = (totalChildWidth - ( totalLft + viewPortSize ) );

        if( totalLft > 0 )
        {
            var current = $(this);
            // make sure that the last childs position still has enough room
            // left to scroll.
            viewPort.animate({ scrollLeft: '-='+parseInt(next)}, speed,easing,function(){
                totalLft = parseInt( viewPort.scrollLeft());

                if( totalLft == 0 )
                {
                    current.addClass('disabled');
                }
            });
            
        }
        return false;
    });
};


/**
 * 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 += 0.5;
    });
    return total ;
}

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 googleAnalytics() {
    try {
        var pageTracker = _gat._getTracker("UA-17924366-1");
        pageTracker._setDomainName('none');
        pageTracker._setAllowLinker(true);
        pageTracker._trackPageview();
    } catch(err) {}

    ga_dealer = $('jws\\\:dealerconfig').attr('jws:ga_account');
    if(ga_dealer)
    {
        // alert(ga_dealer);
        try {
            var pageTracker = _gat._getTracker($('jws\\\:dealerconfig').attr('jws:ga_account'));
            pageTracker._setDomainName('none');
            pageTracker._setAllowLinker(true);
            pageTracker._trackPageview();
        } catch(err) {}
    }
}

function flowplayer_init() {

    if (!$('#player').length) {
        return;
    }

    var fpurl = 'swf/flowplayer.commercial-3.2.7.swf';
    var fpkey = '';
    if (window.location.hostname.match(/youniquegoldtribe.com$/)) {
        fpkey = '#@802df9442145a2e9523'; // youniquegoldtribe.com
    }
    else if (window.location.hostname.match(/youniquewealth.com$/)) {
        fpkey = '#@c773b9e38d9a6a96419'; // youniquewealth.com
    }
    else if (window.location.hostname.match(/goldshop101.com$/)) {
        fpkey = '#@6e66051466ec1de6d76'; // goldshop101.com
    }
    else {
        fpurl = 'swf/flowplayer-3.2.7.swf';
    }

    $f("player", 
    {
        src: fpurl,
        wmode: 'transparent'
    },
    {
        key: fpkey,
        clip: {
            // url: 'mp4:ibo/oppv_01_640x360_crf22',
            provider: 'rtmp',
            bufferLength: '5',
            // autoBuffering: true
            onMetaData:function() 
            {
                // alert('onMetaData');
                // $f().seek(333);
            },
            onStart:function() 
            {
                // alert('onStart');
                // $f().seek(10);
            }
        },
        /*
        playlist: [
            'mp4:training/ness_01_20100925_640x360_crf22',
            'mp4:training/ness_02_20100925_640x360_crf22',
        ],
        */
        plugins: {
            controls: {
                url: 'swf/flowplayer.controls-3.2.5.swf',
                stop: true,
                tooltips: {
                    buttons: false,
                    fullscreen: 'Enter fullscreen mode'
                }
            },
            rtmp: {
                url: 'swf/flowplayer.rtmp-3.2.3.swf',
                netConnectionUrl: 'rtmp://cabernet.voice.net.au/younique'
            }
        }
    });
    
    $f("player").playlist(".playlist", {

        // CSS class name of a playing entry
        playingClass: 'playing',

        // CSS class name of a paused entry
        pausedClass: 'paused',

        // CSS class name for an entry that is loading
        progressClass: 'progress',

        loop: false,
        playOnClick: false
    });
}

/**
 * Clear the seven steps signup input boxes on focus if they are
 * the default values, restoring to defaults on blur if there is
 * no new text.
 */
function sevensteps_clear() {
    $('#sevenstep-form input[type="text"]').each(function() {
        $(this).focus(function(){
            if ($(this).val() == $(this).attr('defaultValue')) {
                $(this).val('');
            }
        }).blur(function(){
            if ($(this).val() == '' || $(this).val() == ' ') {
                $(this).val( $(this).attr('defaultValue'));
            }
        });
    });
}

// jquery.fn.slideshow
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('4.I.U=p(a){j b={y:\'Q\',n:\'10\',6:\'l\',m:8,o:8,u:8};3(a){4.Y(b,a)}j c=0,2=1,9=0,k=\'\';j d=p(){3(c==0){O(j i=0;i<f.g;i++){4(f[i]).5(\'F\',\'G\')}4(f[9]).5(\'F\',\'H\').5(\'r\',\'0\');4(f[2]).5(\'r\',\'1\').J(b.y);3(b.6==\'l\'){3((2+1)<f.g){2=2+1;9=2-1}h{2=0;9=f.g-1}}h 3(b.6==\'7\'){9=2;z(2==9){2=q.D(q.7()*(f.g))}}h{E(\'6 x B C \\\'l\\\' A \\\'7\\\'\')}k=s(d,b.n)}};j e=p(){3(c==0){c=1;S(k);3(b.o!=8){b.u(4(\'#\'+b.m))}}h{c=0;d();3(b.o!=8){b.o(4(\'#\'+b.m))}}v W};t.5(\'w\',\'M\');j f=t.R(\'K\').T();4.N(f,p(i){4(f[i]).5(\'r\',f.g-i).5(\'w\',\'V\').5(\'L\',\'0\').5(\'X\',\'0\')});3(b.6==\'l\'){k=s(d,b.n)}h 3(b.6==\'7\'){P{2=q.D(q.7()*(f.g))}z(2==0);k=s(d,b.n)}h{E(\'6 x B C \\\'l\\\' A \\\'7\\\'\')}3(b.m!=8){4(\'#\'+b.m).Z(e)}v t};',62,63,'||current|if|jQuery|css|type|random|null|last|||||||length|else||var|timer|sequence|pauselink|timeout|playcallback|function|Math|zIndex|setTimeout|this|pausecallback|return|position|must|fadetime|while|or|either|be|floor|alert|display|none|block|fn|fadeIn|img|top|relative|each|for|do|slow|find|clearTimeout|get|slideshow|absolute|false|left|extend|click|2000'.split('|'),0,{}))

