var mydata;
var categories;
var types;
var hotellist;
var paginator;


function JSSelect(name,header,affectedlist,callback) {
  this.name = name;
  this.header = header;
  this.collapseheader = this.header.replace(/ /g,"");
  this.headerid = "#li" + header.replace(/ /g,"");
  this.myid = "#" + this.name;
  this.headerid = this.myid + " " + this.headerid + " a";
  this.affectedlist = affectedlist;
  this.callback = callback;
  this.prepare();
  this.bindSelectClicks();
}

JSSelect.prototype = {
  "name":"",
  "data":[],
  "revealed":0,
  "header":"",
  "collapseheader":"",
  "headerid":"",
  "headerid":"",
  "myid":"",
  "affectedlist":"",
  "callback":"",
  "showme":function() {
    $(this.myid + " li:hidden").show();
    $(this.myid + " .selected a").attr("class","none");
    $(this.headerid).attr("class","first");
    var me = this;
	  this.revealed = 1;
	  var bodyClick = function() { // when you click on the body, select hides
      $("body").bind('click',function() {
        me.hideme();
      });
    };
    setTimeout(bodyClick,25);
  },
  "hideme":function() {
    $(this.myid + " li").hide();
    $(this.myid + " .selected a").attr("class","first");
	  $(this.myid + " .selected").show();
	  this.revealed = 0;
    $("body").unbind('click');
  },
  "reset":function(){
    $(this.myid).empty();
	  this.prepare();
  },
  "getSelected":function(){
    var selected = $(this.myid + " .selected a").attr("id");
	  return selected;
  },
  "showhide":function() {
    if(this.revealed == 0) {
      this.showme();
    }
    else {  
      this.hideme();
      }
  },
  "bindSelectClicks":function() {
    var me = this;
    $(this.myid).click(function() {
        me.showhide();
    });
    
  },
  "prepare":function(){
    this.renderItem(this.header,"selected");
    this.addClicks();
  },
  "addClicks":function() {
    var me = this;
    $(this.myid + " li a").click(function () {
      if(me.revealed == 1 && $(this).attr("id") != me.collapseheader) {
        var thisparent = $(this).parent();
    		var oldselected = me.getSelected();
    		$(me.myid + " .selected a").attr("class","none");
    		  $(me.myid + " .selected").attr("class","unselected");
    			$(thisparent).attr("class","selected");
    			$(thisparent).show();
          var newselected = me.getSelected();
    			var thisvalue = $(this).attr("id");
    			if (me.affectedlist != "" && (oldselected != newselected)) {
    			  var mystuff = eval("mydata." + me.name);
            $.each(mystuff,function(i) {
               if(this.name == thisvalue){
                  eval(me.affectedlist + '.fill("' + me.name + '['+i+']","values");');
                  eval(me.affectedlist + '.showme();');
              }
            });
    			}
    			else if(me.callback != "" && $(this).attr("id") != me.collapseheader) {
    				eval(me.callback);
    			}
    		}
	  });	
  },
  "fill":function(filter,key){
    this.reset();
    var me = this;
    key = key || "none";
    if(key != "none"){
      me.data = eval("mydata." + filter + "." + key);
      $.each(me.data, 
			function() {
			  me.renderItem(this);	
			});
    }
    else {
      me.data = eval("mydata." + filter);
      $.each(me.data, 
			function() {
			  me.renderItem(this.name);	
			});
    }
		this.addClicks();
  },
  "renderItem":function(item,selected) {
    selected = selected || "unselected";
    var linkclass = "none";
    if(selected == "selected"){linkclass = "first";}
    var listid = item.replace(/ /g,"");
    $(this.myid).append('<li class="' + selected + '" id="li' + listid + '"><a href="javascript:void(0)" class="'+linkclass+'" id="' + listid + '">' + item + '</a></li>');
    if(selected == "unselected") {
      $(this.myid + " li#li" + listid).hide();
    }
  },
  "parseTemplate":function() {
			var regexp = /\{(\w+\.\w+)\}/g;
			return '"'+this.template.replace(regexp, "\"+$1+\"")+'"';
  }
} //END JSSelect


function DynamicList(element,data,template,columns) {
  this.element = element;
  this.items = data;
  this.displayeditems = this.items;
  this.count = this.items.length;
  this.template = template;
  this.tpl = this.parseTemplate();
  this.columns = columns;
  if(this.columns == true){this.floatclass = 'floatleft';}
}

DynamicList.prototype = {
  "element":"",
  "items":[],
  "displayeditems":[],
  "count":0,
  "template":'',
  "tpl":'',
  "columns":false,
  "columnNum":0,
  "floatclass":'noclass',
  "updateView":function() {
    this.clearElement();
    if(this.columns == true){this.floatclass = 'floatleft';this.columnNum = 0;}
    var me = this;
    if(this.displayeditems.length > 0) {
      $.each(this.displayeditems,function(i) {
          me.renderItem(this);
      });
    } else {
      $(this.element).append('There are no Hotels that matched your selection.  Please try again.');
    }
    
  },
  "clearElement":function() {
    $(this.element).empty();
  },
  "add":function(item) {
    this.items.push(item);
    this.count++;    
  },
  "updateCollection":function(items){
    this.removeAll();
    if(this.columns == true){this.floatclass = 'floatleft';}
    this.columnNum = 0;
    var me = this;
    $.each(items,function() {
      me.add(this);
    });
    this.updateView();
  },
  "remove":function(item) {
    this.items.pop(item);
    this.count--;
  },
  "removeAll":function(){
    this.items = [];
  },
  "updateCount":function() {
    this.count = this.items.length;
  },
  "updateDisplayedItems":function(offset,items) {
  	this.displayeditems = this.items.slice(offset,items);
  	this.updateView();
  },
  "renderItem":function(item) {
  		var me = this;
    	var code = "$(this.element).append("+me.tpl+")";
    	eval(code);
    	if (this.columns == true) {
					if(this.columnNum == 0){this.columnNum = 1;}
					else{this.columnNum = 0;$(this.element).append("<div class=\'clear\'></div>");}
					if(this.floatclass == 'floatleft'){this.floatclass = 'floatright';}
					else{this.floatclass = 'floatleft'}
			}
	},
  "parseTemplate":function() {
			var regexp = /\{(\w+\.\w+)\}/g;
			return '"'+this.template.replace(regexp, "\"+$1+\"")+'"';
  },
  "showme":function(){
    $(this.element).show();
  }
}

function Paginator(element,affected,perpage) {
  this.affected = affected;
  this.element = element;
  this.perpage = perpage || 12;
  this.locater = this.element + " span.paglocater";
  this.pagprev = this.element + " a.pagprev";
  this.pagnext = this.element + " a.pagnext";
  this.addClicks();
  this.set();
}

Paginator.prototype = {
  "count":0,
  "perpage":12,
  "pages":1,
  "current":1,
  "offset":0,
  "element":"",
  "affected":"",
  "locater":"",
  "pagprev":"",
  "pagnext":"",
  "set":function() {
  	this.count = this.affected.items.length;
  	this.pages = Math.ceil(this.count/this.perpage);
  	if(this.pages < 1) {this.pages = 1;}
  	this.current = 1;
  	this.update();
  },
  "update":function() {
    this.affected.updateDisplayedItems(this.offset,this.offset + this.perpage);
    this.updateView();
  },
  "next":function() {
    if(this.current < this.pages && this.pagnext.className != 'inactive') {
      this.current += 1;
      this.offset = this.offset + this.perpage;
      this.update();
    }
  },
  "prev":function() {
    if(this.current > 1 && this.pagprev.className != 'inactive') {
      this.current -= 1;
      this.offset = this.offset - this.perpage;
      this.update();
    }
  },
  "showme":function() {
    		$(this.element).toggleClass("hidden");	  	
  },
  "hideme":function() {
    $(this.element).toggleClass("hidden");
  },
  "updateView":function() {
    $(this.locater).text('Viewing Page '+this.current+' of ' + this.pages);
     if(this.current == 1){$(this.pagprev).addClass('inactive');}
     if (this.current == 2){$(this.pagprev).removeClass('inactive');}
     if (this.current == this.pages){$(this.pagnext).addClass('inactive');}
     if (this.current == this.pages -1 || (this.current == 1 && this.pages > 1)){$(this.pagnext).removeClass('inactive');}    
  },
  "addClicks":function() {
    var me = this;
    $(this.pagnext).click(function() {
      me.next();
    });
    $(this.pagprev).click(function() {
      me.prev();
    });
  }
  
  
}

function isArray(obj) {
   if (obj.constructor.toString().indexOf("Array") == -1) {
      return false;
    }
   else{
      return true;
    }
}

function randomize ( myArray ) {
  var i = myArray.length;
  if ( i == 0 ) return false;
  while ( --i ) {
     var j = Math.floor( Math.random() * ( i + 1 ) );
     var tempi = myArray[i];
     var tempj = myArray[j];
     myArray[i] = tempj;
     myArray[j] = tempi;
   }
   return myArray;
}

function compareNames(a,b) {
	alert(a.name);
	alert(b.name);
	return a.name - b.name;
}

function alphabetize ( myArray ) {
  ar = myArray.sort(compareNames);
  return ar;
}

String.prototype.stripSpaces = function() {
	str = this.replace(/\s/g, "");
	return str.replace(/&amp;/g, "&");	
}













$(document).ready(function() {
  $(affecteddiv).hide();
  $(".jsselect").toggleClass('hidden');
  $.getJSON("./bpjs/places.js",
    function(data){
			mydata = data;
			categories = new JSSelect("categories","Search Our Collection By Category","types");//name,header,affectedlist
		  categories.fill("categories");//node under mydata
      types = new JSSelect("types","Please Select A Type","","fillList()"); //name,header,affectedlist,callback
		  var allhotels = [];
		  $.each(mydata.hotels, function(i) { //store all hotels in JSON file as an array of objects
      	allhotels.push(mydata.hotels[i]);
     	});
     	switch(itemorder) {
     		 	case 'random':
     		 		randomize(allhotels);
     		 		break;
     		 	case 'alphabetical':
     		 		alphabetize(allhotels);
     		 		break;
     		 	default:
     		 		break;
     		 }
      hotellist = new DynamicList(affecteddiv,allhotels,template,usescolumns);//element,collection
		 	paginator = new Paginator(".paginator",hotellist,elementsperpage);//element, collection, affected Objects
		 	paginator2 = new Paginator(".paginator2",hotellist,elementsperpage);
		 	paginator.showme();//display paginator
		 	paginator2.showme();
		 	$(affecteddiv).show();
		 	$(".refresh").click(function() {
		 	 			hotellist.updateCollection(allhotels);
		 	 			paginator.set();
		 	 			paginator2.set();
		 	 			categories.fill("categories");
		 	 			types.reset();
	 	 	 });
		});
});


function fillList() {
  var data = mydata.hotels;
  var collection = [];
  $.each(data,function() {
	  var sCat = categories.getSelected().stripSpaces();
	  var sType = types.getSelected().stripSpaces();
	  sCat = sCat.toLowerCase();
		var mycat = eval("this." + sCat);
		if(isArray(mycat)) {
		  var me = this;
	  	$.each(mycat, function () {
				if(this.stripSpaces() == sType) {
					collection.push(me);
				}
			});
	  }
	  else {
		  if(mycat.stripSpaces() == sType) {
			 collection.push(this);
		}
	  }
	});
	hotellist.updateCollection(collection);
	paginator.set();
	paginator2.set();
}