var num = 0;
$(document).ready(function(){
	ad_loadScripts();
	ad_treeAddButton();
	ad_frontAddButton();
	ad_frontButtons();
});

function ad_loadScripts(){
	debug('ad_loadScripts');
	ad_addGroupFunctions();
	ad_pageTypeFunctions();
	ad_popupButtonControls();
	ad_systemRowItem();
	ad_paging();
	ad_editWindow();
	ad_mediaLibrary();
	ad_systemBar();
}

// gets all the ck editors on the page 
function ad_getCkEditors() {
	$('.adRichTextInput').each(function(){ ad_runCkEditor($(this).attr('id')); });
}

// creates all the ck editors on the page
function ad_runCkEditor(field){ 
	//debug('cow');
	//$('#'+field).ckeditor();
	var $editors = $('#'+field);
	if ($editors.length) {
		var instance = CKEDITOR.instances[field];
		if(instance) { CKEDITOR.remove(instance); }
		CKEDITOR.replace(field);
	}
}

// setups up the add button in the tree
function ad_treeAddButton(){
	$('.adAddBtnPop .adSystemBtn').click(function(){
		var type = $(this).attr('id').replace('adTreeAdd_','');
		debug(type);
		$.post('?adTreeAdd='+type, { }, function(data){
			$('body').append(data);
			ad_loadScripts();
			ad_drags();
		});
		return false;
	});	
}

// button controllers for the popups
function ad_popupButtonControls() {
	// close / cancel button
	$('.adSystemEditAddHolder .adSystemCancel').click(function(){
		$(this).closest('.adSystemEditAddHolder').remove();
		return false;																													 
	});	
	$('.adSystemEditHolderButtonsClose').click(function(){
		$(this).closest('.adSystemEditHolder').remove();
		return false; 	
	});
}

// page type functions 
function ad_pageTypeFunctions(){
	$('.adOptionType_PageType').change(function(){
		var data = $(this).val();
		if(data == 'External') {
			$(this).parent().parent().next().show();	
			$(this).parent().parent().next().next().hide();	
		} else {
			$(this).parent().parent().next().hide();	
			$(this).parent().parent().next().next().show();	
		}
	});
}

// sets up the add a file function when clicking on items in the tree
function ad_addGroupFunctions() {
	
	$('.adSystemEditTable .adSystemTreeAdd span').click(function(){
		parents = $(this).parentsUntil('.adSystemEditWindowArea');
		finalParent = String(parents[parents.length-1]);
		// TODO: there has to be a better way to do this
		if(finalParent[12] == 'H') {
			var path = '.adSystemTree .adSystemContentForm .ad_parent';
		} else {
			var path = '.adSystemEditWindowArea .adSystemContentForm .ad_parent';
		}
		var guid = $(this).attr('class').replace('adTree','').replace(' adTreeOn','');
		$(path).empty().val(guid);
		return false;
	});
	
	$('.adSystemEditTable .adSystemTreeAddGroup span').click(function(){
		parents = $(this).parentsUntil('.adSystemEditWindowArea');
		finalParent = String(parents[parents.length-1]);
		debug(finalParent);
		// TODO: there has to be a better way to do this
		if(finalParent[12] == 'H') {
			var path = '.adSystemEditAddHolder .adSystemContentForm .ad_group_guids';
			var path2 = '.adSystemEditAddHolder .adSystemContentForm .adSystemGroups';
		} else {
			var path = '.adSystemEditWindowArea .adSystemContentForm .ad_group_guids';
			var path2 = '.adSystemEditWindowArea .adSystemContentForm .adSystemGroups';
		}
		var guid = $(this).attr('class').replace('adTree','').replace(' adTreeOn','');
		var name = $(this).text();
		var guids = $(path).val();
		var guidSplit = guids.split(',');
		if(!in_array(guid,guidSplit)) {
			if(guids == '') {
				guids = guid;
			} else {
				guids = guids+','+guid;	
			}
			$(path).val(guids);
			$(path2).append('<div class="adSystemGroupRow"><div class="adSystemGroupDelete"><a href="" onclick="return ad_deleteGroupItem(event,\''+guid+'\');"><img src="inc/images/btnDelete.png" width="16" height="16"/></a></div>'+name+'</div><!-- ad system group row -->');
		}
		debug(name);
		debug(guidSplit);
		debug(guid);
		debug($(path).val());
		//$(path).empty().val(guid);
		debug('-------------');
		return false;																																		
	});	
}

// deletes an item
function ad_deleteGroupItem(e,guid) {
	var confirmItem = confirm('Are you sure you want to delete this item?');
	if(confirmItem) {
		//alert('delete');
		var x;
		var guidString = '';
		var group = e.target;
		var guidsHolder = $(group).parent().parent().parent().parent().siblings('.ad_group_guids');
		var groupRow = $(group).parent().parent().parent();
		var guids = guidsHolder.val()
		var guidSplit = guids.split(',');
		for(x in guidSplit) {
			if(guidSplit[x] != guid) {
				guidString += guidSplit[x]+',';	
			}
		}
		guidString = guidString.substr(0,guidString.length-1);
		guidsHolder.val(guidString);
		groupRow.hide();
		debug(guids);
		debug(guid);
		debug(groupRow);
		debug(guidSplit);
		debug('-------------');
		
	} else {
		//alert('dont delete');
	}
	return false;	
}

// deletes an item
function ad_deleteItem(guid){
	var confirmItem = confirm('Are you sure you want to delete this item?');
	if(confirmItem) {
		debug(guid);
		//ad_loaderBlocker('up');
		$.post('?adItemRow=delete', { guid:guid });//, function(data){
			//response(data);
			//ad_loaderBlocker('down');
			//debug(data);
		//});
		return false;
		if($('#adSystemRowItem'+guid).length > 0) $('#adSystemRowItem'+guid).fadeOut(500,function(){ $(this).remove(); ad_resetRowColours(); });
	}
}

// deletes an media item
function ad_deleteMediaItem(guid){
	var confirmItem = confirm('Are you sure you want to delete this item?');
	if(confirmItem) {
		debug(guid);
		//ad_loaderBlocker('up');
		$.post('?adMediaLibrary=delete', { guid:guid }, function(data){
			//ad_loaderBlocker('down');
			$('.adSystemEditWindow').empty().append(data);
			ad_loadScripts();
			ad_treeClicks();
			ad_resetScroll('.adSystemEditWindow');
		});
		return false;
	}
}

// deletes an edit item
function ad_deleteEditItem(guid,dbTable){
	var confirmItem = confirm('Are you sure you want to delete this item?');
	if(confirmItem) {
		//$.post('index.php', { adFront:'delete',guid:guid,dbTable:dbTable });
		//return true;
		$.ajax({
			type: 'POST',
			url: 'index.php?adFront=delete',
			data: 'guid='+guid+'&dbTable='+dbTable,
			success: function(){ $('#adEditItem_'+guid).fadeOut(300,function(){ $(this).remove(); }); }
		});
		return false;
	} else {	
		return false;
	}
}

// resets the row colours
function ad_resetRowColours(){
	debug('reset colours');
	$('.adSystemRow2').each(function(){ $(this).removeClass('adSystemRow2'); });
	$('.adSystemRow').each(function(i){
		if((i+1) % 2 === 1) {
			$(this).addClass('adSystemRow2');
		}
	});
}

// functions for editing on the fly
function ad_systemRowItem(){
	$('.adSystemRowBlock').dblclick(function(){
		debug('dblclick');
		var row = $(this);
		var theText = row.text();
		var theId = row.parent().attr('id').replace('adSystemRowItem','');
		var theClass = row.attr('class').replace(' adSystemRowBlock','').replace('adSystemBlock','');
		debug(theClass);
		debug(theText);
		debug(theId);
		switch(theClass) {
			case 'Name':
				var edit = '<input type="text" id="adSystemItemInput'+theId+'" class="adSystemItemInput" name="itemRow" value="'+theText+'"/>&nbsp;<img src="inc/images/btnSave.png" width="16" height="16" id="adSystemItemSave'+theId+'" class="adSystemItemSave"/>&nbsp;<img src="inc/images/btnCancel.png" width="16" height="16" id="adSystemItemCancel'+theId+'" class="adSystemItemCancel"/>';
				var editId = "#adSystemItemInput"+theId;
			break;
			case 'Enabled':
				var edit = '<select id="adSystemItemSelect'+theId+'" class="adSystemItemSelect" name="itemRow">';
					edit += '<option';if(theText == 'Yes') { edit += ' selected="selected"'; }; edit += '>Yes</option>';
					edit += '<option';if(theText == 'No') { edit += ' selected="selected"'; }; edit += '>No</option>';
				edit += '</select>&nbsp;';
				edit += '<img src="inc/images/btnSave.png" width="16" height="16" id="adSystemItemSave'+theId+'" class="adSystemItemSave"/>&nbsp;<img src="inc/images/btnCancel.png" width="16" height="16" id="adSystemItemCancel'+theId+'" class="adSystemItemCancel"/>'
				var editId = "#adSystemItemSelect"+theId;
			break;
		}
		row.empty().append(edit);
		row.children('.adSystemItemInput').focus();
		row.children('.adSystemItemSave').click(function(){ 
			ad_loaderBlocker('up');
			var fieldData = $(editId).val();
			$.post('?adItemRow=update', { update:fieldData, field:theClass, guid:theId }, function(data){
				row.empty().append('<span class="adSystemItemInputSpan">'+fieldData+'</span>');
				if(theClass == 'Enabled') {
					if(fieldData == 'Yes') {
						debug(row.parent().attr('class'));
						row.parent().removeClass('adSystemRowDisabled');
					} else {
						row.parent().addClass('adSystemRowDisabled');
					}
				}
				ad_loaderBlocker('down');
			});
		});
		row.children('.adSystemItemCancel').click(function(){ 
			row.empty().append('<span class="adSystemItemInputSpan">'+theText+'</span>');
		});
		return false;																						
	});
}

// handles the ajax paging
function ad_paging() {
	debug('ad_paging');
	$('.adSystemPaging a').click(function(){
		debug('click');
		ad_loaderBlocker('up');
		var totalPages = 0;
		var newPage = 0;
		
		// getting class number
		var thePageClass = $(this).parent().attr('class');
		var thePage = thePageClass.replace('adSystemPages','');
		debug('thePageClass: '+thePageClass);
		debug('thePage: '+thePage);	
		
		// getting the current page
		var currentPage = $('.adSystemPaging a.onLink').parent().attr('class').replace('adSystemPages','');
		debug('currentPage: '+currentPage);
		
		// getting the number of pages
		$(this).parent().parent().children('li').each(function(){
			theClass = $(this).attr('class').replace('adSystemPages','');
			if(!theClass.match('Next') && !theClass.match('Last') && !theClass.match('Back') && !theClass.match('First')) {
				totalPages ++;
			}
		});
		debug('totalPages: '+totalPages);
		
		// converting the totalPages and currentPage to numbers
		currentPage = parseInt(currentPage);
		totalPages = parseInt(totalPages);
		
		// applying the class to the number
		switch(thePage) {
			case 'Next':
				debug('next');
				if(currentPage < totalPages) {
					newPage = currentPage +1;
					$('.adSystemPaging .adSystemPages'+(newPage)+' a').addClass('onLink');
				}
			break;
			case 'Last':
				debug('last');
				newPage = totalPages;
				$('.adSystemPaging .adSystemPages'+(newPage)+' a').addClass('onLink');
			break;
			case 'Back':
				debug('back');
				if(currentPage > 0) {
					newPage = currentPage - 1;
					$('.adSystemPaging .adSystemPages'+(newPage)+' a').addClass('onLink');
				}
			break;
			case 'First':
				debug('first');
				newPage = 1;
				$('.adSystemPaging .adSystemPages1 a').addClass('onLink');
			break;
			default: 
				debug('number clicked');
				newPage = thePage;
				$('.'+thePageClass).each(function(){
					$(this).children('a').addClass('onLink');	
				});	
			break;	
		}
		newPage = parseInt(newPage);

		// removing the class on the numbers
		debug('currentPage: '+currentPage+' totalPages: '+totalPages+' newPage: '+newPage);
			$('.adSystemPaging a.onLink').each(function(){
				if(newPage != $(this).text()) {
					$(this).removeClass('onLink');	
				}
			});

		// hiding or showing the buttons
		if(newPage <= 1) {
			$('.adSystemPaging .adSystemPagesFirst, .adSystemPaging .adSystemPagesBack').addClass('adSystemHide');
		} else {
			$('.adSystemPaging .adSystemPagesFirst, .adSystemPaging .adSystemPagesBack').removeClass('adSystemHide');
		}
		if(newPage < totalPages) {
			$('.adSystemPaging .adSystemPagesLast, .adSystemPaging .adSystemPagesNext').removeClass('adSystemHide');
		} else {
			$('.adSystemPaging .adSystemPagesLast, .adSystemPaging .adSystemPagesNext').addClass('adSystemHide');
		}
		
		// update the edit window
		var theId = $('.adTreeOn').attr('id').replace('adTree','');
		debug(theId);
		editItems = ad_treeEditItems();
		argItems = ad_treeArgItems();
		
		$.post('?adEditWindow=update', { guid:theId, editItems:editItems, args:argItems, pageNum:newPage }, function(data){
			$('.adSystemEditWindow').empty().append(data);
			ad_loadScripts();
			ad_paging();
			ad_resetScroll('.adSystemEditWindow');
			ad_loaderBlocker('down');
		});		

		//console.log('------------------------------');
		return false;	
	});
}

// handles the edit window folders and items
function ad_editWindow() {
	$('.adEditWindowItem a').click(function(){
		debug('click');
		ad_loaderBlocker('up');
		var theClass = $(this).attr('class');
		debug(theClass);
		editItems = ad_treeEditItems();
		argItems = ad_treeArgItems();

		// setting the id
		if(theClass.match('adEditWindowItemEdit') && !theClass.match('adEditWindowItemEdit2')) {
			debug('matched');
			var theId = parseInt($(this).parent().parent('li').attr('id').replace('adEditItem',''));
			//ad_updateTreeClass(theId);
		} else if(theClass.match('adEditWindowItemEdit2')) {
			debug('matched 2');
			var theId = parseInt($(this).parent('li').attr('id').replace('adEditItem',''));
		} else {
			var theId = parseInt($(this).parent('li').attr('id').replace('adEditItem',''));
			ad_updateTreeClass(theId);
		}
		
		// reloading the window 
		if(theClass.match('adEditWindowItemEdit') || theClass.match('adEditWindowItemEdit2')) {
			debug('here we are');
			var parentGuid = $('.adSystemTreeHolder .adTreeOn').attr('id').replace('adTree','');	
			$.post('?adEditWindow=update', { guid:theId, editItems:editItems, args:argItems, editForm:theId, parent:parentGuid }, function(data){
				$('.adSystemEditWindow').empty().append(data);
				ad_loadScripts();
				//ad_getCkEditors();
				ad_resetScroll('.adSystemEditWindow');
				ad_loaderBlocker('down');
				ad_runDates();
			});		
		} else {
			$.post('?adEditWindow=update', { guid:theId, editItems:editItems, args:argItems }, function(data){
				$('.adSystemEditWindow').empty().append(data);
				ad_loadScripts();
				//ad_getCkEditors();
				ad_resetScroll('.adSystemEditWindow');	
				ad_loaderBlocker('down');
				ad_runDates();
			});		
		}


		
		debug(theId);
		debug('--------------------------');
		return false;	
	});
	
	$('.adSystemEditWindowArea .adSystemCancel').click(function(){
		ad_loaderBlocker('up');
		var theId = $('.ad_editParent').val();
		editItems = ad_treeEditItems();
		argItems = ad_treeArgItems();

		$.post('?adEditWindow=update', { guid:theId, editItems:editItems, args:argItems }, function(data){
			$('.adSystemEditWindow').empty().append(data);
			ad_loadScripts();
			ad_resetScroll('.adSystemEditWindow');
			ad_loaderBlocker('down');
		});		
		return false;	
	});
	
	$('.adSystemContentForm').submit(function(){
		debug('form.. weee');
		ad_loaderBlocker('up');
		//return false; 	
	});
}

function ad_formProcess(theFrame) {
	debug('form has finished');	
	theFrame.processajax('','inc/adAjaxFormProcess.php');
}

function ad_resetScroll(scrollItem) {
	$(scrollItem).scrollTop(0);
};

function ad_runDates() {
	$('.adInputDate').each(function(){
		debug('bitch');
		//$(this).datePicker().val(new Date().asString()).trigger('change');													
		//ad_runCkEditor($(this).attr('id'));															
	});
}


// setts up xmlhttp object
function getXmlHttp() {
	debug('getXmlHttp');
	// create a boolean variable to check for a valid Microsoft ActiveX instance.
	var xmlhttp = false;
	
	// check if we are using IE
	try {
		// ie 5+
		xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');	
	}	catch(e) {
		// older than ie 5
		try{
			// if using IE
			xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');	
		} catch(E) {
			// good browser
			xmlhttp = false;
		}	
	}
	
	// if we arnt using IE, create a js instnace of the object
	if(!xmlhttp && typeof XMLHttpRequest != 'undefined') xmlhttp = new XMLHttpRequest();
	
	return xmlhttp;
}

// porcess an XMLHttpRequest
function processajax(obj,serverPage) {
	debug('processajax');
	// get an XMLHttpRequest object for use
	var theItem;
	xmlhttp = getXmlHttp();	
	xmlhttp.open('GET', serverPage);
	xmlhttp.onreadystatechange = function(){
		if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
			debug('stuff');	
			var theId = $('.ad_editParent').val();
			var theItemId = $('.ad_guid').val();
			var theType = $('.ad_dbTable').val();
			var theName = $('.adEditName').val();
			if(theType == 'ad_medialibrary_group') ad_updateTree(theName,theItemId); 
			editItems = ad_treeEditItems();
			argItems = ad_treeArgItems();
	
			$.post('?adEditWindow=update', { guid:theId, editItems:editItems, args:argItems }, function(data){
				$('.adSystemEditWindow').empty().append(data);
				ad_loadScripts();
				ad_resetScroll('.adSystemEditWindow');
				ad_loaderBlocker('down');
				if($('.adSystemEditAddHolder').length > 0) $('.adSystemEditAddHolder').remove();
			});		
		}	
	}
	xmlhttp.send(null);
}

// updating the tree if name updates
function ad_updateTree(value,guid) {
	$('#adTree'+guid).empty().append(value);	
}

// puts up the loader blocker 
function ad_loaderBlocker(dir) {
	var editWindowBlocker = '.adSystemEditHolderBlocker';
	var fadeSpeed = 200;
	if(dir == 'up') {
		$(editWindowBlocker).fadeIn(fadeSpeed);
	}	else if(dir == 'down') {
		$(editWindowBlocker).fadeOut(fadeSpeed);	
	}
}

// from end add button 
function ad_frontAddButton(){
	$('.adAddSection .adSystemBtn').click(function(){
		debug('clicked!!');
		var controls = $(this).attr('href').replace('?','').split('&');
		var dbTable = controls[0].split('='); dbTable = dbTable[1];
		var source = controls[1].split('='); source = source[1];
		var parent = controls[2].split('='); parent = parent[1];
		var dontEdit = controls[3].split('='); dontEdit = dontEdit[1];
		var buttonText = $(this).text();
		debug(controls);
		debug(dbTable)
		debug(source);
		debug(parent);
		debug(dontEdit);
		$.post('?adFront=add', { dbTable:dbTable, source:source, parent:parent, dontEdit:dontEdit, buttonText:buttonText }, function(data){
			$('body').append(data);
			ad_loadScripts();
			ad_getCkEditors();
			ad_runDates();
			ad_drags();
		});
		return false;
	});	
}

// from end edit button 
function ad_frontButtons(){
	$('.adEditBtns .adBlockEdit').click(function(){
		debug('clicked!!');
		var theId = $(this).parent().attr('id');
		theId = '#'+theId;
		debug(theId);
		var dbTable = $(theId+' .adEditBtndbTable').val();
		var source = $(theId+' .adEditBtnsource').val();
		var parent = $(theId+' .adEditBtnparent').val();
		var theGuid = $(theId+' .adEditBtnguid').val();
		var dontEdit = $(theId+' .adEditBtndontEdit').val();
		var buttonText = '';
		
		debug(dbTable)
		debug(source);
		debug(parent);
		debug(dontEdit);
		$.post('?adFront=edit', { dbTable:dbTable, source:source, parent:parent, dontEdit:dontEdit, buttonText:buttonText, guid:theGuid }, function(data){
			$('body').append(data);
			ad_loadScripts();
			ad_getCkEditors();
			ad_runDates();
			ad_drags();
		});
		return false;
	});	
}

// set the links for the popup media library
function ad_mediaLibrary() {
	$('.adEditImageEdit').click(function(){
		debug('showMediaLibrary');
		
		$.post('?adMediaLibrary=edit', {  }, function(data){
			$('body').append(data);
			ad_paging();
			//ad_editWindow();
			ad_loadScripts();
			//ad_getCkEditors();
			ad_treeClicks();
			ad_drags();
		});
		return false; 	
	});
	
	$('.adEditWindowItemSelect2').click(function(){
		debug('selecting image');
		var theId = $(this).parent().attr('id').replace('adEditItem','');
		var bgImage = $(this).css('backgroundImage');
		debug(bgImage);
		debug(theId);
		$('.adEditImageFile .adInput').val(theId);
		$('.adEditImage').css('backgroundImage',bgImage);
		$('.adSystemEditHolderLarge').fadeOut(200,function(){ $('.adSystemEditHolderLarge').remove(); });
		return false; 	
	});
	
	$('.adEditImageRemove').click(function(){
		debug('remove img');
		$('.adEditImageFile .adInput').val('');
		$(this).parent().siblings('.adEditImage').css('backgroundImage','none');
		return false; 
	});
}


// system bar functions 
function ad_systemBar() {
	$('#adSystemNav a').click(function(){
		var theClass = $(this).attr('class');
		var href = $(this).attr('href');
		
		switch(theClass) {
			case 'systemEdit':
			case 'systemView':
			case 'systemLogout':
				window.location = href;
			break;	
			case 'systemMediaLibrary':
				$.post('?adMediaLibrary=add', {  }, function(data){
					debug(data);
					$('body').append(data);
					ad_loadScripts();
					/*ad_addGroupFunctions();
					ad_pageTypeFunctions();
					ad_popupButtonControls();
					ad_paging();
					//ad_editWindow();
					ad_mediaLibrary();*/
					ad_treeAddButton();
					//ad_getCkEditors();
					ad_treeClicks();
					ad_drags();
				});
			break;
		}
		return false; 	
	});
}

// throws a response
function response(data) {
	var content = data;
	debug(content);
}

// debug function
function debug(data) { 
	//console.log(data);
	//alert(data);
}

// debug function
function debug2(data) { 
	//console.log(data);
	//alert(data);
}

function in_array(needle, haystack, argStrict) {
	var key = '', strict = !!argStrict; 
	if (strict) {
		for (key in haystack) {
			if (haystack[key] === needle) {
				return true;
			}
		}
	} else {
		for (key in haystack) {
			if (haystack[key] == needle) {                
				return true;
			}
		}
	}
	return false;
}
