$(window).load(function() {
    $('#pageLoader').fadeOut(300);


    setTimeout( function() {
        self.location.href='/etc/timeout.html';
    }, 7200000);  /* 2 hour timeout */


});

$(window).resize(function() {
//    cht.easyInfoLaunch();
    cht.easyInfoPos();
});

$(function(){

//    cht.easyInfoLaunch();
    cht.easyInfoPos();
    setTimeout( cht.easyInfoWiggle, 6000);

    $('#easyInfoLaunch, a.easyInfoBtn').click(function() {
        $('#easyInfo').fadeIn(300);
        return false;
    });

    $('a.easyInfoBtn').hover(function() {
        $(this).stop().animate({opacity:0.8},200);
    }, function() {
        $(this).stop().animate({opacity:1.0},200);
    });

    $('#easyInfoSubmit').click(function() {
        var eiData = {
            context: 'EasyInformation',
            name: 'Easy Information Anonymous',
            phone: '000 000 0000',
            email: 'no-reply@abtoyota.net',
            eiTitle: ei_title,
            eiContext: ei_context,
            eiUrl: self.location.href,
            addlist: 'FALSE',
            comments: $('#eiComments').val()
        };

        var canCall = false;

        if ( $('#eiEmailPhone').val().match(/^\(*[0-9]{3}\)*[\s-]*[0-9]{3}[\s-]*[0-9]{4}$/) ) {
            eiData.phone = $('#eiEmailPhone').val();
            canCall = true;
        }

        if ( $('#eiEmailPhone').val().match(/\b[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}\b/i) ) {
            eiData.email = $('#eiEmailPhone').val();
            canCall = true;
        }

        if ( ! canCall ) {
            cht.dialog('oops!','You must enter a valid email address or telephone number.<br /><br />' +
                       'If using phone number, the format is: xxx-xxx-xxxx');
            return false;
        }

        if ( $('#eiName').val() != '' )
            eiData.name = $('#eiName').val();

        $('body').css({cursor: 'progress' });
        $('#easyInfo').fadeOut(300);

        $.ajax({
            timeout: 3000,
            type: "POST",
            url: "/ajax_serv/generic_submit.php",
            data: eiData,

            success: function(json_data) {
                cht.dialog('We got it!','We have received your request, and will be in touch shortly.');
                $('body').css({cursor: 'default' });
            },
        
            error: function(json_data) {
                cht.dialog('Oops!','There was a technical problem when submitting - please try again later.');
                $('body').css({cursor: 'default' });
            }
            
        });

        return false;
    });

    $('#easyInfoClose').click(function() {
        $('#easyInfo').fadeOut(300);
        return false;
    });

    $('#easyInfoSubmit').hover(function() {
        $(this).stop().animate({ opacity: 0.7 }, 300, 'swing');
    }, function() {
        $(this).stop().animate({ opacity: 1.0 }, 300, 'swing');
    });

    $('a').click(function() {
        var href = $(this).attr('href');

        if ( $(this).attr('class').match(/newWin/) ) {
            cht.openWin(href);
            return false;
        }

        if ( $(this).attr('class').match(/nowarn/) )
            return true;

        if ( href.match(/^http[s]*:/) ) {
            var dg = "<div class=\"diagContent\" title=\"You are about to visit an external Web Site!\" id=\"extWeb\">";
            dg += "<p>We are not responsible for the content of third party websites.</p>" +
                  "<p>Do you wish to continue?</p>";
            dg += "</div>";

            $('body').append(dg);

            $('#extWeb').dialog({
                close: function() {
                    $('#extWeb').remove();
                },
                width: 400,
                height: 200,
                resizable: false,
                modal: true,
        
                buttons: {
                    'OK': function() {
                        self.location.href=href;
                    },
                    'Cancel': function() {
                        $(this).dialog("close");
                    }
                }
            });

            return false;
        }
    });

    if ( $('#mmPane').is(':visible') ) {
        cht.mm();
    }

    $('#aSiteMap').click(function() {
        if ( $('#ftSiteMap').is(':visible') )
            $('#ftSiteMap').hide();
        else {
            $('#ftSiteMap').show();
  
            $(window).scrollTop ( $(document).height() ); 
            
        }

        return false;
    });


    $('a.testDriveBtn').click(function() {
        cht.carChooser('Pick a vehicle to test drive...', function(vehicle_id) {
            self.location.href='/new/'+vehicle_id+'/testdrive';
        });
        return false;
    });

    $('.mnuVehicleChooser').click(function() {
        cht.carChooser('View our new vehicle range...', function(vehicle_id) {
            self.location.href='/new/'+vehicle_id;
        });
        return false;
    });
});


var cht = {

    openWin: function(url) {
        window.open(url,'_blank','width=1024,height=600,scrollbars=1,toolbar=1');
    },

    dialog: function(title,content) {
        $('body').append("<div class=\"diagContent\" title=\"" + title + "\" id=\"chtDiag\">" +
                 content + 
                 "</div>");
        
        $('#chtDiag').dialog({
            close: function() { $('#chtDiag').remove(); },
            width: 400, height: 200,
            resizable: false, modal: true,
            autoOpen: true,
            zIndex: 10000,
            buttons: {
                'OK': function() { $(this).dialog("close"); }
            }
        });
    },
        
    easyInfoLaunch: function() {
        if ( $(window).width() > 1080 ) {
            $('#easyInfoLaunch').show();
        }
        else
            $('#easyInfoLaunch').hide();
    },

    easyInfoPos: function() {
        $('#easyInfo').css({
            left: Math.floor( $(window).width() / 2 ) - Math.floor( $('#easyInfo').width() / 2 ),
            top: Math.floor( $(window).height() / 2 ) - Math.floor( $('#easyInfo').height() / 2 )
        });
    },

    easyInfoWiggle: function() {
        $('#easyInfoText').animate({ opacity: 0.0 }, 300, 'swing', function() {
            $(this).animate({ opacity: 1.0 }, 300, 'swing', function() {
                $(this).animate({ opacity: 0.0 }, 300, 'swing', function() {
                    $(this).animate({ opacity: 1.0 }, 300, 'swing');
                });
            });
        });  
        setTimeout( cht.easyInfoWiggle, 11000);
    },

    carChooser: function(title,action) {
        var chooser = "<div title=\"" + title + "\" id=\"carChooser\">";

        var vehicles = [
            { id: 'corolla', name: 'Corolla' },
            { id: 'yaris', name: 'Yaris' },
            { id: 'matrix', name: 'Matrix' },
            { id: 'camry', name: 'Camry' },
            { id: 'prius', name: 'Prius' },
            { id: 'venza', name: 'Venza' },
            { id: 'avalon', name: 'Avalon' },
            { id: 'sienna', name: 'Sienna' },
            { id: 'rav4', name: 'Rav4' },
            { id: 'highlander', name: 'Highlander' },
            { id: 'sequoia', name: 'Sequoia' },
            { id: 'tacoma', name: 'Tacoma' },
            { id: 'tundra', name: 'Tundra' },
            { id: 'fjcruiser', name: 'FJ Cruiser' },
            { id: '4runner', name: '4Runner' }
        ];

        chooser +=      "<div id=\"ccOuter\">";

        for ( veh in vehicles ) { 
            chooser += "<div class=\"ccIns\">" +
                            "<div style=\"color:#eeeeee;text-align:center;\">" + vehicles[veh].name + "</div>" +
                            "<img id=\"choose_" + vehicles[veh].id + "\" src=\"/layout/images/new/choose_" +
                           vehicles[veh].id + ".jpg\" width=\"100\" height=\"100\" alt=\"" + vehicles[veh].name + "\" />" + 
                       "</div>";
        }

        chooser +=      "</div>";

        chooser += "</div>";

        $('body').append(chooser);

        $('#carChooser img').hover(function() {
            $(this).stop().animate({
                width: '120px',
                height: '120px',
                opacity: 1.0
            }, 100, 'swing');
        }, function() {
            $(this).stop().animate({
                width: '100px',
                height: '100px',
                opacity: 0.8
            }, 100, 'swing');
        }).click( function() {
            action( $(this).attr('id').replace(/choose_/, '') );
        });

        $('#carChooser').dialog({
            close: function() {
                $('#carChooser').remove();
            },
            width: 690,
            height: 520,
            resizable: false,
            modal: true,
            buttons: {
                'Cancel': function() {
                    $(this).dialog("close");
                }
            }
        });

    },

    mm: function() {
        $('#mmPane').html("<iframe frameborder=\"0\" class=\"xtimeMM\" src=\"http://xws.xtime.com/xmmquery/?make=TOYOTA&variant=TCI\">" + 
                          "</iframe>");
    },

    tooltip: function(argv) {
        $(argv.parent).append("<div id=\"" + argv.id + "\" class=\"tooltip\"><div class=\"tooltip" +
                        argv.direction + "\"><!-- --></div>" +
                         "<strong>Website tips</strong><br />" +
            argv.tip + "</div>");

        $('#'+argv.id).css({
            left: argv.left,
            top: argv.top
        }).fadeIn(500);

        setTimeout(function() {
            $('#'+argv.id).fadeOut(500,function() {
                $('#'+argv.id).remove();
            });
        }, argv.duration);

    },

    preload: [
        '/layout/images/stdMenuBg.png',
        '/layout/images/h1alwyn.png',
        '/layout/images/loading.gif',
        '/layout/images/easyInfoBg.png'
    ],

    init: function() {

        $('div.stdMenuBody li').hover(
            function() { $(this).css({
                backgroundImage: "url('/layout/images/stdMenuHover.png')",
                backgroundColor: '#333333',
                color: '#ffffff'}); },
            function() { $(this).css({
                backgroundImage: 'none',
                backgroundColor: '#ffffff',
                color: '#333333'}); }
        );

        $('#quickSearch').click( function() {
            $(this).val('');
        });

        if ( $.browser['msie'] == true && $.browser.version == '6.0' ) {
            $('div.stdMenuBody').css({backgroundImage: "url('/layout/images/stdMenuBg_IE6.gif')"});
            $('div.stdMenuFooter').css({backgroundImage: "url('/layout/images/stdMenuFooterBg_IE6.gif')"});
            $('div.dNvFoot').css({backgroundImage: "url('/layout/images/stdMenuFooterBg_IE6.gif')"});
        }


        switch(pageId) {
            case 'home':
                this.home.init();
                break;
            case 'vehicleView':
                this.vehicleView.init();
                break;
            case 'vehicleModels':
                this.vehicleModels.init();
                break;
            case 'vehicleFeatures':
                this.vehicleFeatures.init();
                break;
            case 'serviceBook':
                this.serviceBook.init();
                break;
            case 'serviceToyotaTouch':
                this.serviceToyotaTouch.init();
                break;
            case 'newTestdrive':
                this.newTestdrive.init();
                break;
            case 'usedPortal':
                this.usedPortal.init();
                break;
        }

        $.preload(cht.preload);

        
        /* Turn H1s into fancy H1 */
        $('div.cStdContent h1, #pcNew h1').each(function() {
            var heading = $(this).text().toLowerCase();
            var fakeHeading = '';

            for ( i=0; i<heading.length; i++ ) {
    
                var xchar = heading.charAt(i);

                if ( ! xchar.match(/[a-z]/)  )
                    fakeHeading += "<div class=\"fakeH1char fakeH1charspace\"><!-- --></div> ";
                else
                    fakeHeading += "<div class=\"fakeH1char fakeH1char" + xchar + "\"><!-- --></div> ";
            }

            $(this).before("<div class=\"fakeH1\">" + fakeHeading + "</div>").remove();
        });

        cht.tabs.init();
    },

    tabs: {
        state: new Array,
        deAct: null,
        activeMenu: null,
        preDelay: null,

        init: function() {
            $('a.tab').hover( function() {
                var tabId = parseInt($(this).attr("id").replace(/^tab/,''));
                cht.tabs.active(tabId);

            }, function() {
                var tabId = parseInt($(this).attr("id").replace(/^tab/,''));
                cht.tabs.inactive(tabId);
            });

            $('div.stdMenu').hover(function() {
                clearTimeout( cht.tabs.deAct );
            }, function() {
                var tab = $(this).attr('id').replace(/tab([0-9]+)dd/, "$1");
                cht.tabs.inactive(tab);
            });
            
        },

        active: function(tab) {
            clearTimeout( cht.tabs.deAct );

            if ( tab != cht.tabs.activeMenu ) {
                cht.tabs.ddInactive(cht.tabs.activeMenu);
            }

            cht.tabs.preDelay = setTimeout( function() {

                if ( cht.tabs.activeMenu != tab ) {
                    cht.tabs.ddInactive(cht.tabs.activeMenu);
                }

                $('a.tab').removeClass('tabOn');
                $('#tab'+tab).addClass('tabOn');

                $('#TabHiLight').stop().animate({
                    left: tabs['tab'+tab].left + 'px'
                },100,"swing");

                cht.tabs.ddActive(tab);
            }, 200);

        },

        inactive: function(tab) {
            clearTimeout( cht.tabs.preDelay );

            cht.tabs.deAct = setTimeout( function() {
                $('a.tab').removeClass('tabOn');
                $('#'+activeTab).addClass('tabOn');


                $('#TabHiLight').stop().animate({
                    left: tabs[activeTab].left + 'px'
                },100,"swing");

                cht.tabs.ddInactive(tab);
            }, 300);
        },

        ddActive: function(tab) {
            if ( tab == cht.tabs.activeMenu )
                return;

            cht.tabs.activeMenu = tab;
            $('#tab'+tab+'dd').show("slide", { direction: 'up' }, 150);

        },

        ddInactive: function(tab) {
            cht.tabs.activeMenu = null;

            if ( $('#tab'+tab+'dd').is(":visible") )
                $('#tab'+tab+'dd').hide("slide", { direction: 'up' }, 150);

        }

    },

    newTestdrive: {
        init: function() {
            $.datepicker.setDefaults({
                dateFormat: "yy/mm/dd"
            });

            $('#tdf_testdrive_date').datepicker();
        }
    },

    vehicleModels: {
        init: function() {
            $('div.nvCo').hide();
            $('div.nvCo').show('blind', { direction: 'verticle'}, 1000);
        }
    },

    vehicleFeatures: {
        init: function() {
            $('table tr:nth-child(even)').addClass('striped');

        }
    },

    vehicleView: {
        init: function() {
            $('#pcNewSplash').hide();
            $('#pcNewSplash').fadeIn(2000);
        }
    },

    serviceBook: {
        init: function() {
            $.datepicker.setDefaults({
                dateFormat: "yy/mm/dd"
            });

            $('#saf_apt_date0').datepicker();
            $('#saf_apt_date1').datepicker();
        }
    },

    serviceToyotaTouch: {
        init: function() {
        }
    },

    usedPortal: {
        pos: { '0': 0, '1': 66, '2': 132, '3': 198 },
        timeout: { },
        iter: { '0': 0, '1': 0, '2': 0, '3': 0 },

        init: function() {
            this.spin('0');
            this.spin('1');
            this.spin('2');
            this.spin('3');
        },

        spin: function(ctr) {
            var speed = 15;

            switch (ctr) {
                case '0':
                    speed = 25;
                    break;
                case '1':
                    speed = 20;
                    break;
                case '2':
                    speed = 15;
                    break;
                case '3':
                    speed = 10;
                    break;
            }

            cht.usedPortal.pos[ctr]+= speed;

            if ( cht.usedPortal.pos[ctr] >= 660 ) {
                cht.usedPortal.pos[ctr] = 0;
                cht.usedPortal.iter[ctr]++;
            }

            $('#usedCtr'+ctr).css({
                backgroundPosition: '0px '+ cht.usedPortal.pos[ctr] + 'px'
            });

            if ( cht.usedPortal.iter[ctr] > 1 ) {
                var num = usedCtr.substr(parseInt(ctr),1);
                var offset = num * 66;

                if ( offset == 0 ) {
                    if ( cht.usedPortal.pos[ctr] >= 0 ) {
                        cht.usedPortal.findPos(ctr,offset,speed);
                        return;
                    }
                }
                    
                if ( cht.usedPortal.pos[ctr] >= (660-offset) ) {
                    cht.usedPortal.findPos(ctr,offset,speed);
                    return;
                }
            }

            cht.usedPortal.timeout[ctr] = setTimeout( function() {cht.usedPortal.spin(ctr)}, 33 );
        },

        findPos: function(ctr, offset,speed) {
            var bounce = 3;
            var distance = 40;

            $('#usedCtr'+ctr).effect("bounce", {direction: 'up', times: bounce, distance: distance}, 200);

            $('#usedCtr'+ctr).css({
                backgroundPosition: '0px '+ (660-offset) + 'px'
            });
        }
    },

    home: {
        splashIns: 0,
        splashTimeout: null,
        splashDelayTimeout: null,

        splashSwitch: function(el) {
            var splashId = el.replace(/splashLink/,'');
            $('#homeSplashLinks a').stop().animate({marginLeft: '29px',opacity: 0.5},250,'swing');
            $('#'+el).stop().animate({marginLeft: '0px',opacity: 1.0},250,'swing');

            cht.home.splashIns = splashId;

/*
            if ( cht.home.splashIns == 0 ) 
                cht.home.triSplash();
            else {
                $('#triSplash1, #triSplash2, #triSplash3').remove();
            }
*/

    
            $('#homeSplash').stop().animate({left: splash[splashId].splashX +"px"}, 200, 'swing', function() {
                $('#homeSplashInfo').stop().animate({top: '354px'},300,'swing', function() {
                    $('#homeSplashInfo p').html( splash[splashId].mainLine1 + '<br />' + splash[splashId].mainLine2 );
                    $('#homeSplashInfo').animate({top: '304px'},200,'swing');
                });
            });

        },

        autoRotate: function() {
            cht.home.splashTimeout = setTimeout(function() {
                cht.home.splashIns++;

                if ( cht.home.splashIns == 5 )
                    cht.home.splashIns = 0;

                cht.home.splashSwitch( 'splashLink'+cht.home.splashIns );
                cht.home.autoRotate();
            }, 10000);
        },

        triSplash: function() {
            $('#triSplash1, #triSplash2, #triSplash3').remove();

            $('#homeSplashLoader').append("<div class=\"splashSeg\" id=\"triSplash1\"><!-- --></div>");
            $('#homeSplashLoader').append("<div class=\"splashSeg\" id=\"triSplash2\"><!-- --></div>");
            $('#homeSplashLoader').append("<div class=\"splashSeg\" id=\"triSplash3\"><!-- --></div>");

            $('div.splashSeg').hover( function() {
                $(this).stop().animate({
                    opacity: 0.2
                }, 300);
            }, function() {
                $(this).stop().animate({
                    opacity: 0.0
                }, 300);
            });

//            $('#triSplash1').click(function() { window.open( splash[0].trilink1 ); });
//            $('#triSplash2').click(function() { window.open( splash[0].trilink2 ); });
//            $('#triSplash3').click(function() { window.open( splash[0].trilink3 ); });
            $('#homeSplashInfo').click( function() { self.location.href = splash[0].link; });
            
        },

        init: function() {
//            this.triSplash();

            $('div.splashSeg').css({ opacity: 0.0 });

            $(window).load( function() {
                cht.home.autoRotate();
            });

            $('#splashLink1, #splashLink2, #splashLink3, #splashLink4').css({opacity:0.5});

            $('#homeSplash, #homeSplashInfo').click(function() {

                /* Ignore For tri-splash! */
//                if ( cht.home.splashIns != 0 ) {
                    self.location.href=splash[cht.home.splashIns].link;
//                }
            });

            $('#homeSplashLinks a').click(function() {
                clearTimeout(cht.home.splashTimeout);
                cht.home.splashSwitch( $(this).attr('id') );

                clearTimeout(cht.home.splashDelayTimeout);
                cht.home.splashDelayTimeout = setTimeout( cht.home.autoRotate, 12000 );
                return false;
            });

            $('div.homeButton').hover(function() {
                $(this).css({ backgroundPosition: "0px 0px" });

                $(this).find('img').each(function() {
                    $(this).stop().animate({
                        width: "130px",
                        height: "130px",
                        opacity: 0.0
                    },400);
                });
            }, function() {
                $(this).css({ backgroundPosition: "-130px 0px" });

                $(this).find('img').each(function() {
                    $(this).stop().animate({
                        width: "49px",
                        height: "49px",
                        opacity: 0.8
                    },400);
                });
            });

            $('#promoLarge, #promoSmall1, #promoSmall2').hover(function() {
                
                $(this).stop().animate({ opacity: 0.8 }, 100, "swing");
            }, function() {
                $(this).stop().animate({ opacity: 1.0 }, 100, "swing");
            });

            $('#homeQuickLinks a').hover(function() {
                $(this).css({backgroundPosition: '0px -33px'}).stop().animate({marginLeft: '0px'},200,'swing');
            }, function() {
                $(this).css({backgroundPosition: '0px 0px'}).stop().animate({marginLeft: '10px'},200,'swing');
            });
        }
    },

    survey: {
        yes: function() {
            this.cookie();
            self.location.href = '/survey/';
        },
        no: function() {
            this.cookie();
            $('#surveyDropIn').hide('slide', { direction: "up" }, 300);
        },

        cookie: function() {
            tools.setCookie('survey','true',28);
        }
    }

};

var tools = {
    t: new Array,

    iv: {
        regen: function(el) {
            var now = new Date();
            $('#'+el).get(0).src = '/iv/iv.php?' + now.getTime();
        }
    },
    
    setCookie: function(c_name,value,expiredays,path) {
        var exdate=new Date();
        exdate.setDate(exdate.getDate()+expiredays);
        document.cookie=c_name+ "=" +escape(value)+
        ((expiredays==null) ? "" : ";expires="+exdate.toGMTString()) +
        ((path==null) ? "" : ";path="+path);
    },

    getCookie: function(c_name) {
        if (document.cookie.length>0) {
            c_start=document.cookie.indexOf(c_name + "=");
            if (c_start!=-1) { 
                c_start=c_start + c_name.length+1; 
                c_end=document.cookie.indexOf(";",c_start);
                if (c_end==-1) c_end=document.cookie.length;
                return unescape(document.cookie.substring(c_start,c_end));
            } 
        }
        return "";
    }
};
