var e = Array();
var newe = Array();
var playerid = '';
var fields = Array('dob','dod','position','hometown','college_career','links','after_college','where_now','contact_info','player_first','player_last');
edittext = "Edit this field";
editclass = "lightgray";
ineditmode = 0;
var newmessage;
var newmessageheader;
hasprimaryimage = 0;

String.prototype.br2nl =
  function() {
    return this.replace(/<br\s*\/?>/mg,"\n");
  };

var editable = function(elementId, config){
// private vars
// set some defaults for our object.
var _defaultAjaxMethod = 'POST'
var _deafultCssClass = "editable";

this.config = config;

// test what we've beplayer-message-board_topic_3messageen passed.
var _checkConfig = function(config){
// checking its a literal.
if (config.constructor != Object) {
throw new Error("Invalid Config");
}

if(config.extraParams)
{
if(config.extraParams.constructor !== Object)
{
throw new Error("Invalid config value extraParams - must be a literal.");
}
}

if(config.paramName)
{
if(config.paramName.constructor !== String)
{
throw new Error("Invalid config value paramName - must be a string.");
}
}

// check required params.
if (config.ajaxUrl.length == 0) {
throw new Error("Cannot have empty config value ajaxUrl");
}
}

// after the update has occured put everything back to normal.
this.cleanUp = function(elId, keepEditable){
Ext.get(elId + '_editor').remove();

Ext.get(elId).setStyle({
'display': ''
});

if (keepEditable) {
Ext.get(elId).addClass(this.config.editableCls != null ? this.config.editableCls : 'editable');
}

if (this.config.destroy) {
	this.killEditor(elId);
}

// calling custom after update
if (this.config.afterUpdate) {
this.config.afterUpdate(elId);
}
}

// everything went swimmingly..
this.editComplete = function(text, elId){
el = Ext.get(elId);
el.update(text);

// calling custom on success
if (this.config.onSuccess) {
this.config.onSuccess(text, elId);
}
}

// what to do when an edit fails.
// must be a custom func from config.
this.editFailed = function(text, elId){
if (this.config.onFailure) {
this.config.onFailure(text, elId);
}

// no default action.
}

// methods that handles the posting of the data to the server.
this.saveChanges = function(elId,editortype){
var el = Ext.get(elId);
if(editortype == 'date')
{
	day = Ext.get(elId + '_edit[day]').getValue();
	month = Ext.get(elId + '_edit[month]').getValue();
	year = Ext.get(elId + '_edit[year]').getValue();
	if(!day && !month && !year)
	{
		day = '99';
		month = '99';
		year = '9999';
	}
	if(!day || !month || !year)
		var new_value = '00-00-0000';
	else
		var new_value = day + '-' + month + '-' + year;
}
else
	var new_value = Ext.get(elId + '_edit').getValue();

el.update('Saving...');

this.cleanUp(elId, true);

var arr_params = [];


// add the actual edited value.
// if the name attr is blank we use the id instead.
arr_params[(this.config.paramName) ? this.config.paramName : elId] = new_value;

if(this.config.extraParams)
{
	for(var key in this.config.extraParams)
		arr_params[key] = this.config.extraParams[key];
}

// do ajax request here.
Ext.Ajax.request({
url: this.config.ajaxUrl,
method : (this.config.ajaxMethod != null ? this.config.ajaxMethod : _defaultAjaxMethod),
params: arr_params,
success: function(response){
this.editComplete(response.responseText, elId);
},
failure: function(response){
this.editFailed(response.responseText, elId);
},
scope: this
});
}

// just adds a click handler and css class.
this.makeEditable = function(elId){
var e = Ext.get(elId);

e.addClass(this.config.editableCls != null ? this.config.editableCls : 'editable');

e.on('click', function(){
this.edit(elId);
}, this);
}

this.edit = function(elId){
var el = Ext.get(elId);

// hide El.Hide() is naff
el.setStyle({
'display': 'none'
});


Ext.DomHelper.insertBefore(elId, [{
tag: 'div',
id: elId + '_editor'
}]);
Ext.get(elId + '_editor').addClass('inline_editor');

// put a single line text input or multi line textbox.
if (this.config.editorType == "single")
{
	Ext.DomHelper.append(elId + '_editor', [{
	tag: 'input',
	id: elId + '_edit',
	name: elId + '_edit',
	type: 'text',
	value: el.dom.innerHTML == edittext ? '' : el.dom.innerHTML
	}]);
}
else if (this.config.editorType == "date")
{
	var arr_params = [];
	arr_params['field'] = elId + '_edit';
	if(el.dom.innerHTML != 'Edit this field')
		arr_params['date'] = el.dom.innerHTML;

	Ext.Ajax.request({
	url: '/ajax/datepicker.php',
	method : (this.config.ajaxMethod != null ? this.config.ajaxMethod : _defaultAjaxMethod),
	params: arr_params,
	success: function(response){
		Ext.DomHelper.insertFirst(elId + '_editor', [{
		tag: 'span',
		html: response.responseText,
		style: 'float:left;'
		}]);
	},
	failure: function(response){
		Ext.DomHelper.insertFirst(elId + '_editor', [{
		tag: 'input',
		id: elId + '_edit',
		name: elId + '_edit',
		type: 'text',
		value: el.dom.innerHTML == edittext ? '' : el.dom.innerHTML,
		style:(this.config.maxWidth ? 'width:'+this.config.maxWidth : 'width:80%')
		}]);
	},
	scope: this
	});
}
else
{
	Ext.DomHelper.append(elId + '_editor', [{
	tag: 'textarea',
	id: elId + '_edit',
	name: elId + '_edit',
	rows: 4,
	cols: 60,
	html: el.dom.innerHTML == edittext ? '' : el.dom.innerHTML.br2nl()
	}]);
}

// add the buttons.
if(this.config.buttons)
{
Ext.DomHelper.append(elId + '_editor', this.config.buttons);
}
else
{
Ext.DomHelper.append(elId + '_editor', [{
tag : 'img',
src: '/images/save.jpg',
id: elId + '_save'
}, {
tag : 'img',
src: '/images/cancel.jpg',
id: elId + '_cancel'
}]);
}

// button handlers.
Ext.get(elId + '_save').on('click', function(){
this.saveChanges(elId,this.config.editorType);
}, this);

Ext.get(elId + '_cancel').on('click', function(){
this.cleanUp(elId, true);
}, this);

if (this.config.editorType != "date")
	Ext.get(elId + '_edit').focus();
}

this.killEditor = function(elId){
var e = Ext.get(elId);
e.removeClass(this.config.editableCls != null ? this.config.editableCls : 'editable');
e.un('click', function(){
this.edit(elId);
}, this);
}

// check everything first.
_checkConfig(config);

// constructor code
this.makeEditable(elementId);
}

// Image Uploader ----------------------------------------------------------->
var uploader = function(elementId,config){

this.config = config;

this.showUploader = function(elementId){
	Ext.QuickTips.init();

	playerid = this.config.playerid;
	if(this.config.photoexists == 1)
		hasprimaryimage = this.config.photoexists
		
  prevHtml = Ext.get(elementId).dom.innerHTML;
	Ext.get(elementId).dom.innerHTML = '';

	var showimage = function(imageid,caption,icount){
		
		imgLoader = new Image();// preload image
		imgLoader.src = tb_pathToImage;
		tb_show(caption,"/images/playerphotos/resized/"+imageid+".jpg",false);
		Ext.get(elementId).dom.innerHTML = prevHtml;
		
		var array_params = [];
		array_params['photo'] = "/images/playerphotos/resized/"+imageid+".jpg";
		if(icount == 2){
			//ajax call
			Ext.Ajax.request({
				url: '/ajax/imagesize.php',
				method : 'POST',
				params: array_params,
				success: function(response){
					Ext.get('showmorephotos').dom.style.display = 'block';
					Ext.get('showmorephotoslink').dom.href = '/ajax/imageviewer.php?id='+imageid+'&playerid='+playerid+'&ajaxgallery=true&'+response.responseText;
				}
			});
		}
		if(icount == 1 || (icount > 1 && hasprimaryimage == 0)){
			array_params['format'] = "json";
			Ext.Ajax.request({
				url: '/ajax/imagesize.php',
				method : 'POST',
				params: array_params,
				success: function(response){
					var dimensions = eval('(' + response.responseText + ')');
					if(dimensions.ratio > .6 && dimensions.ratio < .85)
					{
						Ext.get('defaultphoto').dom.src = "/images/playerphotos/resized/"+imageid+".jpg";
						Ext.get('defaultphoto').replaceClass('default','playerphoto');
						hasprimaryimage = 1;
					}
					else
					{
						Ext.get('showmorephotos').dom.style.display = 'block';
						Ext.get('showmorephotoslink').dom.href = '/ajax/imageviewer.php?id='+imageid+'&playerid='+playerid+'&ajaxgallery=true&width='+dimensions.width+'&height='+dimensions.height;
					}
				}
			});
		}
	}

	var msg = function(title, msg){
		Ext.Msg.show({
			title: title, 
			msg: msg,
			minWidth: 200,
			modal: true,
			icon: Ext.Msg.INFO,
			buttons: Ext.Msg.OK
		});
	};

	var fp = new Ext.FormPanel({
		renderTo: elementId,
		fileUpload: true,
		width: 218,
		frame: true,
		title: 'Upload Image',
		autoHeight: true,
		bodyStyle: 'padding: 10px 10px 0 10px;',
		labelWidth: 50,
		defaults: {
			anchor: '95%',
			allowBlank: false,
			msgTarget: 'side'
		},
		items: [{
			xtype: 'hidden',
			name: 'playerid',
			value: this.config.playerid
		},{
			xtype: 'fileuploadfield',
			id: 'form-file',
			emptyText: 'Select an image',
			fieldLabel: 'Photo',
			name: 'photo-path',
			buttonCfg: {
					text: '',
					iconCls: 'upload-icon'
			}
		}],
		buttons: [{
			text: 'Save',
			handler: function(){
					if(fp.getForm().isValid()){
						fp.getForm().submit({
								url: '/ajax/file-upload.php',
								waitMsg: 'Uploading your photo...',
								success: function(fp, o){
										showimage(o.result.id,'Successfull uploaded file: "'+o.result.file+'"',o.result.imagecount);
								},
								failure: function(fp, o){
										msg('Upload Failed', o.result.reason);
								}
						});
					}
			}
		},{
				text: 'Cancel',
				handler: function(){
						Ext.get(elementId).dom.innerHTML = prevHtml;
				}
		}]
	});
}

this.showUploader(elementId);
}
// Image Uploader ----------------------------------------------------------->



function addmessage(pid,board,username,callingobject,el)
{
	playerid = pid;
	var dt = new Date();
	Ext.DomHelper.useDom = true
	topics = (document.getElementById(board).childNodes.length/2);

	Ext.DomHelper.insertFirst(board, [{
	tag : 'div',
	id : board+'_topic_'+topics+'header'
	}, {
	tag : 'div',
	id : board+'_topic_'+topics+'message'
	}, {
	tag : 'hr'
	}]);
	Ext.get(board+'_topic_'+topics+'header').addClass('headliner');
	Ext.get(board+'_topic_'+topics+'message').addClass('messagebody');
	newmessage = board+'_topic_'+topics+'message';
	newmessageheader = board+'_topic_'+topics+'header';
	Ext.DomHelper.append(board+'_topic_'+topics+'header', [{
	tag : 'div',
	id : board+'_topic_'+topics+'header_date',
	html: '<em>posted: '+dt.format('F j, Y')+'</em>'
	}, {
	tag : 'div',
	id : board+'_topic_'+topics+'header_name',
	html: '<strong>'+username+'</strong> wrote: '
	}]);
	Ext.get(board+'_topic_'+topics+'header_name').addClass('membername');
	Ext.get(board+'_topic_'+topics+'header_date').addClass('posteddate');
	nm = new editable(board+'_topic_'+topics+'message', {'editorType' : 'multi', 'ajaxUrl' : '/ajax/messageboard.php', 'ajaxMethod' : 'post', 'paramName' : 'message', 'destroy' : 'true', 'extraParams' : {'playerid' : pid, 'el' : el}, 'onSuccess' : function(txt,elid){removeEditor(elid);}});
	nm.edit(board+'_topic_'+topics+'message');
	callingobject.parentNode.removeChild(callingobject);
	return false;
}

function removeEditor(elid)
{
	//move the message to the bottom
	pnode = document.getElementById(elid).parentNode;
	pnode.appendChild(document.getElementById(newmessageheader));
	Ext.DomHelper.append(pnode.id, [{
		tag : 'div',
		id : 'message_'+elid,
		html : document.getElementById(newmessage).innerHTML
		}]);
	Ext.get('message_'+elid).addClass('messagebody');
	rule = Ext.DomQuery.select("hr"),pnode;
	if(Ext.isArray(rule))
		pnode.removeChild(rule[0]);
	pnode.removeChild(document.getElementById(newmessage));
	Ext.DomHelper.append(pnode.id, [{
		tag : 'div',
		id : 'alertmessage',
		html : '<div class="alertmessage"><h3>Thank You</h3><div>Your message has been added</div></div>'
		}]);
	Ext.get('alertmessage').addClass('infobox');
	imgLoader = new Image();
	imgLoader.src = tb_pathToImage;
	tb_show(null,"#TB_inline?height=100&amp;width=300&amp;inlineId=alertmessage",false);
}

function editor(pid,button)
{
	if(ineditmode == 1)
		window.location.reload();
	
	playerid = pid;
	Ext.DomHelper.useDom = true
	//open up our compacted divs
	expanditems = Ext.DomQuery.select("li[class*=expander]");
	if(Ext.isArray(expanditems))
		Ext.each(expanditems, function(obj,ind,arr){Ext.get(obj).removeClass('expander');Ext.get(obj).dom.removeAttribute('style');});
	expanderitems = Ext.DomQuery.select("a[class*=expandlist]");
	if(Ext.isArray(expanderitems))
		Ext.each(expanderitems, function(obj,ind,arr){Ext.get(obj).setDisplayed(false)});
	for(i=0;i<fields.length;i++)
	{
		if(field = document.getElementById(fields[i]))
		{
			try{ field.parentNode.className = 'editable_row'; } catch(e) { alert(fields[i]) };
			if(field.nodeName.toLowerCase() == 'ul')
			{
				listitems = field.getElementsByTagName('li');
				if(listitems.length > 0)
				{
					for(j=0;j<listitems.length;j++)
					{
						try
						{
							if(listitems[j].firstChild.nodeName.toLowerCase() == 'a')
							{
								remove = listitems[j].firstChild;
								Ext.DomHelper.insertFirst(listitems[j], [{
									tag : 'span',
									html : listitems[j].firstChild.href
									}]);
								listitems[j].removeChild(remove);
							}
						} catch(e) {};
						new editable(listitems[j].id, {'editorType' : 'single', 'ajaxUrl' : '/ajax/player.php', 'ajaxMethod' : 'post', 'extraParams' : {'playerid' : pid}});
					}
				}
				else
				{
					Ext.DomHelper.append(fields[i], [{
					tag: 'li',
					id: fields[i]+'[0]',
					html: edittext
					}]);
					Ext.get(fields[i]+'[0]').addClass(editclass);
					new editable(fields[i]+'[0]', {'editorType' : 'single', 'ajaxUrl' : '/ajax/player.php', 'ajaxMethod' : 'post', 'extraParams' : {'playerid' : playerid}, 'onSuccess' : function(txt,elid){Ext.get(elid).removeClass(editclass);}});
				}
			}
			else
			{
				if(fields[i] == 'dob' || fields[i] == 'dod')
					fieldtype = 'date';
				else
					fieldtype = 'single';

				if(document.getElementById(fields[i]).childNodes.length == 0)
				{
					Ext.get(fields[i]).addClass(editclass);
					Ext.DomHelper.insertHtml('afterBegin',document.getElementById(fields[i]),edittext);
					new editable(fields[i], {'editorType' : fieldtype, 'ajaxUrl' : '/ajax/player.php', 'ajaxMethod' : 'post', 'extraParams' : {'playerid' : pid}, 'onSuccess' : function(txt,elid){Ext.get(elid).removeClass(editclass);}});
				}
				else
				{
					new editable(fields[i], {'editorType' : fieldtype, 'ajaxUrl' : '/ajax/player.php', 'ajaxMethod' : 'post', 'extraParams' : {'playerid' : pid}});
				}
			}
		}
	}
	//button.style.display="none";
	Ext.get(button).dom.innerHTML = 'Done Editing';
	morebuttons = Ext.DomQuery.select("a[class*=morelinks]");
	if(Ext.isArray(morebuttons))
	{
		Ext.each(morebuttons, function(obj,ind,arr){Ext.get(obj).removeClass('morelinks')});
	}
	try
	{
		document.getElementById('age').style.display = 'none';
	}
	catch(e){};
	ineditmode = 1;
	
	return false;
};

function addmore(ulid)
{
	if(ineditmode == 1)
	{
		children = document.getElementById(ulid).childNodes.length;
		Ext.DomHelper.useDom = true
		Ext.DomHelper.append(ulid, [{
		tag: 'li',
		id: ulid+'['+children+']',
		html: edittext
		}]);
		Ext.get(ulid+'['+children+']').addClass(editclass);
		new editable(ulid+'['+children+']', {'editorType' : 'single', 'ajaxUrl' : '/ajax/player.php', 'ajaxMethod' : 'post', 'extraParams' : {'playerid' : playerid}, 'onSuccess' : function(txt,elid){Ext.get(elid).removeClass(editclass);}});
	}
	return false;
}

function print_r(theObj){
  if(theObj.constructor == Array ||
     theObj.constructor == Object){
    document.write("<ul>")
    for(var p in theObj){
      if(theObj[p].constructor == Array||
         theObj[p].constructor == Object){
document.write("<li>["+p+"] => "+typeof(theObj)+"</li>");
        document.write("<ul>")
        print_r(theObj[p]);
        document.write("</ul>")
      } else {
document.write("<li>["+p+"] => "+theObj[p]+"</li>");
      }
    }
    document.write("</ul>")
  }
}
