/*extern document */
/*extern WCD, Ext */
/*extern propertylist */

/*jslint white: false */

// first, declare the namespace if it does not exist
if (WCD === null || typeof(WCD) !== 'object') {
    var WCD = {};
}

WCD.PropertyList = function (div) {
    this.filterCheckboxPrefix = 'wcdPropertyListShowCategoryCheckbox';

    this.divMain = Ext.get(div);
    //this.divFilter = Ext.insertFirst(this.divMain, { tag : 'div', id : 'wcdPropertyListFilter' }, true);
    this.divFilter = Ext.get('wcdPropertyListFilter');
    this.divGrid = Ext.get('wcdPropertyListGrid');

    //hide the noscript lists
    Ext.fly('wcdPropertyListNoScript').dom.style.display = 'none';

    this.header = '<div class="alternatingTableContainer"><table class="altRowTable propertyList" width="100%" cellspacing="0" cellpadding="0">';	
    this.footer = '</table></div>';
		
    this.propertyTypes = [];
    this.propertyTypesIndex = [];
    this.propertyTypesIndex[1] = 'Casino';
    this.propertyTypesIndex[2] = 'Casino cruise';
    this.propertyTypesIndex[3] = 'Cruise ship';
    this.propertyTypesIndex[4] = 'Dog track';
    this.propertyTypesIndex[5] = 'Dog track/Racino';
    this.propertyTypesIndex[6] = 'Horse track';
    this.propertyTypesIndex[7] = 'Horse track/Racino';
    this.propertyTypesIndex[8] = 'Jai-Alai';
    this.propertyTypesIndex[9] = 'Poker room';
		
    this.filteredProperties = [];
};


/*WCD.PropertyList.prototype.divMain;
WCD.PropertyList.prototype.divFilter;
WCD.PropertyList.prototype.divGrid;

WCD.PropertyList.prototype.filterTextBox;
WCD.PropertyList.prototype.filterTextBoxClear;

WCD.PropertyList.prototype.header;
WCD.PropertyList.prototype.footer;
WCD.PropertyList.prototype.filter;

WCD.PropertyList.prototype.properties;
WCD.PropertyList.prototype.filteredProperties;
WCD.PropertyList.prototype.propertyTypes;
WCD.PropertyList.prototype.propertyTypesFilter;
WCD.PropertyList.prototype.propertyTypesIndex;*/


WCD.PropertyList.prototype.redraw = function () {

	this.filterProperties();

	this.drawFilter();
	
	this.redrawGrid();
	
	this.addBehaviors();
		
};

WCD.PropertyList.prototype.addBehaviors = function() {
	Ext.addBehaviors({
	   // add a listener for click on all anchors in element with id foo
	   'a.rater@click' : function(){
			var parameterString = this.href.replace(/.*\?(.*)/, "$1"); // onclick="sndReq('j=1&q=2&t=127.0.0.1&c=5');
			var parameterTokens = parameterString.split("&"); // onclick="sndReq('j=1,q=2,t=127.0.0.1,c=5');
			var parameterList = new Array();

			for (j = 0; j < parameterTokens.length; j++) {
				var parameterName = parameterTokens[j].replace(/(.*)=.*/, "$1"); // j
				var parameterValue = parameterTokens[j].replace(/.*=(.*)/, "$1"); // 1
				parameterList[parameterName] = parameterValue;
			}
			var theratingID = parameterList['q'];
			var theVote = parameterList['j'];
			//var theuserIP = parameterList['t'];
			var theunits = parameterList['c'];
			
			//for testing	alert('sndReq('+theVote+','+theratingID+','+theunits+')'); //return false;
			
			sndReq(theVote,theratingID,theunits);
			//sndReq(5,1851,'127.0.0.1',5);
			//return false;
		}
	});
}

/* scans the properties to build an array of property types so we know what filters to display */
WCD.PropertyList.prototype.getPropertyTypes = function() {
	var keyVar, keyVar2;
	for ( keyVar in this.properties) {
		if(keyVar === 'casinos') {
			for (keyVar2 in this.properties[keyVar]) {
				if(typeof(keyVar2) !== 'function') {
					this.propertyTypes[this.properties[keyVar][keyVar2].casino_type] = true;
				}
			}
		}
	}
	
	this.propertyTypesFilter = this.propertyTypes;
};

WCD.PropertyList.prototype.redrawGrid = function () {
	var keyVar, keyVar2;
	
	var output = '';
	
	var altCounter = 0;

	//re-filter the properties
	//if it's not the first time drawing
	this.filterProperties(); 
	//}

	for ( keyVar in this.filteredProperties) {
		if(keyVar === 'casinos') {
			for (keyVar2 in this.filteredProperties[keyVar]) {
				if(typeof(keyVar2) !== 'function' && typeof(this.filteredProperties[keyVar][keyVar2].casinoid) !== 'undefined') {
					output = output + 
					'<tr class="altRowTable-d' + altCounter++%2 + '"><td class="propertyList-picture" valign="top">';

					if(this.filteredProperties[keyVar][keyVar2].thumbnailImage !== undefined && this.filteredProperties[keyVar][keyVar2].thumbnailImage !== null) {
						output = output + '<img src="' + this.filteredProperties[keyVar][keyVar2].thumbnailImage + '" width="' +  this.filteredProperties[keyVar][keyVar2].thumbnailImageWidth + '" align=left>';
					}
					
					output = output + '</td><td class="propertyList-main">' +

					'<div style="float: right; clear: none;">' +
					
					'<div id="unitlong' + this.filteredProperties[keyVar][keyVar2].casinoid + '">' +
					
					
					'<table border=0 cellpadding=0 cellspacing=0>' +
					'<tr><td><span class="wcdPropertyListRating">' +
					this.filteredProperties[keyVar][keyVar2].rating +
					'</span></td><td>'+

					'<ul id="unitul' + this.filteredProperties[keyVar][keyVar2].casinoid + '" class="unit-rating" style="width:95px;"><li class="current-rating" style="width:'+(this.filteredProperties[keyVar][keyVar2].rating)*19+'px;">Currently '+this.filteredProperties[keyVar][keyVar2].rating+'/10</li><li><a href="/layout/ratings/db.php?j=1&q=' + this.filteredProperties[keyVar][keyVar2].casinoid + '&c=5" title="1 out of 5" class="r1-unit rater imagelink" onclick="return false;">1</a></li><li><a rel=nofollow href="/layout/ratings/db.php?j=2&q=' + this.filteredProperties[keyVar][keyVar2].casinoid + '&c=5" title="2 out of 5" class="r2-unit rater imagelink" onclick="return false;">2</a></li><li><a rel=nofollow href="/layout/ratings/db.php?j=3&q=' + this.filteredProperties[keyVar][keyVar2].casinoid + '&c=5" title="3 out of 5" class="r3-unit rater imagelink" onclick="return false;">3</a></li><li><a rel=nofollow href="/layout/ratings/db.php?j=4&q=' + this.filteredProperties[keyVar][keyVar2].casinoid + '&c=5" title="4 out of 5" class="r4-unit rater imagelink" onclick="return false;">4</a></li><li><a rel=nofollow href="/layout/ratings/db.php?j=5&q=' + this.filteredProperties[keyVar][keyVar2].casinoid + '&c=5" title="5 out of 5" class="r5-unit rater imagelink" onclick="return false;">5</a></li></ul></td>' +
/*

					'<ul id="unitul' + this.filteredProperties[keyVar][keyVar2].casinoid + '" class="unit-rating" style="width:95px;"><li class="current-rating" style="width:'+(this.filteredProperties[keyVar][keyVar2].rating)*19+'px;">Currently '+this.filteredProperties[keyVar][keyVar2].rating+'/10</li><li><a href="javascript:null()" title="1 out of 5" class="r1-unit rater imagelink">1</a></li><li><a rel=nofollow href="javascript:null()"  title="2 out of 5" class="r2-unit rater imagelink">2</a></li><li><a rel=nofollow href="javascript:null()" title="3 out of 5" class="r3-unit rater imagelink">3</a></li><li><a rel=nofollow href="javascript:null()" title="4 out of 5" class="r4-unit rater imagelink">4</a></li><li><a rel=nofollow href="javascript:null()" title="5 out of 5" class="r5-unit rater imagelink">5</a></li></ul></td>' +
*/
					'</tr></table></div>' +
					
					
					'</div>';
					
					output = output + '<a href="' + this.filteredProperties[keyVar][keyVar2].url + '">' +
					'<h1>' + this.filteredProperties[keyVar][keyVar2].company + '</h1>' +
					'</a>';

					if(parseInt(this.filteredProperties[keyVar][keyVar2].casino_type,10) !== 1) { output = output + '<div class="wcdPropertyListPropertyType"><b>' + this.propertyTypesIndex[this.filteredProperties[keyVar][keyVar2].casino_type] + '</b></div>'; }
					
					
					
					var gaming_machines = ( parseInt(this.filteredProperties[keyVar][keyVar2].slot_machines,10) + parseInt(this.filteredProperties[keyVar][keyVar2].gaming_machines,10));

					if(gaming_machines > 0) { output = output + '<span class="wcdPropertyListStats"><img src="/images/sslot.gif" width=8 height=8> Gaming machines: <b>' + gaming_machines + '</b></span><br>'; }
					if(this.filteredProperties[keyVar][keyVar2].table_games > 0) { output = output + '<span class="wcdPropertyListStats"><img src="/images/poker.gif" width=8 height=8> Table games: <b>' + this.filteredProperties[keyVar][keyVar2].table_games + '</b></span>'; }

					if(this.filteredProperties[keyVar][keyVar2].summary > '') {output = output + '<p class="wcdPropertyListPropertyDescription">' + this.filteredProperties[keyVar][keyVar2].summary + '... <a href="' + this.filteredProperties[keyVar][keyVar2].url + '">more</a></p>'; }

					output = output + '</td></tr>';
				}
			}
		}
	}
	
	
	this.divGrid.update(this.header+output+this.footer);	
};

WCD.PropertyList.prototype.drawFilter = function () {
	var typeKeyVar;
	
	var filter = '<div class="alternatingTableContainer"><table border=0 class="altRowTable propertyList" width="100%"><tr class="altRowTable-d0 wcdPropertyListFilter"><td colspan=2 valign=top style="padding-bottom: 5px;"> ';
	
	var rowcounter = 0;

	filter = filter + '<table border=0>';
	for(typeKeyVar in this.propertyTypesIndex) {
		if(typeof(typeKeyVar) !== 'function' && this.propertyTypes[typeKeyVar] === true) {
			if(rowcounter % 2 === 0) { filter = filter + '<tr>'; }
			filter = filter + '<td valign=top style="padding-right: 5px;">';
			filter = filter + '<input type="checkbox" id="' + this.filterCheckboxPrefix + typeKeyVar + '" checked="checked"> <a href="#" onClick="propertylist.showOneCategory('+ typeKeyVar +'); return false;">' + this.propertyTypesIndex[typeKeyVar];
			if(parseInt(typeKeyVar,10) !== 8) { filter = filter + 's'; }
			filter = filter + '</a> ';
			filter = filter + '</td>';
			if(rowcounter % 2 !== 0) { filter = filter + '</tr>'; }
			rowcounter++;
		}
	}
	filter = filter + '</table>';

	filter = filter + '</td>';
	filter = filter + '<td align="right" width="210" valign=top style="visibility: hidden;">';
	filter = filter + 'Sort: <select id="wcdPropertyListSortCombo">' +
		'<option value="ratingdesc">by rating (highest to lowest)</option>' +
		'<option value="ratingasc">by rating (lowest to highest)</option>' +
		'<option value="namealpha">by name (a - z)</option>' +
		'<option value="namereversealpha">by name (z - a)</option>' +
		'</select><br>';
	filter = filter + 'Filter: <input type="text" id="wcdPropertyListFilterTextBox">';
	filter = filter + '<br><div id="wcdPropertyListFilterTextBoxClear"><a href="#" onClick="propertylist.filterTextBoxClear(); return false;">Clear filter</a></div> ';
	filter = filter + '</td>' +
		
		'</tr></table></div>';
	
	//Ext.fly('wcdPropertyListFilter').update(filter);
	this.divFilter.update(filter);	
	
	//add event listeners for checkboxes
	for(typeKeyVar in this.propertyTypesIndex) {
		if(typeof(typeKeyVar) !== 'function' && this.propertyTypes[typeKeyVar] === true) {
			/*Ext.addBehaviors(
			{
			   // add a listener for click on all anchors in element with id foo
			   '#wcdPropertyListShowCasinosCheckbox'+ typeKeyVar +' @change' : this.showCasinosCheckboxChange.createDelegate(this)
			}
			);*/
			Ext.get(this.filterCheckboxPrefix+typeKeyVar).on('change', this.propertyFilterCheckboxChange.createDelegate(this));
		}	
	}

	this.filterTextBox = Ext.get('wcdPropertyListFilterTextBox');
	this.filterTextBox.on('keypress', this.filterTextBoxChange.createDelegate(this));

	this.filterTextBoxClearLink = Ext.get('wcdPropertyListFilterTextBoxClear');
	this.filterTextBoxClearLink.setStyle('display', 'none');

};


WCD.PropertyList.prototype.propertyFilterCheckboxChange = function(e, target) {

	var propertyType = parseInt(target.id.substring(this.filterCheckboxPrefix.length),10);

	if(target.checked) {
		propertylist.propertyTypesFilter[propertyType] = true;
	} else { 
		propertylist.propertyTypesFilter[propertyType] = false;
	}
			
	propertylist.redrawGrid();
};

WCD.PropertyList.prototype.showOneCategory = function(category) {
	var checkboxEl, typeKeyVar;
	for(typeKeyVar in propertylist.propertyTypesIndex) {
		if(typeof(typeKeyVar) !== 'function') {
			propertylist.propertyTypes[typeKeyVar] = false;
			
			checkboxEl = Ext.get(this.filterCheckboxPrefix+typeKeyVar);
			if(checkboxEl) {
				checkboxEl.dom.checked = false;
			}
		}
	}
	
	propertylist.propertyTypes[category] = true;
	Ext.get(this.filterCheckboxPrefix+category).dom.checked = 'checked';

	propertylist.redrawGrid();
};

WCD.PropertyList.prototype.filterTextBoxChange = function(e, target) {
	this.filterTextBoxClear.setStyle('display', 'inline');

	propertylist.redrawGrid();
};

WCD.PropertyList.prototype.filterTextBoxClear = function(e, target) {
	this.filterTextBox.dom.value = '';
	this.filterTextBoxClear.setStyle('display', 'none');

	propertylist.redrawGrid();
};



WCD.PropertyList.prototype.filterProperties = function() {
	var keyVar, keyVar2;
	var altCounter = 0;
	this.filteredProperties = [];
	
	for ( keyVar in this.properties) {
		if(keyVar === 'casinos') {
			for (keyVar2 in this.properties[keyVar]) {
				//if the tickbox is allowing us to display this time of property
				if(typeof(keyVar2) !== 'function' && this.propertyTypesFilter[this.properties[keyVar][keyVar2].casino_type] !== false) {
					if (this.filteredProperties[keyVar] === null || typeof(this.filteredProperties[keyVar]) === "undefined") { this.filteredProperties[keyVar] = []; }
					
					//apply a text filter if there is one
					if(typeof(this.filterTextBox) === 'undefined' || this.filterTextBox === '') {
						this.filteredProperties[keyVar].push(this.properties[keyVar][keyVar2]);
					} else {
						var pos = this.properties[keyVar][keyVar2].name.indexOf(this.filterTextBox.dom.value);

						if (pos >= 0) {
							this.filteredProperties[keyVar].push(this.properties[keyVar][keyVar2]);
						}
					}
				}
			}
		}
	}

	//document.getElementById('wcdPropertyListDebug').innerHTML = dump(this.filteredProperties);

};

WCD.PropertyList.prototype.setProperties = function (properties) {
	this.properties = properties;
	this.getPropertyTypes();
	
	this.redraw();
};

WCD.PropertyList.prototype.sortRecordsByAlpha = function () {
/*	var store = new Ext.data.SimpleStore({
	  fields: ['abbr', 'state'],
	  data : Ext.exampledata.states // from states.js
	});
	
	var combo = new Ext.form.ComboBox({
	  store: store,
	  displayField:'state',
	  typeAhead: true,
	  mode: 'local',
	  triggerAction: 'all',
	  emptyText:'Select a state...',
	  selectOnFocus:true,
	  width:135
	});
*/
};
WCD.PropertyList.prototype.reorderRecordsByRating = function () {};


/* ComboBox filterBy extension */

Ext.form.ComboBox.prototype.filterBy = function(fn, scope) {
	var ds = this.store;
	ds.filterBy(fn, scope);
	ds.realSnapshot = ds.snapshot;
	ds.snapshot = ds.data;
};

Ext.form.ComboBox.prototype.clearFilter = function(suppressEvent) {
	var ds = this.store;
	if (ds.realSnapshot && ds.realSnapshot !== ds.snapshot) {
		ds.snapshot = ds.realSnapshot;
		delete ds.realSnapshot;
	}
	ds.clearFilter(suppressEvent);
};

/* hidden field */

Ext.form.HiddenField = function(config){
    config.type = 'hidden';
    config.inputType = 'hidden';
    Ext.form.HiddenField.superclass.constructor.call(this, config);
};
Ext.extend(Ext.form.HiddenField, Ext.form.TextField,  {
    // private
    onRender : function(ct, position){
        if(this.el){
            this.el = Ext.get(this.el);
            if(!this.target){
                ct.dom.appendChild(this.el.dom);
            }
        }else {
            var cfg = {tag: "input", type: "hidden"};
            if(!cfg.name){
                cfg.name = this.name || this.id;
            }
            this.el = ct.createChild(cfg, position);
        }
        this.el.dom.readOnly = true;
        this.el.dom.parentNode.parentNode.style.display = 'none';
        this.initValue();
    }
});



Ext.example = function(){
    var msgCt;

    function createBox(t, s){
        return ['<div class="msg">',
                '<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>',
                '<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc"><h3>', t, '</h3>', s, '</div></div></div>',
                '<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>',
                '</div>'].join('');
    }
    return {
        msg : function(title, format){
            if(!msgCt){
                msgCt = Ext.DomHelper.insertFirst(document.body, {id:'msg-div'}, true);
            }
            msgCt.alignTo(document, 't-t');
            var s = String.format.apply(String, Array.prototype.slice.call(arguments, 1));
            var m = Ext.DomHelper.append(msgCt, {html:createBox(title, s)}, true);
            m.slideIn('t').pause(1).ghost("t", {remove:true});
        },

        init : function(){   }
    };
}();

//Ext.onReady(Ext.example.init, Ext.example);


Ext.onReady(function () {

	Date.patterns = {
	    ISO8601Long:"Y-m-d H:i:s",
	    ISO8601Short:"Y-m-d",
	    ShortDate: "n/j/Y",
	    LongDate: "l, F d, Y",
	    FullDateTime: "l, F d, Y g:i:s A",
	    MonthDay: "F d",
	    ShortTime: "g:i A",
	    LongTime: "g:i:s A",
	    SortableDateTime: "Y-m-d\\TH:i:s",
	    UniversalSortableDateTime: "Y-m-d H:i:sO",
	    YearMonth: "F, Y",
	    ShortMonthDayYear: "m/d/y"
	};
	//WCD.util.loginForm();
	//Ext.MessageBox.alert('test', 'test');
	//alert('test');
	//WCD.util.loginForm();
	//bind login button to login form
	/*Ext.get('wcdUserPanelLoginLink').on('click', function(e){
		WCD.util.loginForm();
	});*/
});