var myHeight = 0;
var venture = '';
var address =0;




function sizeMe(){
    
    $("#container, #contentContainer").css({"height":100});

    if ( $(document).height()>$(window).height()  ){
        myHeight = $(document).height();
    }else {
        myHeight = $(window).height();
    }
    $("#container").css({"height":myHeight});
    $("#contentContainer").css({"height":(myHeight-192)});
}



var addressStarted = false;
var addressStarted2 = false;

$(document).ready(function(){
sizeMe();
window.onresize=sizeMe;
document.onresize=sizeMe;







            // Document title
            var title = document.title;

            // Default tracker mock
            var pageTracker = {
                _trackPageview: function() {
                    gaPageTracker._trackPageview(arguments[0]);
                    log('track: ' + arguments[0]);
                }
            }

            // Init and change handlers
            $.address.init(function(event) {
                /* If we are not on the home page load the correct window */
                //$.address.value('chimp');

                // Shouldnt have to do this!!!!
                address = $.address.baseURL().replace(baseURL,'');
                
                if( address!=event.value){
                    $.address.value(address);
                }

                var parts =event.value.split('/');
                var page = parts[1];
                var type = parts[2];
                var cat =  parts[3];

                if(event.value !='/' && page !='ventures' && page !='years'){

                    $("#content").fadeTo("fast", 0, function(){
                        $.ajax({
                            type:"POST", datatype:"html", url:baseURL+event.value, success: function( data ){
                                $("#content").html(data).fadeTo("fast", 1);
                                sizeMe();
                            }
                        });
                    });
                }


                $('.navLink').each(function() {

                        if( '/'+$(this).attr('href')==""+event.value){
                                highlightNavLink($(this).attr('id'));
                        }
                });
                addressStarted2 =true;
                
            }).change(function(event) {
                // Shouldnt have to do this!!!!
                
                event.value=event.value.replace("/"+baseURL,'');
                /**************************** CHANGE EVENT ***************************/
                
                // If we are just landing do nothing
                if(addressStarted2== false){
                    addressStarted2 = true;
                    return false;
                }
                if(addressStarted== false){
                    addressStarted = true;
                    return false;
                }
                
                /* Not too sure... yet?? */
                var names = $.map(event.pathNames, function(n) {
                    return n.substr(0, 1).toUpperCase() + n.substr(1);
                }).concat(event.parameters.id ? event.parameters.id.split('.') : []);
                var links = names.slice();
                //var match = links.length ? links.shift() + ' ' + links.join('.') : 'Home';
                

                // Lets split up our URL into parts
                var parts =event.value.split('/');
                var page = parts[1];
                var type = parts[2];
                var cat =  parts[3];
                if(page=='ventures'){
                    highlightNavLink(type+'Link');
                    //venture = type;
                }else if(page=='years'){
                    
                }
                else{ // Default is navlink
                    $('.navLink').each(function() {

                        if( '/'+$(this).attr('href')==""+event.value){
                                highlightNavLink($(this).attr('id'));    
                        }
                    });

                    
                    $("#content").fadeTo("fast", 0, function(){
                            $.ajax({
                                type:"POST", datatype:"html", url:baseURL+event.value, success: function( data ){
                                    $("#content").html(data).fadeTo("fast", 1);
                                    sizeMe();
                                }
                            });
                     });
                }

                // change title
                $.address.title([title].concat(names).join(' | '));



            }).externalChange(function(event){

                // Shouldnt have to do this!!!!
                /**************************** External Change ***************************/
                event.value=event.value.replace("/"+baseURL,'');
                var parts =event.value.split('/');
                var page = parts[1];
                if(page=='ventures'){
                    
                    
                    var type = parts[2];
                    var cat =  parts[3];
                    
                    // first need to check we have ventures in the window
                    if( $('#ventureSpacer').length == 0 || type != venture){
                        venture = type;
                        $("#content").fadeTo("fast", 0, function(){
                            $.ajax({
                                type:"POST", datatype:"html", url:baseURL+'/'+parts[1].slice(0, -1)+'/'+parts[2], success: function( data ){
                                    $("#content").html(data).fadeTo("fast", 1);
                                    openVentureCategory(1,'external',cat);
                                    $('.downarrow').remove();
                                    $('.ventureAnchor').addClass('greyLink');
                                    $("#venture_"+cat).children().removeClass('greyLink').append("<span class='downarrow'>&nbsp;&darr;</span>");
                                    sizeMe();
                                }
                            });
                     });
                    }else{
                        
                        openVentureCategory(1,'external',cat);
                        $('.downarrow').remove();
                        $('.ventureAnchor').addClass('greyLink');
                        $("#venture_"+cat).children().removeClass('greyLink').append("<span class='downarrow'>&nbsp;&darr;</span>");
                        
                    }
                    
                }else if(page=='years'){
                   
                    var type = parts[2];
                    var cat =  parts[3];
                    var year = parts[4];

                    // first need to check we have ventures in the window
                    if( $('#ventureSpacer').length == 0 || type != venture){
                        venture = type;
                        $("#content").fadeTo("fast", 0, function(){
                            $.ajax({
                                type:"POST", datatype:"html", url:baseURL+'/venture/'+parts[2], success: function( data ){
                                    $("#content").html(data).fadeTo("fast", 1);
                                    openVentureCategory(1,'external',cat);
                                    openVentureYears(1,'external',cat,year);
                                    sizeMe();
                                }
                            });
                     });
                    }else{

                        openVentureCategory(1,'external',cat);
                        openVentureYears(1,'external',cat,year);
                        $('.downarrow').remove();
                        $('.ventureAnchor').addClass('greyLink');
                        $("#venture_"+cat+'_'+year).children().removeClass('greyLink').append("<span class='downarrow'>&nbsp;&darr;</span>");

                    }

                    
                }

                if(page=='ventures' || page=='years'){
                    var names = $.map(event.pathNames, function(n) {
                        return n.substr(0, 1).toUpperCase() + n.substr(1);
                    }).concat(event.parameters.id ? event.parameters.id.split('.') : []);
                    var links = names.slice();
                    // Change title
                    $.address.title([title].concat(names).join(' | '));
                }

                

            });

            /* mine*/

            $(".navLink").click(function () {

                // Are we already on this page??
                if( $(this).hasClass("navLinkActive")){
                 return false;
                }

                if($(this).attr('id')=='projectsLink'){
                    venture = 'projects';
                }else if($(this).attr('id')=='eventsLink'){
                    venture = 'events';
                }
                // Continue
                // Change the $.address value
                $.address.value($(this).attr('href').replace(baseURL,''));
                
                return false;
            });
            
            
            
            $(".goLink").click(function () {
                // Change the $.address value
                $.address.value($(this).attr('href').replace(baseURL,''));

                return false;
            });

            $(".goLink").live("click",function () {
                // Change the $.address value
                $.address.value($(this).attr('href').replace(baseURL,''));

                return false;
            });




            function highlightNavLink(id){
                
                $(".navLink").removeClass("navLinkActive").addClass("white");
                $("#"+id).addClass("navLinkActive").removeClass("white");
            }


            

            

            $(".greyLink").live("click",function () {
                $('.downarrow').remove();
                $('.ventureAnchor').addClass('greyLink');
                $(this).removeClass('greyLink').append("<span class='downarrow'>&nbsp;&darr;</span>");
                
            });
           

            /****************** VENTURE CATEGORIES *****************/

            $(".ventureCategory").live("click",function () {
                dealWithVentureCategory(this);
                return false;
            });

            $(".ventureCategory").click(function () {
                dealWithVentureCategory(this);
                return false;
            });

            function dealWithVentureCategory(myObj){

                // Are we already on this page??
                if( $(myObj).parent().hasClass("ventureCategoryActive")){
                     closeVentureCategory(myObj,1);

                }else{
                     openVentureCategory(myObj,'dealwith',false);
                }
                // Change the $.address value
                $.address.value($(myObj).attr('href'));

                return false;
            }

            function closeVentureCategory(myObj,children){
                var id = $(myObj).parent().attr("id");
                $(myObj).parent().removeClass('ventureCategoryActive');

                if(children==1){
                    // close children
                    $("."+id).hide('slow');
                }
                // close all of these
                $(".ventureLinkContainer").hide('slow');
            }

            function openVentureCategory(myObj,from,cat){
                if(from=='external'){
                    if(typeof(cat) != "undefined"){
                        var id="venture_"+cat;
                    }else{
                        var id=false;
                    }
                }else{
                    var id = $(myObj).parent().attr("id");
                }
                
                $('.ventureCategoryActive').removeClass('ventureCategoryActive');
                $(".ventureYearsContainer").hide('slow');
                $(".ventureLinkContainer").hide('slow');
                if(id){
                    $("#"+id).addClass('ventureCategoryActive');
                    $("."+id).show('slow');
                }
            }

            /****************** VENTURE YEARS *****************/
             $(".ventureYears").live("click",function () {
                dealWithVentureYears(this);
                return false;
            });

            $(".ventureYears").click(function () {
                dealWithVentureYears(this);
                return false;
            });

            function dealWithVentureYears(myObj){

                // Are we already on this page??
                if( $(myObj).parent().hasClass("ventureYearsActive")){
                     closeVentureYears(myObj);
                }else{
                     openVentureYears(myObj,'dealwith',false,false);
                }
                // Change the $.address value
                $.address.value($(myObj).attr('href').replace(baseURL,''));

                return false;
            }

            function closeVentureYears(myObj){
               var id = $(myObj).parent().attr("id");
               $("#"+id).removeClass('ventureYearsActive');
               $("."+id).hide('slow');
            }

            function openVentureYears(myObj,from,cat,year){

                if(from=='external'){
                    if(typeof(year) != "undefined"){
                        var id="venture_"+cat+'_'+year;
                    }else{
                        var id=false;
                    }
                }else{
                    var id = $(myObj).parent().attr("id");
                }


               $('.ventureYearsActive').removeClass('ventureYearsActive');
               $(".ventureLinkContainer").hide('slow');
               if(id){
                    $("#"+id).addClass('ventureYearsActive');
                    $("."+id).show('slow');
                }
               
            }






            /*********************** OTHER FUNCTIONS ****************************/

            $(".ventureThumbs").live("click",function () {
                var img = new Image();
                var  src = $(this).attr('src').replace('80_48','368_240');
                $('#ventureImg').fadeTo('fast',0,function(){
                     $(img).load(function () {
                        $('#ventureImg').attr('src',src).fadeTo("fast",1);
                    }).attr('src', src);
                })
                return false;
            });

            $(".imgy").live("click",function () {

                    if( $("#galleryFlowplayer").is(":visible")  ){
                        $f("galleryFlowplayer").stop();
                    }
                $('#ventureLgImg').removeClass('bigVid');
                var img = new Image();

                if($(this).hasClass('portrait')){
                    var  src = $(this).attr('src').replace('48_32','360_448');
                    $('#ventureLgImg').css({"width":360,"height":448})
                }else{
                    var  src = $(this).attr('src').replace('48_32','752_448');
                    $('#ventureLgImg').css({"width":752,"height":448})
                }
             
                if ( $('#ventureLgImg').attr('src')==src){
                    //return false;
                }
                var  id = $(this).attr('id');
                var imgNo = id.substr(9);
                $(".ventureLilThumb").fadeTo('fast',0.6);
                if( $("#totalVids").is(":visible")  ){
                    $("#totalVids").css("display","none");
                    $("#totalImages").css("display","block");
                }
                $("#imgCaption").fadeTo('fast',0);
                $('#ventureLgImg').fadeTo(1,0,function(){
                     $(img).load(function () {
                        $('#ventureLgImg').attr('src',src).fadeTo("fast",1);
                        $("#"+id).fadeTo('fast',1);
                        $("#imageNo").html(imgNo);
                        $("#imgCaption").html( $("#"+id).attr('alt')  ).fadeTo('fast',1);

                    }).attr('src', src);
                })
                return false;
            });

            $("#ventureLgImg").live("click",function () {
                if($(this).hasClass('bigVid')){
                    runVideoPlayer(this);
                }
            });

            $(".viddy").live("click",function () {
                var  id = $(this).attr('id');
                var imgNo = id.substr(9);
                $(".ventureLilThumb").fadeTo('fast',0.6);
                $("#imgCaption").fadeTo('fast',0, function(){
                    $("#imgCaption").html( $("#"+id).attr('alt')  ).fadeTo('fast',1);
                    $("#"+id).fadeTo('fast',1);
                });
                
                
                $("#videoNo").html(imgNo);
                $("#ventureLgImg").css("background-image", $(this).css('background-image').replace("48_32", "752_448")  );

                runVideoPlayer(this);
                if( $("#totalImages").is(":visible")  ){
                    $("#totalImages").css("display","none");
                    $("#totalVids").css("display","block");
                }
                
            });
            
            $("#filmStripRight").live("click",function () {
                
                var no_of_thumbs = $('.ventureLilThumb').size();
                var max_left = 0-((no_of_thumbs * 64)-640);
                var currentMargin = parseInt($('#ventureLilThumbs').css('margin-left') );
                if(currentMargin > max_left){
                    $(".filmStripMovers").addClass("moving");
                    $('#ventureLilThumbs').animate({
                        marginLeft: (currentMargin-64)
                        }, {
                        duration: 500,
                        complete: function() {
                            $(".filmStripMovers").removeClass("moving");
                        }
                    });
                }
                return false;
            });

            $("#filmStripLeft").live("click",function () {
                
                var no_of_thumbs = $('.ventureLilThumb').size();
                var currentMargin = parseInt($('#ventureLilThumbs').css('margin-left') );
                if(currentMargin <0){
                    $(".filmStripMovers").addClass("moving");
                    $('#ventureLilThumbs').animate({
                        marginLeft: (currentMargin+64)
                        }, {
                        duration: 500,
                        complete: function() {
                            $(".filmStripMovers").removeClass("moving");
                        }
                    });
                }
                return false;
            });

           
            
            $(".galHoverer").live("mouseover",function () {
                    if($(this).hasClass('showing')){
                        return false;
                    }


                    $(this).addClass("showing");

                    $(this).siblings(".galThumbHover2").fadeTo('fast',1,function(){$(this).siblings('.galHoverer').removeClass('showing')}).siblings('.galThumbHover').fadeTo('fast',0.6);

                    //$(".galThumbContainer").not(this).children(".galThumbHover2").fadeTo('fast',0).siblings('.galThumbHover').fadeTo('fast',0);
                    
                
                return false;
            });

            $(".galHoverer").live("mouseout",function () {

                    if($(this).hasClass('hiding')){
                        return false;
                    }

                    $(this).addClass("hiding");

                    $(this).siblings(".galThumbHover2").fadeTo('fast',0,function(){$(this).siblings('.galHoverer').removeClass('hiding')}).siblings('.galThumbHover').fadeTo('fast',0);

                return false;
            });

            $(".galHoverer").live("click",function () {
                $.address.value(  $(this).attr('href').replace(baseURL,'') );
                return false;
            });






});


function searchForm(myObj){
    $("#content").fadeOut('fast',function(){
        $.post($("#searchSite").attr('action'), { searchTerm: $("#searchTerm").attr('value') },
            function(data){
                $("#content").html(data).fadeIn('fast');
            });

            $.address.title('Hoping Foundation | Search Results');
    });
    
    return false;
}


function runVideoPlayer(myObj){
       //var vidpath = $(this).attr('href');

       var columns = $(myObj).attr('id').split('_');
       var column = parseInt(columns[2]);
       var vidpath=$(myObj).css("background-image");

       vidpath = vidpath.replace(/"/gi, '');
       vidpath =vidpath.replace('url(http://www.hopingfoundation.org/', "");
       vidpath =vidpath.replace('url("http://www.hopingfoundation.org', "");
       vidpath =vidpath.replace('/752_448', "");
       vidpath =vidpath.replace('/48_32', "");
       vidpath =vidpath.replace('.jpg', ".mp4");
       vidpath =vidpath.replace(')', "");

       $("#galleryFlowplayer").fadeIn(1500);

       flowplayer("galleryFlowplayer", "js/flowplayer.swf", {        // supply the configuration

        clip : {            // Clip is an object, hence '{...}'
            autoPlay: true,
            autoBuffering: true,
            baseUrl: baseURL
        },

        playlist: [            // playlist is an array of Clips, hence [...]

            {url: vidpath}    // small object as entry
        ],

        plugins: {            // load one or more plugins
            controls: {            // load the controls plugin
                url: 'js/flowplayer.controls.swf',    // always: where to find the Flash object
                //stop:true,
                play:false,
                    time:false,
                    sliderColor:  	'#111111',
                    bufferColor:  	'#111111',
                    progressColor:  '#c10076',
                    progressGradient: 'none',
                    scrubberHeightRatio:  	0.07,
                    backgroundGradient: 'none',
                    buttonColor:  	'#999999',
                    volumeSliderColor:  	'#999999',
                    volumeColor:      "#c10076",
                    volumeSliderHeightRatio : 	0.2,
                    tooltipColor: '#999999',
                    buttons:false,
                                   // now the custom options of the Flash object
                    backgroundColor: '#eeeeee',
                tooltips: {                // this plugin object exposes a 'tooltips' object
                    buttons: true,
                    fullscreen: 'Enter Fullscreen mode'
                }
            }
        },

        onFinish: function() {        // set an event handler in the configuration
            $("#galleryFlowplayer").fadeOut("fast");

        },

        onStop: function(){
            $("#galleryFlowplayer").fadeOut("fast");
        }
        });
}
