﻿if(typeof parkside == "undefined") var parkside = new Object();

// Constructor
parkside.paging = function(p_cfc_component, p_settings, p_num_items) {
	this.cfc_component = p_cfc_component;
	this.settings = p_settings;
	this.num_items = p_num_items;
	
	var that = this;
	this.listener = function(ev) { that.handleDeepLinkChange(ev); };

	SWFAddress.addEventListener( SWFAddressEvent.CHANGE, this.listener );
}

/// Static variables
//parkside.paging.first_run = true;

/// Static methods
// parkside.paging.method = function() {}

/// Class members
parkside.paging.prototype = {
	/// class variables
	cfc_component: ""
	, num_items: 5
	, last_link: null
	, settings: null
	, last_page: 1

	/// class methods
	
	/// sets deep link
	, loadPage: function( page ) {
				
		/// force reload when clicked or called
		this.last_page = 0;
				
		/// set deep link
		if (SWFAddress && SWFAddress.setValue) {
			SWFAddress.setValue( "" + page ); // this throws SWFAddressEvent.CHANGE
		} else {
			this.loadPageRequest ( page );
		}
		
	}
	/// handles changes in deep link
	, handleDeepLinkChange: function (event) {
				
		if (event.path.length > 1 && !isNaN(event.path.replace("/", "") && this.last_page != event.path.replace("/", "")) ){
			this.loadPageRequest ( event.path.replace("/", "") );
		} else if (event.path == "/" &&  this.last_page != 1 ) {
			this.loadPageRequest ( 1 );
		}
	}
	/// performs actual request
	, loadPageRequest: function( page ) {
		this.last_link = $(".item_list_paging .active");

		var params = new Object();
		params.cfc_component_name = this.cfc_component;
		params.current_page = page;
		params.num_items =  this.num_items;
		params.settings = $.toJSON(this.settings);
		
		/// transfer query string to the cfc
		var qa = window.location.search.substring(1).split("&");
		for (i=0;i<qa.length;i++) {
			kv = qa[i].split("=");
			params[kv[0]] = kv[1];
		}
		
		this.last_page = page;
		/// stupid scope problems 
		var that = this;
		$.post("custom/modules/list/paging.cfc?method=loadPage", params, function(cfc_result, status) {that.loadPageResponse(cfc_result);}, "json");
		
	}
	/// process the response
	, loadPageResponse: function ( cfc_result ) {

		//SWFAddress.removeEventListener( SWFAddressEvent.CHANGE, this.listener );

		if (cfc_result.HTML.length != 0 && this.last_link != null) {
			var parent = this.last_link.parent();
			while( !parent.hasClass( "item_list_wrapper" ) )
				parent = parent.parent();
			parent.html( cfc_result.HTML );
		}
		
		$(document).scrollTop(0);
		
		initPageSettingsOnAJAXCall();
	}
}

