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

function GSDField(currentLink){
    //console.log(currentLink);
    this.currentLink = currentLink;
}

GSDField.prototype = {
    //some options
    currentLink     : {path:"", fragment:"", query:""},   //holds link_obj parsed by AjaxSite: 
                            // {path:"", fragment: "", query :""}
    currentBreadcrumb: null,
    contentHandler  : "#list-content", //default handler for fields //list-content > ul
    isVisible       : true,
    footerHeight       : 210,
    animationDuration : 100, //200
    currentIndex : 0,
    increaseAmount: 10,
    GSDSheet_obj : '',
    cells           : [], //stores the cells currently available,
    reduce_animation  : false,
    initialize : function(){
        
        var self = this;
        if($.browser.msie && parseInt($.browser.version) < 9){
            self.reduce_animation = true;
        }
        self.reinitialize();
    },

    reinitialize :  function(additionalCells){
        //return false; //TODO, we must have reinit process the additional field items properly for IE7, currently it fails probably because there's a lot of stuff to do for it's weak js engine
        var self = this;
        var all_cell_li;
        var isLoad = false;
        $(self.contentHandler + " li.padding").remove(); //clean up page first
        //console.log("LOADMORE CELL");
        //console.log($(additionalCells).has(".load-more"));
        var last_li = $(self.contentHandler + " li:not('.padding')");
        //console.log("additionalCells", additionalCells);
        //Dumper(additionalCells);
        
        //console.log(additionalCells);
        //console.log(last_li);
        //console.log("has");
        //console.log($(last_li[last_li.length-1]));
        if(($(last_li[last_li.length-1]).has(".load-more")).length > 0){
            last_li = last_li[last_li.length-2]; //skip over load-more
            //alert("skipping load more");
        }
        else{
            last_li = last_li[last_li.length-1];
        }
        if(additionalCells != undefined){
            isLoad = true;
            all_cell_li = additionalCells;
            //prepend stuff
            //alert("adding/reinitializing additional cells");
            //console.log("adding additiional cells");
            //console.log(last_li);
            //last_li.after(additionalCells); //loading more cells
            $(additionalCells).insertAfter(last_li);
        }
        else{
            all_cell_li = $(self.contentHandler + " li");
        }
        
        //alert("blargh0:"+all_cell_li.length +" reduce anim: "+ self.reduce_animation);
        if(all_cell_li.length <= 0){
            return;
        }

        //**********************************************
        //* Setting up field action as a whole
        //*  -this include shifting load-more button
        //*  -and inserting more li's as height increases
        //**********************************************
            if(additionalCells != undefined){
                //* if we're simply adding additional cells, we don't need to init
                self._resizeField(self); //init = 1 //TODO IE7 issues lies here
            }
            else{
                self._resizeField(self, 1); //init = 1 //TODO IE7 issues lies here
            }
            //hiding the cells to animate in;

        //* NOTE: ie7 doesn't link unbinding and rebinding, or binding multiple times
            //* NOTE: ie7 also seems to fail with this fix AND not using reduced animatiuon
            //* Must return here?
        if(!$(window).data("resize") ){
            $(window).resize(function(){self._resizeField(self)});
            $(window).data("resize",true);
        }
        //* initialize state of field
        //var cell_height = $(self.contentHandler + " li").height();
    if(!self.reduce_animation){
        var cell_width = $(all_cell_li).outerWidth();
        //* setting all cells to be hidden, then animating....
        //**********************************************
        //* Setting up each individual grid action
        //**********************************************
        //$(self.contentHandler + " li .cell-hover").hide(); //force it to hide
        $(all_cell_li).find(" .cell-hover").hide();
        $($(all_cell_li).find(".cell")).css({
            "left": "-"+cell_width+"px",
            "opacity":"0.0",
            "visibility":"visible"
        });
            //animate in cells
        var i =0;
        //console.log("allcell");
        //console.log($(all_cell_li));
		self._initHover($(all_cell_li[0]));
        $(all_cell_li[i]).find(" .cell").animate({
            "left":"0px",
            "opacity":"1.0"
        },{
            duration: self.animationDuration,
            complete: function(){
                //console.log($(all_cell_li[i]));
                i++;
                if(i< all_cell_li.length){
                    for(; i< all_cell_li.length; i++){
                        //console.log("index: "+i);
                        //console.log($(all_cell_li[i]).find(" .cell"));
                        if($(all_cell_li[i]).find(" .cell").length > 0 && !$(all_cell_li[i]).hasClass("remove")){
                            self._initHover($(all_cell_li[i]));
                            $(all_cell_li[i]).find(" .cell").animate({"left":"0px",
                                "opacity":"1.0"}, {
                                duration: self.animationDuration, 
                                complete: arguments.callee
                            });
                            break;
                        }
                    }

    
                }
            }
            
            
        });
    }
    else{
        $($(all_cell_li).find(".cell")).css({
            "visibility":"visible"
        });
    }

    },
    _initHover: function(e){
            var cell_hover = e.find(".cell-hover");
            //* reverting css to support hover animation; thus there's css fallback
                e.find(".cell").css("display","block");
                cell_hover.css("position","absolute");
            //**********
            e.unbind("mouseover");
            e.unbind("mouseleave");
            cell_hover.unbind("click");
            e.mouseover(function(event){
                //var e = $(event.target);
                //console.log(e);
                var window_width = $(window) .width();
                //console.log(window_width);
                if($(".no-wait").length == 0){
                cell_hover.delay(300).fadeIn(1, function(){
                    e.addClass("hover");
                });
                }
                else{
                    cell_hover.show();
                    e.addClass("hover");

                }
                //e.addClass("hover");
                //cell_hover.delay(600).show();
                /*
                cell_hover.delay(600).animate({
                    "display":"block"
                },{
                    duration:1,
                    queue:true,
                });
                */
                //check if cell_hover is to the right, we move it
                var temp_position = e.position();
                var temp_width = cell_hover.outerWidth();
                //console.log(temp_position.left);
                //console.log(temp_width);
                //console.log( "width 2:"+ window_width_2);
                
                if(temp_position.left + temp_width > window_width) {
                    cell_hover.addClass("right");
                }
            });
            e.mouseleave(function(){
                cell_hover.clearQueue();
                if(!cell_hover.hasClass("active")){
                  if($(".no-wait").length == 0){
                    cell_hover.fadeOut(100, function(){
                    //cell_hover.hide();
                    cell_hover.removeClass("right");
                    e.removeClass("hover");
                    });
                  }
                  else{
                    cell_hover.hide();
                    cell_hover.removeClass("right");
                    e.removeClass("hover");
                  }
                }
            });
			/*
            cell_hover.click(function(){
                if(cell_hover.hasClass("active")){
                    cell_hover.removeClass("active");
                }
                else{
                    cell_hover.addClass("active");
                }
            });
			*/
    },
    _resizeField : function(self, init){
            if($(self.contentHandler+" li").length == 0){return;}
            //self = this;
            //insert or remove li's until load-more is on the left most cell
            $(self.contentHandler + " li.padding").remove();

            
            //if($(self.contentHandler + " .load-more").length <= 0){return;}
            //pad before load-more
            //var target_left = $(all_cell_li[0]).position().left;
            //console.log($(self.contentHandler + " li"));
            var window_height = $(window).height();
            var ul_height = $(self.contentHandler+" ul").height();
            var li_height = $(self.contentHandler+" li").height();
            var all_li_length = $(self.contentHandler+ " li").length-1;
            /*
            if(window_height < li_height*2 + self.footerHeight){
                window_height = li_height*2+ self.footerHeight; //MINIMUM height of window
            }*/
            
            if(window_height < li_height*4 + self.footerHeight){
                //window_height = li_height*4+ self.footerHeight; //MINIMUM height of window
            }
            var target_left = $($(self.contentHandler + " li")[0]).position().left;
            //* CALCULATING SIZES: WINDOW SIZE AND HOW MANY LIS CAN FIT IT IN
            var base_window_width = $(window).width();
            var base_window_height = $(window).height();
            var base_li_width  = $($(self.contentHandler + " li")[0]).outerWidth();
            var base_li_height  = $($(self.contentHandler + " li")[0]).height();
            var grid_width = parseInt(base_window_width / base_li_width);
            var grid_height = parseInt(base_window_height / base_li_height)+1;  //* the plus one is to pad the row so it gets pushed out
                                                                                //* TODO: or we can Math.ceil it
            var base_size = grid_width*grid_height;
            //alert( base_window_width+"; "+base_window_height+"; "+base_li_width+"; "+base_li_height+"; "+grid_width+"; "+grid_height+";"+base_size);

            if(init && $(self.contentHandler + " .load-more").length > 0){
                //* if there's a .load-more button on screen, then we assume we can truncate content
                //* update the count, and allow ajax to handle inserting more content 
                //* only truncate content IF self.currentIndex == 0, else we should allow
                //* content to grow
                var load_more = $(self.contentHandler + " li:has(.load-more)"); 
                    self.current_index = 0;

                    //* if this is the first time we're loading a new grid
                    //* we truncate the content until the load-more button fits

                    //* since we want to offset the loadmore cell
                    while( $(self.contentHandler + " li").length > base_size + 3){ //* assume the last li is the loadmore
                        load_more.prev().addClass("remove");
                        load_more.prev().remove();
                        all_li_length = $(self.contentHandler+ " li").length -1;
                    }

                    //* Saving new increase amount

                    var init_amount = $(self.contentHandler + " li:not(' :has(.load-more), .padding')").length;
                    self.increaseAmount = init_amount-2;  //* we remove 2 from count, trying to keep the load-more button on the same spot
                        //* If the backend adhere's to the increaseAmount, 
                        //* then we can simply request the correct amount to 
                        //* position the load-more properly as the 3rd cell
                    
                    //* We now truncate the content so that it's 2 cells over ONLY when we receive new content NOTE: don't do this


                    //* updating self.currentIndex; we subtract 2 from cell count because
                    //* of the load-more button AND we're returning index, not count
                    //self.currentIndex = $(self.contentHandler+" li:not('.padding')").length - 2;
                    self.currentIndex = $(self.contentHandler+" li:not('.padding')").length - 1;
                    //* check if there's a start value in the Get params...
                    var getParams = breakoutUrlVars(self.currentLink.query); //*TODO!
                    if(typeof getParams.start != "undefined"){
                        //self.currentIndex += parseInt(getParams.start);
                        self.currentIndex = parseInt(getParams.start);
                    }
                        //update load-more href;
                        //load_more.find("a").attr("href", self.currentLink.path+"?start="+(self.currentIndex+self.increaseAmount)+"&count="+self.increaseAmount);
                        load_more.find("a").attr("href", self.currentLink.path+"?start="+(self.currentIndex)+"&count="+self.increaseAmount);
           
            }
            //* pad until the end of row
                //* past the location of the last li
            var locator = $("<li class='locator'>&nbsp;</li>");
            //alert("test");
            //console.log("test");
            //console.log(locator);
            //console.log(target_left);
            $(self.contentHandler+ " ul").append(locator);

            //* pad empty rows until it fits screen
            //console.log("window height: "+ window_height);
            //console.log("ul height: "+ ul_height);
            //console.log(locator.position());
            while( $(self.contentHandler + " li").length < (grid_width* (grid_height-1) ) ){
                    locator.before("<li class='padding'>&nbsp;</li>");
            }

                var row_pad_modulo = ($(self.contentHandler + " li").length%grid_width) -1; //* -1 for the locator 
                if(row_pad_modulo == -1){row_pad_modulo = grid_width-1;}
                for(var i=row_pad_modulo; i < grid_width; i++){
                    locator.before("<li class='padding'>&nbsp;</li>");
                }
            locator.remove();

            
    },
    //query is the broken up link
    //we use this to check if we need to perform ajax call
    //
    checkContent : function(query){
        var self = this;
        //console.log( "currentLink:", self.currentLink, "new query", query);
        if(typeof self.currentLink != "undefined" && query.path == self.currentLink.path && query.query == self.currentLink.query){
            //* since this url is a field url, we hide the sheet
            $("#list-overlay").hide();
            //* we also check if the feed utility nav is toggled, we inactivate it
            if($("#list-overlay").hasClass("feed-overlay")){
                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");
                }
            }
            return 1;
        }
        return 0;
    },
	setContent : function(content,query, suppress_hide){
        //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);
        if(query.path == self.currentLink.path && query.query == self.currentLink.query){
            //alert("1: path is the same, just show saved content");
            self.show(); //if setContent is called, but the content is the same, then we just show it
            return;
        }
        if(typeof self.currentLink != 'undefined' && query.path != self.currentLink.path){
            //* different path, scrollTop
            $(document).scrollTop(0);
        }
        
        //alert("another test");
		content = $(content);
        //if new content not found, we assume its not for this obj
		if( !( (("#"+$(content).attr("id")) == self.contentHandler) || 
			$(content).find("#"+self.contentHandler).length > 0) ){
            //alert("2: no new content for GSDField");
			return;
		}
        
		self._loadContent(content,query);

        //* we checkif currentBreadcrumb == null, if yes, we save the breadcrumb we have
        
        //NOTE: for GSDField, $(".close-btn").trigger("click.close");
        //run ^--- or new GSDSheet().hide(); to hide the field
        //as we are assuming on new grid load, we do not want the sheet to show up
        if(!(typeof suppress_hide != 'undefined' && suppress_hide)){
            new GSDSheet().hide();
        }
	},
    _retrieveQuery : function(variable, query){
        variable = variable.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
        var regexS = "[\\?&]"+variable+"=([^&#]*)";
        var regex = new RegExp( regexS );
        var results = regex.exec( query.path+"?"+query.query );
        //console.log(regexS);
        //console.log(results);
        if( results == null )
            return "";
        else
            return results[1];
    },
	_loadContent : function(content, query){
		//Note: for GSDField, process the query and deduce whether to add or 
			//sample: start=0&current=10&count=20 //TODO
			//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;
    
		//console.log((("#"+$(content).attr("id"))));
		//console.log((("#"+$(content).attr("id")) == self.contentHandler));
		//console.log($(content).find("#"+self.contentHandler).length);
		if( !( (("#"+$(content).attr("id")) == self.contentHandler) || 
			$(content).find("#"+self.contentHandler).length > 0) ){
			return 0;
		}

        var temp_currentLink = self.currentLink;
        self.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("");

        var new_content;
		if(("#"+$(content).attr("id")) == self.contentHandler ){
			//$(self.contentHandler).replaceWith($(content) );
			new_content = $(content);
		}
		else{
            //console.log("finding handler");
            //console.log($(content).find(self.contentHandler));
			//$(self.contentHandler).replaceWith($(content).find("#"+self.contentHandler));
			new_content = $(content).find("#"+self.contentHandler);
		}
        

        //Parse GET params and then check if we want to add or replace
        //console.log(query);
        var current_index = self._retrieveQuery("current", query);
        var start_index = self._retrieveQuery("start", query);
        //console.log("current: "+current_index);
        //console.log("start: "+ start_index);

        var content_li;
        if(start_index != 0 && start_index != current_index && temp_currentLink.path == query.path){ //* TODO: need to update check here cause if currentLink base path != query, then we need to do else
            //we know its loadmore
            //update loadmore href
            //console.log($(".load-more a"));
            /*
            if($(".load-more a").length > 0){
                $(".load-more a").attr("href" ,query.path+"?start=0&current="+self.currentIndex+"&count="+self.increaseAmount);
            }
            */
            //$(new_content).find("li:has(.load-more)").remove(); // DO NOT REMOVE THE NEW LOADMORE, REMOVE THE CURRENT ONE
            $(self.contentHandler).find("li:has(.load-more)").remove(); //remove the current loadmore
            content_li = $(new_content).find("li");
            //console.log("new_content");
            //console.log(new_content);
            self.reinitialize(content_li);
        }
        else{
            self.currentIndex = 0; //if it's a new field page, then we reset currentIndex;
            self.hide();
			$(self.contentHandler).replaceWith(new_content);
            
            self.reinitialize();
            self.show();
        }
        //* load new media menu
        if($(content).find("#media-menu").length > 0){
            
			$("#media-menu").replaceWith($(content).find("#media-menu"));
        }
			return 1;
	},
	hide : function(){
        var self =this;
		$(self.contentHandler).hide();
        self.isVisible = false;
	},
	show : function(){
        var self =this;
		$(self.contentHandler).show();
		//$(self.contentHandler).fadeIn();
        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




*/

