/*************************************************************************
 **
 ** NOTES:
 ** Path: www.site.com/path/to/page
 ** Fragment: #hash
 ** Query stuff: ?start=10
 ************************************************************************/

var test_content = "<div id='list-overlay'>Test</div>";


$( document ).ready( function () { 
        
    //var AjaxSiteObj = new AjaxSite();
    //AjaxSiteObj.initializeLinks($("#list-overlay"));

    // if loading a page with a path in the fragment, immediately
    // redirect to the fragment path to resolve "inconsistent" urls like:
    //
    //   http://www.segd.org/about-us/index.html#/news/index.html
    //
    // see also hash-redirector.js, which currently preempts this with even
    // earlier hash-based redirection. this is to prevent a full load of the
    // old page followed by an immediate redirect.
	/*
	var GSDSheetObj = new GSDSheet();
	GSDSheetObj.setContent(test_content);
	*/
    return; 


} ); // ready

/*
    AjaxSite constructor
        Initialize content
        
        note: 
        {
        doThis : function(){
            self = this;
            something.click(function(event){
                self.doThat(event)
            });
        },
        doThat : function(evemt){

        }
*/
function GSDSheet(currentLink){
    var self = this;
    this.currentLink = currentLink;

}

GSDSheet.prototype = {
    //some options
    currentLink     : {path:"", fragment:"", query:""},   //holds link_obj parsed by AjaxSite: 
                            // {path:"", fragment: "", query :""}
    currentBreadcrumb: null,
    contentHandler  : "#list-overlay", //default handler for sheets
    isVisible       : false,

    pageChange :    function(link){
        //breakoutLinkParts
		//ajaxLoad
		//set content
		//If contain fragment, do a scrollto
		
		
    },
    _initCustomSheetStuff : function(){
        if( !$("#list-overlay").is(":visible")){
            //return;
        }
        //CSE callback functions
        var _startingCallback = function(searchControl, searcher, query){
            var content = $("#cse-content .gsc-resultsHeader");
            //console.log(content);
            var queryDiv = $("#cse-content #query");
            if (queryDiv.length == 0) {
                var queryDiv = $("<div id='query'></div>");
                
                content.after(queryDiv);
                //document.body.appendChild(queryDiv);
            }
                queryDiv.html( "Search results for <strong>" + query+"</strong>");
        };
        var  _completeCallback = function(searchControl, searcher){
            if(typeof searcher.cursor == "undefined"){return;}
            var arrow_button_html = ' <a href="#" class="prev-btn">previous</a><a href="#" class="next-btn">next</a>'
            //moving the pager
            var pager = $("#cse-content .gsc-results .gsc-cursor-box");
            var queryDiv = $("#cse-content #query");
            var top_pager_container = $("#gsc-top-pager");
            if (top_pager_container.length == 0) {
                var top_pager_container = $("<div id='gsc-top-pager' class='clearfix'></div>"); 
                queryDiv.after(top_pager_container);
            }
            //var test_obj = $("<div style='border:1px solid red;'>test</div>");
            top_pager_container.html(arrow_button_html + pager.html());
            
            //re-establish button clicks here;
            $("#gsc-top-pager .gsc-cursor-page").each(function(i,e){
                $(e).click(function(){
                    $(pager.find(".gsc-cursor-page")[i]).trigger("click");
                });
            });
            
                //setup arrow buttons
            var result_size = searcher.getResultSetSize();
            var current_page = searcher.cursor.currentPageIndex;
            $("#gsc-top-pager .next-btn").click(function(){
                var temp_index = current_page+1;
                if(temp_index == 8){
                    //load moreResultsURL
                }
                else{
                    $(pager.find(".gsc-cursor-page")[temp_index]).trigger("click");
                }
                return false;
            });
            $("#gsc-top-pager .prev-btn").click(function(){
                var temp_index = current_page-1;
                if(temp_index >= 0){
                    $(pager.find(".gsc-cursor-page")[temp_index]).trigger("click");
                }
                return false;
            });
            console.log("current pager", searcher); //cursor
            console.log("pager",pager);
           
            //inserting and updating page count
            var pageCountDiv = $("#cse-content #page-count");
            if (pageCountDiv.length == 0) {
                var pageCountDiv = $("<div id='page-count'></div>");
                queryDiv.after(pageCountDiv);
            }
            var start_page = parseInt(searcher.cursor.pages[current_page].start)+1;
            pageCountDiv.html(start_page+" - " +(start_page+result_size) +" of about "+ searcher.cursor.estimatedResultCount);
        };
        //END OF CSE CALLBACK FUNCTIONS

            if($('.gal-holder').length > 0){
                var loaded_count = 0;
                var timeout_id=0;
                var img_ref_count = $('.frontend-slideshow img').length;
                    //* we have to wait until the images load before we create the slideshow
                $('.frontend-slideshow img').load(function(){
                    $('.frontend-slideshow').frontendSlideshow();
                    return;
                    loaded_count++;
                    if(loaded_count == img_ref_count){
                        //console.log("image loaded",timeout_id);
                        if(!timeout_id){
                            clearTimeout(timeout_id);
                            $('.frontend-slideshow').frontendSlideshow();
                        }
                    }
                });
                //* if img load doesn't get called in 8 seconds, we process the slideshow anyways
                timeout_id = setTimeout(function(){
                        //console.log("timeout", timeout_id);
                        timeout_id = 0;
                        //$('.frontend-slideshow').frontendSlideshow();
                }, 8000);
            }
            //* Check if theres a newsmodule and set it up
            if($('.news-module').length > 0 && !$('.news-module').hasClass('news-module-init') ){
                //calculate how many news items there are
                var count = $('.news-module .jCarouselLite ul li').length;
                var button_list_holder = $(".news-module .button-list");
                var button_list = [];
                var button_list_arr = $(button_list_holder.find("button"));
                var button_list_holder_class = button_list_holder.selector;
                //for(var i=0 ; i< self.options.button_list_holder.find("button"); i++){
                $(button_list_holder.find("button")).each(function(i,e){
                    button_list[i]=button_list_holder_class+" ."+$(e).attr("class");
                });
                $(button_list_arr[0]).addClass("active");
                $('.news-module .jCarouselLite').jCarouselLite({
                    btnNext: ".news-module .switcher .btn-next",
                    btnPrev: ".news-module .switcher .btn-prev",
                    //btnGo: $(".news-module .button-list button")
                    scroll: 1,
                    visible: 1,
                    btnGo: button_list ,
                    afterEnd: function(el){
                        active = $(".news-module .jCarouselLite ul li").index(el);
                        active = parseInt(el.attr("class"));
                        var temp_index = active;
                        
                        $(button_list_arr).removeClass("active");
                        $(button_list_arr[temp_index-1]).addClass("active");

                    }
                });
                !$('.news-module').addClass('news-module-init');
            }
            if($(".main-block .sheet-form, .comment-form").length > 0){ 
                //console.log("comment form test", $(".main-block .sheet-form, .comment-form"));
                $( '.main-block .sheet-form, .comment-form' ).each(function(i,e){
                    if(!$(e).hasClass("form-init")){
                        $(e).frontendForm({ clear_form_on_success: true}); 
                        $(e).addClass("form-init");
                    }
                });
            }
            //* setting up comments pager
            if( $(".comment-list .comment-entry").length > 0 && !$(".comment-list").hasClass("pager-init")){
                var comment_list = $(".comment-list .comment-entry");
                var comment_pages = $(".comment-list .comment-page").hide();
                $("#comment-page-0").show();
                $(".comment-pager .page-btn").click(function(){
                    var target_id = $(this).attr("href");
                    $(".comment-list .comment-page").hide();
                    $(target_id).show();
                    //* setting other page btns inactive
                    $('.page-btn').removeClass('active');
                    $(this).addClass('active');
                    //* jump to a[name=comments];
                    
                    var target = $('a[name="comments"]');
                    if (target.length > 0) {
                        var pos = $(target[0]).offset();
                        window.scrollTo(pos.left, pos.top);
                    }
                    return false; //* don't return false, would rather have it jump to the start of the comments
                });
                $(".comment-pager .next-btn").click(function(){
                    var next =  $('.comment-pager .active').next('.page-btn');
                    if(next.length ==0){
                        next = $($('.comment-pager .page-btn')[0]);
                    }
                    next.trigger('click');
                    return false;
                });
                $(".comment-pager .prev-btn").click(function(){
                    var prev =  $('.comment-pager .active').prev('.page-btn');
                    if(prev.length ==0){
                        prev = $($('.comment-pager .page-btn'));
                        prev = $(prev[prev.length-1]); //* the last element
                    }
                    prev.trigger('click');
                    return false;
                });
                $(".comment-list").addClass("pager-init");
            }

            if($("#cse-content").length > 0){
                $("#cse-content").googleCSE({
                    completeCallback:_completeCallback,
                    startingCallback:_startingCallback,
                    googleSearchCX: GOOGLE_SEARCH_CX
                });
            }
            if($(".main-block object.fe-youtube").length > 0){
                $(".main-block object.fe-youtube").each(function(i,e){
                    var temp_height;
                    temp_height = parseInt($(e).attr("height"));
                    $(e).attr("height", temp_height+3); //* need to increase the height by a little to trigger the stillframe to be the right height
                    $(e).find("object").attr("height", temp_height+3);
                });
            }
            if($(".fe-video").length > 0){
                //* initialize video
                var  temp_video = $( '.fe-video' ).frontendVideo({
                    jwplayer_params:{
                        flashplayer: '/javascript/jwplayer/player.swf',
                        skin: '/images/flash/gsd_skin/gsd_skin.xml'
                    }
                });
            }
            if($(".fe-audio").length > 0){
                $(".fe-audio").css("height","40px"); //* force exact height for all audio, different from skin to skin
                $(".fe-audio").attr("height","40"); //* force exact height for all audio, different from skin to skin
                var  temp_video = $( '.fe-audio' ).frontendVideo({
                    jwplayer_params:{
                        flashplayer: '/javascript/jwplayer/player.swf',
                        "controlbar.position": "bottom",
                        "icons": false,
                        skin: '/images/flash/gsd_skin/gsd_skin.xml'
                    }
                });
            }
            if($(".nyro-btn-full").length > 0){
                $(".nyro-btn-full").nyroModal({
                    callbacks:{
				// beforeResize: function(elts) {
				// 	resizeModalImages(elts.contentWrapper.find( '.gal-holder' ));
				// 	verticallyCenterModalImages($('div.gallery > ul.slide > li', elts.contentWrapper.find( '.gal-holder' )));
				// },
                        beforeShowCont: function(elts){
        					//elts.elts.cont.addClass("slideshow-nyro");
        					elts.elts.cont.addClass("image-nyro");
                            $(".nyroModalClose").text("Return to previous page");
                        },
                        afterShowCont: function(elts){
                            elts.contentWrapper = $(".nyroModalDom");
                            $(".nyroModalCloseButton").show();
                            //self._initLightbox(elts);
                            //$(".nyroModalCont").addClass("slideshow-nyro");
                        }
                    }
                });
            }
            if($("#captcha-field").length > 0){ // dynamically create captcha widget
                $("#captcha-field .rtg-input").empty();
                $("#captcha-field .rtg-input").html('<div id="recaptcha_div"></div>');
                showRecaptcha("recaptcha_div");
            }

    },
    initialize :  function(){
        var self = this;
        //self.hide();
        
        //self.reinitialize();
        //self.show();
        //self.setContent($(self.contentHandler), self.currentLink);
            //^-- we call it like this instead of reinitialize because we don't want it to do other stuff involved in reinitialization
        self._initCustomSheetStuff(); //custom stuff like slideshows and google cse
    },
    enableFeed: function(){
            var news_feed_btn = $("#media-menu .news-feed-btn");
            if(news_feed_btn.length > 0 ){ //TODO a hacky way to disable the GSD news feed
                news_feed_btn.addClass("active");
            }
    },
    
    disableFeed: function(){
            var news_feed_btn = $("#media-menu .news-feed-btn");
            if(news_feed_btn.length > 0 ){ //TODO a hacky way to disable the GSD news feed
                news_feed_btn.removeClass("active");
            }
    },
    reinitialize :  function(){
        //alert("GSDSheet reinit!");
        var self = this;
        //all of the things one should check for when loading new sheet

        self._initCustomSheetStuff(); //custom stuff like slideshows and google cse


        if($(".close-btn a").length > 0){
            var temp_href =  $(".close-btn a").attr("href");
            if(temp_href[0] == "#" && temp_href.length == 1){
            }
        }
        
        $(".close-btn a").unbind("click.close");
        $(".close-btn a").bind("click.close", function(event){
            self.hide();
            var news_feed_btn = $("#media-menu .news-feed-btn");
            if(news_feed_btn.length > 0){ //TODO a hacky way to disable the GSD news feed
                news_feed_btn.removeClass("active");
            }
            //we're assuming the close button link points to the appropriate field page
            //so that it gets added to the history
            event.preventDefault();
            return false;
        });


        //setup mediamenu button 
        if($("#media-menu .news-feed-btn").length > 0){
            var news_btn =  $("#media-menu .news-feed-btn");
            //check if theres a list content with news-feed clas
            /*
            if($("#list-overlay .news-feed").length > 0){
                news_btn.addClass("active");
                self.isVisible = true;
            }
            */
            //$("#media-menu a:not(.news-feed-btn").click(function(){
            $("#media-menu a.email-btn").click(function(){

                news_btn.removeClass("active");
            })

            /*
            news_btn.click(function(event){
                alert("click ");
                event.preventDefault();
                //if(news_btn.hasClass("active")){
                if(news_btn.hasClass("active")){
                    news_btn.removeClass("active");                    
                    //self.hide();
                }
                else{
                    news_btn.addClass("active");
                    //self.show();
                }
            
            });
            */
        }
        
    },
	_breakoutLinkParts : function(link){
		var origin = window.location.protocol + '//' + window.location.host;
        var path;
        var query = '';
        var fragment = '';
		
        if ( link.indexOf(origin) == 0 ){
            path = link.substr( origin.length );
		}
        else if ( link.indexOf("/") == 0 ){
            path = link;
		}

        // Link must be site-relative or same origin to animate
		// If it's just "href='#top'" then we dont care
        if ( path == null)
            return;

        // Further uri parsing - separate path, query and fragment
        var i;

        if ( (i = path.indexOf('#')) >= 0 ) {
            fragment = path.substr( i+1 );
            path = path.substr( 0, i );
        }

        if ( (i = path.indexOf('?')) >= 0 ) {
            query = path.substr( i+1 );
            path = path.substr( 0, i );
        }

        // Link with path in fragment, e.g. #/home.html - use fragment as target
        if ( fragment.indexOf('/') == 0 ) {
            path = fragment;
            fragment = '';
        }
		return {
			'path': path,
			'fragment': fragment,
			'query': query
		};
	},
    //query is the broken up link
    //we use this to check if we need to perform ajax call
    //
    checkContent : function(query){ 
		var self = this;
        if(typeof self.currentLink != "undefined" && query.path == self.currentLink.path && query.query == self.currentLink.query){
            //alert("1: path is the same, just show saved content");
            //* we need to check if args contain x=1, if yes, we need to close the sheet    
                //* checking if the reopened sheet is a feed;
                    if($("#list-overlay").hasClass("feed-overlay")){
                        self.enableFeed();
                    }
                    else{
                        self.disableFeed();
                    }
                self.show(); //*if setContent is called, but the content is the same, then we just show it

				if(query.fragment != ""){
				    //* scroll to the anchor if there is one
					var target = $('a[name="' + query.fragment + '"]');

					if (target.length > 0) {
					  var pos = $(target[0]).offset();
					  window.scrollTo(pos.left, pos.top);
					}
				}else{
                    //* scrollTop since we loaded a new sheet
                    $(document).scrollTop(0);
                }
            return 1;
        }
        else if( typeof (query.query_hash.x) != 'undefined' && query.query_hash.x ){
            //* checking if the url contains the argument that closes the sheet, 
            //* if so, we close the sheet. This is to aid history browsing via
            //* the browser's back and forward buttons
                self.hide();
                self.disableFeed();
                return 1;
        }
        return 0;
    },
	setContent : function(content,query){
        //console.log("setContent called");
		var self = this;
        //if both the path and the GET params are the same, we can assume its the same page
        //we don't need to reload
        //if we want to be efficient, we can have AjaxSite do this comparison before
        //the ajax call
        //console.log("BlARGH");
        //console.log(query);
        //console.log(self.currentLink);
        
		//self.hide(); //hide it regardless of whether the content contains sheet stuff
        //alert("another test");
		content = $(content);
        //if new content not found, we assume its not for this obj

        var target_content;
        //console.log(content);
        if( ("#"+$(content).attr("id")) == self.contentHandler){
            //alert("found content ");
            target_content = $(content);
        }
        else if( $(content).find("#"+self.contentHandler).length > 0 ) {
            //alert("found content 2 ");
            target_content = $(content).find("#"+self.contentHandler);

        }
        else {
            //alert("failed found content ");
            return;
        }
        if($(target_content).html().length == 0){ //loading a fresh page, no content
            //alert("no page, hide");
            self.hide();
            return;
        }
        /*
		if( !( (("#"+$(content).attr("id")) == self.contentHandler) || 
			$(content).find("#"+self.contentHandler).length > 0) ||
            ($(content)) ){
            //alert("2: no new content for GSDSheet");
			return;
		}
        */
        //console.log(query.query, query.query_hash);
        
		//self.show();
		self._loadContent(content,query);
        //NOTE: for GSDField, $(".close-btn").trigger("click.close");
        //run ^--- or new GSDSheet().hide(); to hide the sheet
        //as we are assuming on new grid load, we do not want the sheet to show up
        //* Check whether we should toggle feed button here
        if($("#list-overlay").hasClass("feed-overlay")){
            self.enableFeed();
        }
        else{
            self.disableFeed();
        }
        //* scrollTop since we loaded a new sheet
        $(document).scrollTop(0);
	},
	_loadContent : function(content, query){
            //alert("loadContent called");
		//Note: for GSDField, process the query and deduce whether to add or 
			//sample: start=0&current=10&count=20
			//on the backend, if ajax ==1, then return only from current => current+count
				//return only the items in <li>, no "list-content" wrapper
			//on the frontend, if GET[current] == defined && GET[current] > 0, add content instead of refreshing the page
				// OR if no list-content wrapper, but ul wrapper, then add
		var self = this;
            if($(content).find(".news-feed").length == 0){
                //self.disableFeed();
            }
		//console.log((("#"+$(content).attr("id")) != self.contentHandler));
		if( !( (("#"+$(content).attr("id")) == self.contentHandler) || 
			$(content).find(self.contentHandler).length > 0) ){
			return;
		}
        this.currentLink = query; 
            //save the recent link used to retrieve the content it is setting
            //this is only saved IF the content is suitable for this obj
		//$(self.contentHandler).replaceWith("");
		if(("#"+$(content).attr("id")) == self.contentHandler ){
            //if is_visible, dont hide
            
            if(!self.isVisible){
                //self.hide();
                try{$(content).hide();}
                catch(err){
                    console.log(err, "This is ok. It only happens for 404 pages");
                }
            }
            $(content).find(".sheet").css("visiblity","hidden");
			$(self.contentHandler).replaceWith($(content) );
		}
		else{
            //$(content).find(self.contentHandler).hide();
            
            if(!self.isVisible){
                //self.hide();
                try{$(content).find(self.contentHandler).hide();}
                catch(err){
                    console.log(err, "This is ok. It only happens for 404 pages");
                }
            }
            $(content).find(self.contentHandler+ " .sheet").css("visiblity","hidden");
            //console.log("finding handler");
            //console.log($(content).find(self.contentHandler));
			$(self.contentHandler).replaceWith($(content).find(self.contentHandler));
		}
        self.show();
        self.reinitialize();
	},
	hide : function(){
        var self =this;
		$(self.contentHandler).hide();
        //self.isVisible = false;
        self.isVisible = $(self.contentHandler).is(":visible");
	},
	show : function(){
        var self =this;
		//$(self.contentHandler).show();
        self.isVisible = $(self.contentHandler).is(":visible");
        if(!self.isVisible){
    		$(self.contentHandler).fadeIn(1000);
        }
        self.isVisible = true;
	}
	


}






/*


// OLD CODE FOR REFERENCE

function getPageContent( link, jqPage, cback )
{
    var path = getPageURL( link );
    path     = path.replace( /\.html(\?.*)?$/, '.xml$1' );
    
    preparePageForContent( jqPage );

    var successCallback = cback;

    if( successCallback ==  null ) 
	successCallback = function (html) { 
	    showPageContent( jqPage, { 'html' : html } );
	}

    $.ajax( {
	url      : "/services/content" + path,
	type     : 'GET',
	error    : function (res) { return getPageContent('/error.html', jqPage, cback) },
	success  : successCallback
    } );

    return true;
} // getPageContent




*/

