// global cookie options
cookieOptions = { path: '/', expires: 90 };


$(document).ready(function() {initDocument();});
		
		
function initDocument() {
	
	mainmenu();
	
	//var testStr = '{"formErrors":"asdf"}';
	//var testJson = 
	$(".backButton").click(function(){
		var backUrl = $(this).attr("url");
		if (backUrl!=null && backUrl!="undefined"){
			window.location = backUrl;
		}
	});
	
	$(".selectSubcheckboxes1").click(function(){
		var subs = $(this).parent().parent().parent().parent().find("input[type=checkbox]");
		if ($(this).attr('checked')){
			subs.attr('checked', true);
			subs.attr('disabled', true);
		} else {
			subs.attr('checked', false);
			subs.attr('disabled', false);
		}
		$(this).attr('disabled', false);
	});
	
	var $chargeDialog = $('<div></div>')
		.html('<p>You will be charged by 1 credit. Are you sure?</p>'
			+'<p class="info">You can turn these alerts off on the Edit profile page.</p>');
	
	var $emptyDialog = $('<div></div>').html('<h1>Loading...</h1>');
	
	$(".chargeConfirmation").click(function(){
		var redirUrl = $(this).attr("href");
		$chargeDialog.dialog({
			//bgiframe: true,
			title: 'Confirmation',
			resizable: false,
			draggable: false,
			height:160,
			width:350,
			modal: true,
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
			buttons: {
				Ok: function() {
					window.location.replace(redirUrl);
				},
				Cancel: function() {
					$(this).dialog('close');
				}
			},
			close: function(event, ui) {
				$(this).dialog('destroy');
			}
		});
		return false;
		
	});
	
	var $modalDialogContent = $('<div></div>');
	$(".showModalDialogContent").click(function(){
		var redirUrl = $(this).attr("href");
		redirUrl = redirUrl + "/nolayout/1";
		$emptyDialog.load(redirUrl).dialog({
			//bgiframe: true,
			title: 'Confirmation',
			resizable: false,
			draggable: false,
			height:500,
			width:700,
			modal: true,
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
			buttons: {
				Ok: function() {
					$(this).dialog('close');
				}
			},
			close: function(event, ui) {
				$(this).dialog('destroy');
			}
		});
		return false;

	});
	
	var $noCreditsLeftDialog = $('<div></div>')
	.html('<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 5px 0;"></span>You have no credits left!</p>');
	
	$(".noCreditsLeftDialog").click(function(){
		$noCreditsLeftDialog.dialog({
			//bgiframe: true,
			title: 'Please Buy More Credits',
			resizable: false,
			draggable: false,
			height:150,
			width:350,
			modal: true,
			overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		},
		buttons: {
			"Buy 2 credits for £25 here": function() {
				window.location  = "/member/upgrade";
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		},
		close: function(event, ui) {
			$(this).dialog('destroy');
		}
		});
		return false;
		
	});
	
	var $notLoggedDialog = $('<div></div>')
		.html('	<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 5px 0;"></span>You need to be logged in!</p>');



	$(".notLoggedConfirmation").click(function(){
		$notLoggedDialog.dialog({
			//bgiframe: true,
			title: 'Need to log in',
			resizable: false,
			draggable: false,
			height:150,
			width:350,
			modal: true,
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
			buttons: {
				"Login": function() {
					window.location  = "/user/login";
				},
				"Register": function() {
					window.location  = "/user/register";
				},
				Cancel: function() {
					$(this).dialog('close');
				}
			},
			close: function(event, ui) {
				$(this).dialog('destroy');
			}
		});
		return false;
		
	});
	
	$(".radioList input.RadioInput").live('change', function(){
		if ($(this).hasClass('selectChoose')){
			$(this).parent().parent().find('.TextInput').attr('disabled', true);
			$(this).parent().parent().find('.SelectInput').removeAttr('disabled');
			$(this).parent().parent().find('.TextInput').hide();
			$(this).parent().parent().find('.SelectInput').show();
		}
		else {
			$(this).parent().parent().find('.SelectInput').attr('disabled', true);
			$(this).parent().parent().find('.TextInput').removeAttr('disabled');
			$(this).parent().parent().find('.SelectInput').hide();
			$(this).parent().parent().find('.TextInput').show();
		}
	});
	
	$(".tabsContainer").mpTabs();
	
	$(".toogleButton").expandButton();

	
	displayFormElementTooltipFunction = function() {
		try {
		hideFormElementTooltipFunction();
		
		var tooltipContainer = $(this).parent().next(".description");
		if (tooltipContainer.length==0){
			tooltipContainer = $(this).next(".description");
			if (tooltipContainer.length==0){
				return;
			}
		}
		var tooltipContent = tooltipContainer[0].innerHTML;
		if (tooltipContent==""){
			return;
		}
		
		$(this)//.html("leftMiddle") // Set the links HTML to the current opposite corner
		.qtip({
			content: tooltipContent, // Set the tooltip content to the current corner
			position: {
			corner: {
			tooltip: "leftMiddle", // Use the corner...
			target: "rightMiddle" // ...and opposite corner
		}
		},
		show: {
			when: false, // Don't specify a show event
			ready: true // Show the tooltip when ready
		},
		hide: {
			when: {
			target: $(this),
			event: 'blur' }
		},
		style: {
			border: {
			width: 5,
			radius: 5,
			color: '#018bba'
		},
		padding: 5, 
		background: '#003466',
		textAlign: 'left',
		tip: true, // Give it a speech bubble tip with automatic corner detection
		name: 'dark' // Style it according to the preset 'cream' style
		}
		});
		}
		catch (e){
			alert(e);
		}
	};
	hideFormElementTooltipFunction = function() {
		// Destroy currrent tooltip if present
		try {
		if($(this).data("qtip")){
			$(this).qtip("destroy");
			//$(this).data("qtip").remove();
		}
		}
		catch (e){
			alert(e);
		}
	};
	
	$(".TextInput,.ui-autocomplete-input").focus(displayFormElementTooltipFunction);
	$(".FileInput,.SelectInput").hover(displayFormElementTooltipFunction, hideFormElementTooltipFunction);

	
	jQuery.fn.qtipTableRow = function(columnAttrib, columnValue) {
		$(this).hover(function() {
		
			// Destroy current tooltip if present
			if($(this).data("qtip")) $(this).qtip("destroy");
	
			tooltipContent = $(this).find("["+columnAttrib+"='"+columnValue+"']").text();
			//console.log($(this));
			if (tooltipContent==""){
	             tooltipContent = $(this).next(".description").text();
	             if (tooltipContent==""){
	             	return;
	             }
			}
			$(this).qtip({ //.html("leftMiddle") // Set the links HTML to the current opposite corner
	               content: tooltipContent, // Set the tooltip content to the current corner
	               position: {
	                  corner: {
	                     tooltip: "leftMiddle", // Use the corner...
	                     target: "rightMiddle" // ...and opposite corner
	                  }
	               },
	               show: {
	            	   delay: 0,
	            	   effect: {length: 1},
	                  when: false, // Don't specify a show event
	                  ready: true // Show the tooltip when ready
	               },
	               hide: {
	            	   effect: {length: 1},
						when: {
							target: $(this),
							event: 'blur' }
	               },
	               style: {
	                  border: {
	                     width: 5,
	                     radius: 5,
	                     color: '#018bba'
	                  },
	                  padding: 5, 
						background: '#003466',
						textAlign: 'left',
	                  tip: true, // Give it a speech bubble tip with automatic corner detection
	                  name: 'dark' // Style it according to the preset 'cream' style
	               }
			});
		},function() {
	         // Destroy current tooltip if present
	         if($(this).data("qtip")) $(this).qtip("destroy");
		});
		
		
		$('.warningIfDontExist.ui-autocomplete-input').click();
		
	};
	
	inventoryTypeSwitcher = function (){
		if ($("#InventoryType-existing").is(":checked")){
			$("#InventoryName-container").hide();
			$("#ExistingInventory-container").show();
		}
		else if ($("#InventoryType-new").is(":checked")){
			$("#ExistingInventory-container").hide();
			$("#InventoryName-container").show();
		}
	};
	inventoryTypeSwitcher();
	
	$("#InventoryType-existing").click(inventoryTypeSwitcher);
	
	$("#InventoryType-new").click(inventoryTypeSwitcher);

	$('.uploadForm #Parts').change(function(){
		if ($('#InventoryName').is(':empty')){
			$('#InventoryName').val(cleanFilename($(this).attr('value')));
		}
	});
	
	$('.slideSwitchButton').live('click', (function(){
		var forId = $(this).attr('for');
		
		// hide
		if ($("#"+forId).is(':visible')){
			$("#"+forId).hide();//slideUp();
			$(this).removeClass('expanded');
			$(this).find('span.ui-icon').remove();
			$(this).prepend('<span class="ui-icon ui-icon-circle-triangle-e"></span>');
			
		}
		// show
		else {
			//$("#"+forId).offset({top:$(this).offset().top});
			$("#"+forId).show();//slideDown();
			$(this).addClass('expanded');
			$(this).find('span.ui-icon').remove();
			$(this).prepend('<span class="ui-icon ui-icon-circle-triangle-s"></span>');
		}
	}));
	
	
	$('.uploadingProgress .uploadingOptions .hide').click(function(event){
		event.preventDefault();
		//jQuery('#uploadMusicFormContainer [type=submit]').uiButtonLoadingFinished();
		//jQuery('#uploadMusicFormContainer').hide("fast"); 
		$('.uploadingProgress').hide();
		$('.uploadingIntroduction').fadeIn();
		initUploadProgressStep(0);
	 	keepRefreshing = 0;
	});
	
	$('.uploadingProgress .uploadingOptions .cancel').click(function(event){
		event.preventDefault();
		var currentButton = $(this);
		$.ajax({
			method: 'get',
			url : '/member/partsuploadcancel/isXhr/1',
			dataType : 'json',
			beforeSend: function () {
			currentButton.uiButtonLoadingStart({side:'left'});
		},
		success: function (data) {
			if (data.status == 'success' || data.status == 'warning'){
				$('.uploadingProgress').hide();
				$('.uploadingIntroduction').fadeIn();
				initUploadProgressStep(0);
				keepRefreshing = 0;
				currentButton.uiButtonLoadingFinished();
			} else {
				currentButton.uiButtonLoadingError();
			}
		}
		});
		
		return false;
	});
	
	$('.uploadingProgress .uploadingErrorsContainer .skip').click(function(event){
		event.preventDefault();
		var currentButton = $(this);
		$.ajax({
			method: 'get',
			url : '/member/partsuploadskip/isXhr/1',
			dataType : 'json',
			beforeSend: function () {
			currentButton.uiButtonLoadingStart({side:'left'});
		},
		success: function (data) {
			if (data.status == 'success' || data.status == 'warning'){
				showUploadSummary(data);
				initUploadProgressStep(4);
				keepRefreshing = 0;
				currentButton.uiButtonLoadingFinished();
			} else {
				currentButton.uiButtonLoadingError();
			}
		}
		});
		
		return false;
	});

	$('.uploadingProgress .uploadingErrorsContainer input[type=submit]').click(function(event){
		event.preventDefault();
		var currentButton = $(this);

		// TODO
		//var rows= $("#uploadTempPartsGrid").jqGrid('getRowData');
		
		var formData = $("#uploadTempPartsForm").serialize();
	
		/*var convertedRows = {};
		$.each(rows, function(index, value) { 
			convertedRows[value.PartID] = value;
		});
		var postData = convertArrayToPost(convertedRows, 'uploadErrors');*/
		
		$.ajax({
			type: "post",
			url : '/member/partsuploadprocesserrors/isXhr/1',
			data: formData,
			dataType : 'json',
			beforeSend: function () {
				currentButton.uiButtonLoadingStart({side:'left'});
			},
			success: function (data) {
				if (data.status == 'success' || data.status == 'warning'){
					showUploadSummary(data);
					initUploadProgressStep(2, 0);
				 	keepRefreshing = 1;
					currentButton.uiButtonLoadingFinished();
				} else {
					currentButton.uiButtonLoadingError();
				}
			}
		});
	
		return false;
	});
	
	$(".hideErrorAfterChange").live('change', function (event){
		$(this).parent().find('.errors').remove();
	});
}

function cleanFilename(filename){
	var slashIndex = filename.lastIndexOf('/');
	var slashIndex2 = filename.lastIndexOf('\\');
	if (slashIndex2 > slashIndex){
		var slashIndex = slashIndex2;
	}
	
	if (slashIndex != -1){
		filename = filename.substr(slashIndex+1);
	}
	
	var dotIndex = filename.lastIndexOf('.');
	if (dotIndex != -1) {
		filename = filename.substr(0, dotIndex);
	}
	return filename;
}

/**
 * Primary menu function
 */
function mainmenu(){
	$(" #menuholder ul ul ").css({display: "none"}); // Opera Fix
	$(" #menuholder > ul > li:not(.active)").hover(function(){
			$(this).find('ul:first').css({display: "block"}).show();
			$("li.active ul").css({display: "none"}).hide();
			},function(){
			$(this).find('ul:first').css({display: "none"});
			$("li.active ul").css({display: "block"}).show();

			});
	$(" #menuholder li.active ul").css({display: "block"}).show();
	
	}
	 
/**
 * Show confirmation dialog
 */	
function confirmDelete(text){
	if (text==null)
		text = 'Do you really want delete that item?';
	return confirm(text);
}

/**
 * Get all (except submit and empty values) form fields
 * and redirect to the proper ZF rewriten url
 */ 
formRewriteFunction = function() {
	returnStr = '';
	for(var i=0; i < this.elements.length; i++){
		if (this.elements[i].value==''
			|| this.elements[i].value==0
			|| this.elements[i].type=='submit')
			continue;
		var encodeValue = this.elements[i].value.replace(/\//g,"%2F");
		var encodeValue = $.URLEncode(encodeValue);
		
		returnStr += '/';
		returnStr += this.elements[i].name;
		returnStr += '/';
		returnStr += encodeValue;


	}

	searchUrl = this.action;
	document.location = searchUrl + returnStr;
	return false;
};


/*** ACTIVITY TYPES ***/


getParentId = function(childId){
	if (activityTypes[childId]==null || activityTypes[childId]["ActivityTypeParentID"]==null){
		return 0;
	} else {
		return activityTypes[childId]["ActivityTypeParentID"];
	}
};
setActiveSelect = function(el){
	$("select[name='"+activeSelectName+"']").removeAttr("name");
	el.attr("name", activeSelectName);
	el.removeClass("activityParents");
};



createSelectAfter = function(parent, currentBranch, selectedActivityId, parentId){
	var newSelectId = selectParentsNamePrefix+parentId;

	parent.append(getNewSelect(currentBranch, selectedActivityId, newSelectId)
			.fadeIn("fast"));

	createSelectOptions(newSelectId, currentBranch, selectedActivityId);

	appSelects.selectsArrAdd(newSelectId, "0");
	$("#"+newSelectId).change(selectChangeFunction);
	return newSelectId;

};
getNewSelect = function(currentBranch, selectedActivityId, newSelectId){
	var selectIdNum = getParentId(selectedActivityId);
	newEl = $("<select></select>").attr("id",newSelectId)
		.addClass("SelectInput").addClass("activityParents").attr("size", 5);
	return newEl;
};

createSelectOptions = function(newSelectId, currentBranch, selectedActivityId){
	var selectedActivityParentID = getParentId(selectedActivityId);

	var currentText = "";
	var currentOption = null;
	$.each(currentBranch, function(key,element) {
		$('#'+newSelectId).append($("<option></option>").attr("value",key).text(element["ActivityTypeName"]));
	});
	if (selectedActivityId>0){
		$('#'+newSelectId+' option[value='+selectedActivityId+']').attr('selected', 'selected');
	} else {
		$('#'+newSelectId+' option:first').attr('selected', 'selected');
	}
	
};

makeArray = function(currentParent){
	var returnArr = {};
	var childs;
	$.each(activityTypes, function(key,element) {
		if (currentParent==element["ActivityTypeParentID"]){
			
			returnArr[element["ActivityTypeID"]] = element;
			childs = makeArray(key);
			//if (childs!==false){
				returnArr[element["ActivityTypeID"]]["items"] = childs;
			//}
		}
	});
	if (returnArr.length<1){
		return false;
	} else {
		return returnArr;
	}
};

showSubelements = function(branchArray, selectedId){
	if (branchArray==false){
		return false;
	}
	$.each(branchArray, function(key,element) {
		if (element["items"]!=false && element["items"]!=null && element["items"]!=0){
			//showSubelements(element["items"], selectedId);
		}
		return false;
	});
	var newSelectId = createSelectAfter(selectsContainer, branchArray, 0, selectedId);
	setActiveSelect($("#"+newSelectId));
};

getSubbranch = function(branch, elementId){
	var returnValue = false;
	$.each(branch, function(key,element) {
		if (element["ActivityTypeParentID"]==elementId){
			returnValue = branch;
			return false;
		} else {
			if (element["items"]!=null){
				if (returnValue = getSubbranch(element["items"], elementId)){
					return false;
				}
			}
		}
	});
	return returnValue;
};

getSameBranch = function(branch, elementId){
	var returnValue = false;
	$.each(branch, function(key,element) {
		if (element["ActivityTypeID"]!=null && element["ActivityTypeID"]==elementId){
			returnValue = branch;
			return false;
		} else {
			if (element["items"]!=null){
				if (returnValue = getSameBranch(element["items"], elementId)){
					return false;
				}
			}
		}
	});
	return returnValue;
};

getStartingList = function(selectedId) {
	var currenParrentId = activityTypes[selectedId]["ActivityTypeParentID"];


	$.each(activityTypes, function(key,element) {
		if (currenParrentId == element["ActivityTypeID"] && currenParrentId!=0){
			getStartingList(element["ActivityTypeID"]);
			return false;
		}
	});
	startingSelects[currenParrentId] = activityTypes[selectedId];

};

showStartingList = function(selectedId) {
	var newSelectId;

	
	$.each(startingSelects, function(key,element) {
		newSelectId = createSelectAfter(selectsContainer, getSameBranch(activityTypesArr, element["ActivityTypeID"]), element["ActivityTypeID"], key);
	});
	setActiveSelect($("#"+newSelectId));
};

selectChangeFunction = function() {
		var afterCurrent = false;
		var currentElId = $(this).attr("id");
		
		selectedValue = $('#'+currentElId+' option:selected').attr('value');

		$.each(appSelects.selectsArr, function(key,element) {
			if (afterCurrent){
				$("#"+element["selectId"]).remove();
				appSelects.selectsArrRemove(key);
			}
			
			if (currentElId==element["selectId"]){
				afterCurrent = true;
				setActiveSelect($("#"+element["selectId"]));
			}
		});
		
		showSubelements(
			getSubbranch(activityTypesArr, selectedValue),
			$("#"+currentElId+" option:selected").val()
		);
			
};

appSelects = {
	"selectsArr" : {},
	"selectsCount" : 0,
	"selectsArrAdd" : function(selectId, elementId) {
		this.selectsArr[this.selectsCount+1] = {"selectId":selectId, "elementId":elementId};
		this.selectsCount++;
		return this.selectsCount;
	},
	"selectsArrRemove" : function(elementId) {
		if (this.selectsCount>0){
			delete this.selectsArr[elementId];
			this.selectsCount--;
		}
	},
	"getBySelectId" : function(elemetnId){
		var returnValue = false;
		$.each(activityTypes, function(key,element) {
			if (element["selectId"]==elemetnId){
				returnValue = element;
				return false;
			}
		});
		return returnValue;
	}
};

activityTypeSelectsSetup = function(fieldName, fieldId){
	/*if ($("#ActivitySubform-ActivityTypeID")!=null){
		selectsContainer = $("#ActivitySubform-ActivityTypeID").parent();
	} else {
		selectsContainer = $("#ActivityTypeID").parent();
	}*/
	if (fieldName==null){
		fieldName="ActivityTypeID";
	}
	if (fieldId==null){
		fieldId="ActivityTypeID";
	}
	selectsContainer = $("#"+fieldId).parent();
	activeSelectName = fieldName;
	selectParentsNamePrefix = "activitySelect";
	
	
	activityTypesArr = {};
	activityTypesArr = makeArray(0);
	
	// get current activity type
	var selectedActivityType = null;
	$.each(activityTypes, function(key,element) {
		if (element["IsSelected"]==1){
			selectedActivityType = key;
			return false;
		}
	});
		
	// remove old form field
	$("#"+fieldId).remove();
	
	startingSelects = {};
	getStartingList(selectedActivityType);
	showStartingList(selectedActivityType);
	

	appSelects.selectsArrAdd(activeSelectName, "0");


	$("#"+activeSelectName).change(selectChangeFunction);
	$(".activityParents").change(selectChangeFunction);
};

$("#AreaID").change(function() {
	selectedArea = this.options[this.selectedIndex].value;
	var countriesSelect = $("#CountryID")[0];

	for(i=1;i < countriesSelect.length;i++){
		var currEl = countriesSelect.options[i];
			currEl.style.display='';
	}
	if (selectedArea!=0){
		countriesSelect.options[0].selected="selected";
		for(i=1;i < countriesSelect.length;i++){
			var currEl = countriesSelect.options[i];
			var currElValue = currEl.value;
			var currElAreaID = currElValue.substr(0, currElValue.indexOf('_'));
			if (currElAreaID != selectedArea){
				currEl.style.display='none';				
			}
		}
	}
});


/**
 * 
 */
jQuery.fn.expandButton = function() {
	var contentId = $(this).attr("target");
	var contentEl = $("#"+contentId);
	var buttonElement = this;
	
	var visibilityCookie = $.cookie(contentId+"_block_visibility");
	if (visibilityCookie == '0'){
		contentEl.hide();
	}
	else if (visibilityCookie == '1'){
		contentEl.show();
	}
	
	if(contentEl.mpIsHidden()){
		buttonElement.children("span.state-1").hide();
		buttonElement.children("span.state-0").show();
	}
	else {
		buttonElement.children("span.state-0").hide();
		buttonElement.children("span.state-1").show();
	}
	$(this).click(function(event){
		event.preventDefault();
		if (contentId==null){
			return;
		}
		if (contentEl==null){
			return;
		}
		
		var stateValue = contentEl.mpIsVisible();
		
		contentEl.slideToggle();
		buttonElement.children("span").toggle();
		if(!stateValue){
			$.cookie(contentId+"_block_visibility", '1');
		}
		else {
			$.cookie(contentId+"_block_visibility", '0');
		}
		
	});
};

/**
 *  Tabs
 */
jQuery.fn.mpTabs = function() {
	var activeIcon = '<span class="inline-icon ui-icon ui-icon-triangle-1-n"></span>';
	var inactiveIcon = '<span class="inline-icon ui-icon ui-icon-triangle-1-s"></span>';
	
	var tabsConatinerEl = this;
	var firstVisibleEl = tabsConatinerEl.find(".tabsContentList :visible:first");
	var activeId = firstVisibleEl.attr("id");
	
	if (firstVisibleEl.hasClass('locked') || tabsConatinerEl.find(".tabsContentList :visible:first").hasClass("locked")){
		tabsConatinerEl.find(".tabsNavigationList a").addClass('disabled');
	}
	
	tabsConatinerEl.find('a[href$="#'+activeId+'"]').addClass("active");
	
	tabsConatinerEl.find(".tabsNavigationList a").not('.active')
		.append(inactiveIcon);
	tabsConatinerEl.find('.active').append(activeIcon);
	
	$(this).find(".tabsNavigationList a").click(function(event){
		event.preventDefault();
		
		var selectedId = $(this).attr("href").substring(1);
		var activeId = tabsConatinerEl.find(".tabsContentList :visible:first").attr("id");
		
		// if disabled
		if (tabsConatinerEl.find('.tabsNavigationList a[href$="#'+selectedId+'"]').hasClass("disabled")){
			return false;
		}

		// if closing
		if (selectedId==activeId){
			tabsConatinerEl.find('.tabsNavigationList a').removeClass('active');

			tabsConatinerEl.find("#"+selectedId).slideUp("fast");
			
			tabsConatinerEl.find('.tabsNavigationList a span.ui-icon').remove();
			tabsConatinerEl.find('.tabsNavigationList a').append(inactiveIcon);
		}
		// if any was opened
		else if (activeId!=null){
			tabsConatinerEl.find('.tabsNavigationList a').removeClass('active');
			tabsConatinerEl.find('.tabsNavigationList a[href$="#'+selectedId+'"]').addClass('active');

			tabsConatinerEl.find(".tabsContentList div.tabContent").hide();
			tabsConatinerEl.find("#"+selectedId).fadeIn();
			
			tabsConatinerEl.find('.tabsNavigationList a span.ui-icon').remove();
			tabsConatinerEl.find('.tabsNavigationList a').not('.active').append(inactiveIcon);
			tabsConatinerEl.find('.tabsNavigationList a.active').append(activeIcon);

		}
		// if none was selected
		else {
			tabsConatinerEl.find('.tabsNavigationList a[href$="#'+selectedId+'"]').addClass('active');

			tabsConatinerEl.find("#"+selectedId).slideDown("fast");
			
			tabsConatinerEl.find('.tabsNavigationList a span.ui-icon').remove();
			tabsConatinerEl.find('.tabsNavigationList a').not('.active').append(inactiveIcon);
			tabsConatinerEl.find('.tabsNavigationList a.active').append(activeIcon);
		}
	});
};

jQuery.fn.lockTabs = function() {
	$(this).addClass('locked');
	$(this).find(".tabsNavigationList a").addClass('disabled');
};

jQuery.fn.unlockTabs = function() {
	$(this).removeClass('locked');
	$(this).find(".tabsNavigationList a").removeClass('disabled');
};


/**
 *  OLD vivibility checking method
 */
jQuery.fn.mpIsHidden = function() {
	return ($(this).css('display')=='none' || $(this).css('visibility') == 'hidden');
};

jQuery.fn.mpIsVisible = function() {
	return !$(this).mpIsHidden();
};

/* FORM VALIDATION */

function showFormValidation(form, messagesArray, warningsArray)
{
		
    /*$.post(url,data,function(resp)
    {
    		$("#"+id).parent().find('.errors').remove();
    		$("#"+id).parent().append(getErrorHtml(resp[id], id));
    },'json');*/
	$(form).find('.errors').remove();
	$(form).find('.warnings').remove();
	
	if (messagesArray!=null){
		$.each(messagesArray, function(key,messages) {
			if (form.elements[key]!=null)
	    	{
	    		var errorHtml = getFormElementErrorHtml(messages, key);
	    		$(form.elements[key]).parent().find('.errors').remove();
	    		$(form.elements[key]).parent().append(errorHtml);
	
	    	}
	    	
	    });
	}
	if (warningsArray!=null){
		$.each(messagesArray, function(key,messages) {
			if (form.elements[key]!=null)
	    	{
	    		var errorHtml = getFormElementWarningHtml(messages, key);
	    		$(form.elements[key]).parent().find('.warnings').remove();
	    		$(form.elements[key]).parent().append(errorHtml);
	
	    	}
	    	
	    });
	}
}

function clearFormValidation(form){
	$(form).find('.errors').remove();
	$(form).find('.warnings').remove();
}


function getFormElementErrorHtml(elementErrors , id)
{
	var o = '<ul id="errors-'+id+'" class="errors">';
	for(errorKey in elementErrors)
	{
		o += '<li>' + elementErrors[errorKey] + '</li>';
	}
	o += '</ul>';
	return o;
}
function getFormElementWarningHtml(elementErrors , id)
{
    var o = '<ul id="warnings-'+id+'" class="warnings">';
    for(errorKey in elementErrors)
    {
        o += '<li>' + elementErrors[errorKey] + '</li>';
    }
    o += '</ul>';
    return o;
}

/* /FORM VALIDATION */


/* AJAX FORM UPLOADING */

jQuery.fn.uiButtonLoadingStart = function(options) {
	if (options==null){
		options = {};
	}
	if (options['side']==null){
		options['side'] = 'right';
	}
	
	var additionalClass="";
	if ($(this).attr('id')!=null){
		additionalClass = ' '+$(this).attr('id') + '_loadingIndicator';
	}
	
	options['indicatorHtml'] = '<span class="loadingIndicator'+ additionalClass +'"><img src="/media/indicator16x16.gif" alt="loading..." /></span>';
	
	$(this).attr('disabled', 'disabled');
	if (options['side']=='left'){
		$(this).before(options['indicatorHtml']);
	}
	else {
		$(this).after(options['indicatorHtml']);
	}
};

jQuery.fn.uiButtonLoadingFinished = function() {
	$(this).removeAttr("disabled");
	$(this).parent().find('.loadingIndicator').remove();
};

jQuery.fn.uiButtonLoadingError = function() {
	$(this).parent().find('.loadingIndicator').remove();
	$(this).after('<span class="loadingIndicator inline-icon ui-icon ui-icon-alert"></span>');
};

function processValidationErrors(importPartsErrors, columnNames){
	var linesArr = [];
	var lastPartId = 0;
	var currentLineId = -1;
	for(var i=0;i<importPartsErrors.length;i++){
		var currentError = importPartsErrors[i];

		// add new element
		if (currentError['PartImportID']!=lastPartId){
			currentLineId++;
			
			linesArr[currentLineId] = {};
			linesArr[currentLineId]['ItemID'] = currentError['PartImportID'];
			linesArr[currentLineId]['LineNumber'] = currentError['FileLineNumber'];
			linesArr[currentLineId]['ErrorTexts'] = [];
			linesArr[currentLineId]['LineElements'] = [];
			
			linesArr[currentLineId]['RowValues'] = jQuery.extend(true, {}, columnNames);
			
			if (columnNames!=null){
				$.each(columnNames, function(key, value) {
					if (importPartsErrors[i][key]!=null){
						linesArr[currentLineId]['RowValues'][key] = importPartsErrors[i][key];
					}
				});
				/*for (j=0;j<columnNames.length;j++){
					linesArr[currentLineId][] = 
				}*/
			}			
		}
		

		
		// add other subelements
		
		linesArr[currentLineId]['ErrorTexts'].push(currentError['ErrorText']);
		linesArr[currentLineId]['LineElements'].push({
			ErrorColumnType: currentError['ErrorColumnType'],
			ErrorColumnName: currentError['ErrorColumn'],
			ErrorColumnTitle: currentError['ErrorColumnTitle'],
			ErrorColumnValues: currentError['ErrorColumnValues'],
			ErrorColumnValue: currentError['ErrorColumnValue'],
			ErrorType: currentError['ErrorType']
		});
		
		lastPartId = currentError['PartImportID'];
	}
	return linesArr;
}

function getValidationLineValues(rowValues){
	var returnStr = '';
	var elNum = 0;
	$.each(rowValues, function(key, value){
		if (value==null || value=='' || value==undefined)
			return true;
		
		if (elNum!=0)
			returnStr += ' | ';
			
		returnStr += value;
		elNum++;
	});
	return returnStr;
}

function showValidationErrors(containerId, importTempParts, importPartsErrors, importSummary, columnNames){
	initUploadProgressStep(2, 100, '{ERRORS}');
	if (importPartsErrors != null){

		// PARTS ERRORS
		/*for(var i=0;i<importTempParts.length;i++){
			for(var j=0;j<importPartsErrors.length;j++){
				if (importTempParts[i]['PartID']==importPartsErrors[j]['PartImportID']){
					if (importTempParts[i]['errors']==null){
						importTempParts[i]['errors'] = importPartsErrors[j]['ErrorText'];
					}
					else {
						importTempParts[i]['errors'] += ', ' + importPartsErrors[j]['ErrorText'];
					}
					importPartsErrors[j]['tempEntryId'] = i;
				}
			}

		}*/
		
		
		var linesArr = processValidationErrors(importPartsErrors, columnNames);
		var errorsFormContent = getPartsImportSummaryErrors(importSummary);

		var lastPartId = 0;
		for(var i=0;i<linesArr.length;i++){
			var currentError = linesArr[i];
			if (lastPartId!=0){
				errorsFormContent += '</fieldset>';
			}
			errorsFormContent += '<fieldset class="clearfix">';
			errorsFormContent += '<div class="importLineHeaderContainer clearfix"><label class="importLineNumber slideSwitchButton" for="importLinePartData_'+i+'"><span class="ui-icon ui-icon-circle-triangle-e"></span>Line #' + currentError['LineNumber'] +  '</label>'
			errorsFormContent += '<label class="importLineErrorsText">' + currentError['ErrorTexts'].join(', ') +  '</label></div>';
			errorsFormContent += '<div id="importLinePartData_'+i+'" class="slideSwitchContent hideDisplay">'+getValidationLineValues(currentError['RowValues'])+'</div>';
			
			
			for (j=0; j<currentError['LineElements'].length; j++){
				errorsFormContent += getErrorFormElement(currentError['LineElements'][j]['ErrorColumnType'],
						currentError['ItemID'],
						currentError['LineNumber'],
						currentError['LineElements'][j]['ErrorColumnName'],
						currentError['LineElements'][j]['ErrorColumnTitle'],
						currentError['LineElements'][j]['ErrorColumnValues'],
						currentError['LineElements'][j]['ErrorColumnValue']);
				
			}
			
			lastPartId = currentError['PartImportID'];
		}
		if (lastPartId != 0){
			errorsFormContent += '</fieldset>';
		}
		

		$('.uploadingProgress .uploadingErrorsInnerContainer').html(errorsFormContent);

		
		// TODO
		/*$("#"+containerId).jqGrid({
			datatype: 'local',
			data: errorsTableData,
			colNames: importGridColNames,
			colModel :importGridColModel,
			pager: jQuery("#"+containerId+'_pager'),
			rowNum:10,
			rowList:[10,20,30],
			//sortname: 'id',
			//sortorder: "desc",
			scroll:1,
			loadonce:true,
			//viewrecords: true,
			//imgpath: 'themes/basic/images',
			cellEdit: true,
			cellsubmit: 'clientArray',
			//editurl: 'clientArray',
			caption: 'Found errors',

			afterSaveCell : function(rowid,name,val,iRow,iCol) {
				//for(var j=0;j<errorsTableData.length;j++)
				//errorsTableData[j]['PartName'] = 'xxxxxxxxxxxxxxxxxxx';
				//$("#"+containerId).jqGrid('saveRow',rowid, false, 'clientArray');
				//alert(' - rowid:'+rowid+' - name:'+name+' - val:'+val+' - iRow:'+iRow+' - iCol:'+iCol);
				
				tmpPartId = $("#"+containerId).getCell(rowid, 'PartID');
				for(var j=0;j<errorsTableData.length;j++){
					if (errorsTableData[j]['PartID'] == tmpPartId){
						errorsTableData[j][name] = val;
						//console.log(errorsTableData[j]);
					}
				}

				//console.log($("#"+containerId));

				$("#"+containerId).jqGrid('setGridParam', {data : errorsTableData});
				//$(this).data.1.PartName = 'sadasdasdasdsad';
				//$("#"+containerId).jqGrid('setRowData',rowid,{name:val});
			},
			width: 565,
			gridComplete: function(){
				//console.log();
				var visibleRowsId = $("#"+containerId).getDataIDs();
				
				var tmpPartId = 0;
				//var tmpRowErrors = [];
				for(var i=0;i<visibleRowsId.length;i++){
					//tmpRowErrors = [];
					tmpPartId = $("#"+containerId).getCell(visibleRowsId[i], 'PartID');
					
					for(var j=0;j<importPartsErrors.length;j++){
						if (importPartsErrors[j]['PartID']==tmpPartId){
							//tmpRowErrors.push(importPartsErrors[j]);
							$("#"+containerId).setCell(visibleRowsId[i], importPartsErrors[j]['ErrorColumn'], '', 'hasErrors');
						}
					}
				}
				
				
				//$("#"+containerId).find("tr").qtipTableRow('aria-describedby', 'uploadTempPartsGrid_errors');
				
				//for(var j=0;j<importPartsErrors.length;j++){
				//	$("#"+containerId).setCell(importPartsErrors[j]['tempEntryId']+1, importPartsErrors[j]['ErrorColumn'], '', 'hasErrors');
				//}

			}
		});*/
		
		//for(var i=0;i<=errorsTableData.length;i++)
		//	$("#"+containerId).jqGrid('addRowData',i+1,errorsTableData[i]);
		
		
		

		
	}
	$('.uploadingProgress .uploadingErrorsContainer').show();
	$('.uploadingProgress .stepInfo').hide();
	
	$('.uploadingProgress .step-2').addClass('errors');



}

function getPartsImportSummaryErrors(summary){
	if (summary.partsSuccessCount == null){
		summary.partsSuccessCount = 0;
	}
	if (summary.partsAdminAcceptCount == null){
		summary.partsAdminAcceptCount = 0;
	}
	if (summary.partsErrorCount == null){
		summary.partsErrorCount = 0;
	}
	
	var errorsFormContent = '';
	
	errorsFormContent += '<div class="importFormMessageSuccess">'+summary.partsSuccessCount+' Parts were successfully imported';
	if (summary.partsAdminAcceptCount>0){
		errorsFormContent += ' <span>(but '+summary.partsAdminAcceptCount+' of them needs to be accepted by admin first)</span>';
	}
	errorsFormContent += '</div>';
	
	errorsFormContent += '<div class="importFormMessageErrors">'+summary.partsErrorCount+' Parts failed our import checks.<span> Please use form below to correct them or use button to download a CSV of problem parts and continue processing the corrected parts<span></div>';

	return errorsFormContent;
}


function showUploadSummary(data){
	if (data.partsSuccess == null || data.partsSuccess == ''){
		data.partsSuccess = 0;
	}
	if (data.partsSkip == null || data.partsSkip == ''){
		data.partsSkip = 0;
	}
	if (data.partsAdminAccept == null || data.partsAdminAccept == ''){
		data.partsAdminAccept = 0;
	}
	
	data.partsSuccess = parseInt(data.partsSuccess);
	data.partsSkip = parseInt(data.partsSkip);
	data.partsAdminAccept = parseInt(data.partsAdminAccept);
	
	var summaryContent = '<ul>';
	
	summaryContent += '<li class="partsSuccess first"><span>'+data.partsSuccess+'</span> part(s) were successfully imported, but they need to be accepted before they are live on the site <a href="/member/parts">Display them now</a></li>';
	if (data.partsAdminAccept){
		summaryContent += '<li class="partsSkip first"><span>'+data.partsAdminAccept+'</span> part(s) needs to be accepted by admin before they will appear in your <a href="/member/parts">parts list</a></li>';
	}
	if (data.partsSkip){
		summaryContent += '<li class="partsSkip first"><span>'+data.partsSkip+'</span> part(s) were skipped </li>';
	}
	if (data.reachedFileLimit){
		summaryContent += '<li class="partsSkip first"><h4 class="partsFatalError">Rest of the parts were skipped due to reaching maximum parts number per file: 64000<h4></li>';		
	}
	

	
	summaryContent += '</ul>';
	
	$('.uploadSummary').html(summaryContent);
	$('.uploadSummary').show();
}

function showUploadFatalError(data){

	var summaryContent = '<h4 class="partsFatalError">Your file appears to be empty</h4>';
	
	$('.uploadSummary').html(summaryContent);
	$('.uploadSummary').show();
}
function getErrorFormElement(elementType, itemId, line, columnName, columnTitle, possibleValues, enteredValue){
	var elId = 'importError_'+itemId+'_'+columnName;
	var elName = 'correctedParts['+itemId+']['+columnName+']';
	if (enteredValue==null){
		enteredValue = '';
	}
	
	switch (elementType) {
	case 'text':
		var labelHtml = '<label for="'+elId+'">'+columnTitle+'</label>';
		var elHtml = '<input type="text" name="'+elName+'" id="'+elId+'" class="TextInput" value="'+enteredValue+'" />';
		break;
		
	case 'select':
		var labelHtml = '<label for="'+elId+'">'+columnTitle+'</label>';
		var elHtml = '<select name="'+elName+'" id="'+elId+'" class="SelectInput">';
		if (possibleValues != null){
			$.each(possibleValues, function(index, value) { 
				elHtml += '<option value="'+index+'">'+value+'</option>';
			});
		}
		elHtml += '</select>';
		
		break;
		
	case 'textAccept':
		var elAddedLabelTitle = '<span class="labelInfo">new values must be accepted by Admin</span>';
		var labelHtml = '<label for="'+elId+'">'+columnTitle+' '+ elAddedLabelTitle +'</label>';
		var elHtml = '';
		elHtml += '<div class="radioList">';
		elHtml += '<input type="radio" name="'+elId+'_radio" id="'+elId+'_radio_add" checked="checked" class="RadioInput selectAdd" />';
		elHtml += '<label for="'+elId+'_radio_add" class="radioLabel">add new maker name</label>';
		elHtml += '<br />';
		elHtml += '<input type="radio" name="'+elId+'_radio" id="'+elId+'_radio_choose" class="RadioInput selectChoose" />';
		elHtml += '<label for="'+elId+'_radio_choose" class="radioLabel">choose maker name from list</label>';
		elHtml += '</div>';

		elHtml += '<select name="'+elName+'" id="'+elId+'_select" disabled="disabled" class="SelectInput hideDisplay">';
		if (possibleValues != null){
			$.each(possibleValues, function(index, value) {
				elHtml += '<option value="'+index+'">'+value+'</option>';
			});
		}
		elHtml += '</select>';
		elHtml += '<input type="text" name="'+elName+'" id="'+elId+'_text" value="'+enteredValue+'" class="TextInput" />';
		
		break;

	default:
		throw 'Unknown form element type';
		break;
	}
	
	elementClass = 'element' + elementType.capitalize(); 
	
	return '<div class="errorElementField '+elementClass+'">' + labelHtml + elHtml + '</div>';
}

// JQGRID GET ROW BY HIDDEN KEY
jQuery.fn.jqgridGetRowByKey = function() {
	$(this).getCell(rowid, 'MyCol');
};



function convertArrayToPost(data, currentKey, returnArr){
	if (returnArr==null)
		var returnArr = {};
	
	$.each(data, function(index, value) { 
		//console.log(typeof value);
	  	if (currentKey!=null){
			index = currentKey + "[" + index + "]";
		}
	  	if (typeof value == 'object' || typeof value == 'array'){
	  		returnArr = convertArrayToPost(value, index, returnArr);
	  	}
	  	else {
	  		returnArr[index] = value;
	  	}
	});
	return returnArr;
}



function initUploadProgressStep(step, value, textValue){ 
	if (value==null || value==0){
		value = 1;
	}
	
	switch (step) {
	case 0:
		$('.uploadingProgress .step-1 .progressBar').progressbar( "destroy" );
		$('.uploadingProgress .step-1').removeClass('active').removeClass('completed').removeClass('errors');
		$('.uploadingProgress .step-1 .progressPercent').html('');
		$('.uploadingProgress .step-2 .progressBar').progressbar( "destroy" );
		$('.uploadingProgress .step-2').removeClass('active').removeClass('completed').removeClass('errors');
		$('.uploadingProgress .step-2 .progressPercent').html('');
		$('.uploadingProgress .step-3 .progressBar').progressbar( "destroy" );
		$('.uploadingProgress .step-3').removeClass('active').removeClass('completed').removeClass('errors');
		$('.uploadingProgress .step-3 .progressPercent').html('');
		
		$('.uploadingProgress .step-1 .stepInfo').hide();
		$('.uploadingProgress .step-2 .stepInfo').hide();
		$('.uploadingProgress .step-3 .stepInfo').hide();
		
		$('.uploadingProgress .uploadSummary').hide();
		$('.uploadingProgress .uploadingOptions .hide').hide();
		$('.uploadingProgress .uploadingOptions .cancel').show();
		
		break;
		
	case 1:
		$('.uploadingProgress .step-1 .progressBar').progressbar({ value: value });
		$('.uploadingProgress .step-1').addClass('active').removeClass('errors');
		$('.uploadingProgress .step-1 .progressPercent').html(getProgressPercentValue(value));
		
		$('.uploadingProgress .step-1 .stepInfo').show();
		$('.uploadingProgress .step-2 .stepInfo').hide();
		$('.uploadingProgress .step-3 .stepInfo').hide();
		$('.uploadingProgress .uploadingErrorsContainer').hide();
		
		$('.uploadingProgress .uploadSummary').hide();
		$('.uploadingProgress .uploadingOptions .hide').hide();
		$('.uploadingProgress .uploadingOptions .cancel').show();

		break;
		
	case 2:
		$('.uploadingProgress .step-1 .progressBar').progressbar({ value: 100 })
			.progressbar( "option", "disabled", true );
		$('.uploadingProgress .step-1').removeClass('active').addClass('completed').removeClass('errors');
		$('.uploadingProgress .step-1 .progressPercent').html(getProgressPercentValue(100));
		$('.uploadingProgress .step-2 .progressBar').progressbar({ value: value });
		$('.uploadingProgress .step-2').addClass('active').removeClass('errors');
		if (textValue!=null)
			$('.uploadingProgress .step-2 .progressPercent').html(textValue);
		else
			$('.uploadingProgress .step-2 .progressPercent').html(getProgressPercentValue(value));
		
		$('.uploadingProgress .step-1 .stepInfo').hide();
		$('.uploadingProgress .step-2 .stepInfo').show();
		$('.uploadingProgress .step-3 .stepInfo').hide();
		
		$('.uploadingProgress .uploadingErrorsContainer').hide();
		$("#uploadTempPartsGrid").GridUnload();
		
		$('.uploadingProgress .uploadSummary').hide();
		$('.uploadingProgress .uploadingOptions .hide').hide();
		$('.uploadingProgress .uploadingOptions .cancel').show();

		break;
		
	/*case 3:
		$('.uploadingProgress .step-1 .progressBar').progressbar({ value: 100 })
		.progressbar( "option", "disabled", true );
		$('.uploadingProgress .step-1').removeClass('active').addClass('completed');
		$('.uploadingProgress .step-1 .progressPercent').html('(100%)');
		$('.uploadingProgress .step-2 .progressBar').progressbar({ value: 100 })
			.progressbar( "option", "disabled", true );
		$('.uploadingProgress .step-2').removeClass('active').addClass('completed');
		$('.uploadingProgress .step-3 .progressPercent').html('(100%)');
		$('.uploadingProgress .step-3 .progressBar').progressbar({ value: value });
		$('.uploadingProgress .step-3').addClass('active');
		$('.uploadingProgress .step-3 .progressPercent').html('('+Math.round(value)+'%)');
		
		$('.uploadingProgress .step-1 .stepInfo').hide();
		$('.uploadingProgress .step-2 .stepInfo').hide();
		$('.uploadingProgress .step-3 .stepInfo').show();
		
		break;*/
		
	case 4:
		$('.uploadingProgress .step-1 .progressBar').progressbar({ value: 100 })
		.progressbar( "option", "disabled", true );
		$('.uploadingProgress .step-1').removeClass('active').addClass('completed').removeClass('errors');
		$('.uploadingProgress .step-1 .progressPercent').html(getProgressPercentValue(100));
		$('.uploadingProgress .step-2 .progressBar').progressbar({ value: 100 })
			.progressbar( "option", "disabled", true );
		$('.uploadingProgress .step-2').removeClass('active').addClass('completed').removeClass('errors');
		$('.uploadingProgress .step-2 .progressPercent').html(getProgressPercentValue(100));
		$('.uploadingProgress .step-3 .progressBar').progressbar({ value: 100 })
		.progressbar( "option", "disabled", true );
		$('.uploadingProgress .step-3').removeClass('active').addClass('completed');
		$('.uploadingProgress .step-3 .progressPercent').html(getProgressPercentValue(100));
		
		$('.uploadingProgress .step-1 .stepInfo').hide();
		$('.uploadingProgress .step-2 .stepInfo').hide();
		$('.uploadingProgress .step-3 .stepInfo').hide();
		
		$('.uploadingProgress .uploadingErrorsContainer').hide();
		$("#uploadTempPartsGrid").GridUnload();

		$('.uploadingProgress .uploadingOptions .cancel').hide();
		$('.uploadingProgress .uploadingOptions .hide').show();

		
		break;
		
	default:
		break;
	}
}

function getProgressPercentValue(value){
	if (value==100){
		return '{DONE}';
	}
	
	return '{' + Math.round(value) + '%}';
}

function changeUploadProgressStep(step, value){
	if (value==null || value==0){
		value = 1;
	}
	
	switch (step) {
	case 1:
		$('.uploadingProgress .step-1 .progressBar').progressbar( "option", "value", value );
		$('.uploadingProgress .step-1 .progressPercent').html(getProgressPercentValue(value));
		
		break;
		
	case 2:
		$('.uploadingProgress .step-2 .progressBar').progressbar( "option", "value", value );
		$('.uploadingProgress .step-2 .progressPercent').html(getProgressPercentValue(value));
		
		break;
		
	case 3:
		$('.uploadingProgress .step-3 .progressBar').progressbar( "option", "value", value );
		$('.uploadingProgress .step-3 .progressPercent').html(getProgressPercentValue(value));

		break;

	default:
		break;
	}
}

uploadProgressParams = {
		progressURL:'/upload_progress.php',
		//debugDisplay:'#upload-progress-debug',
		displayFields : ['kb_uploaded','kb_average','est_sec'],
		start: function() {
			$('.uploadForm [type=submit]').uiButtonLoadingStart();
			$('.uploadTabs').lockTabs();
			var fileValue = $(this).find('[name=Parts]').val();
			if (fileValue){
				$('.stepsSummary .processFilenameField').html(fileValue);
				$('.stepsSummary .processFilenameField').parent().show();
			} else {
				$('.stepsSummary .processFilenameField').html('');
				$('.stepsSummary .processFilenameField').parent().hide();
			}
			$('.stepsSummary .processInventoryField').html('');
			$('.stepsSummary .processInventoryField').parent().hide();
		},
		firstProgressFunction: function() {
			jQuery('#uploadMusicFormContainer [type=submit]').uiButtonLoadingFinished();
			$('.uploadingIntroduction').hide();
			$('.uploadingProgress').fadeIn();
			initUploadProgressStep(1);
			$('.uploadingProgress .processStatusField').html('Validating file');
		},
		success: function(jsonResponse) {
			$('.uploadForm [type=submit]').uiButtonLoadingFinished();
			if (!$('.uploadingProgress').is(':visible')){
				$('.uploadingIntroduction').hide();
				$('.uploadingProgress').fadeIn();
			}
			initUploadProgressStep(2);
			$('.uploadingProgress .processStatusField').html(jsonResponse.threadData.StatusName);
			keepRefreshing = 1;
			clearFormValidation(this);
			//window.location = "#/"+jsonResponse.musicId;
		},
		failed: function() {
			$('.uploadForm [type=submit]').uiButtonLoadingError();
			//jQuery(this).get(0).reset();
			$('.uploadTabs').unlockTabs();
		},
		warning: function(messagesArray) {
			$('.uploadForm [type=submit]').uiButtonLoadingFinished();
			showFormValidation(this, messagesArray);
			$('.uploadTabs').unlockTabs();
			$('.uploadingProgress').hide();
			$('.uploadingIntroduction').fadeIn();
			$('.uploadingProgress .step-1').removeClass('active');
		},
		progressFunction: function(newValue) {
			changeUploadProgressStep(1, newValue);
		},
		beforeFirstSubmitFunction: function(form) {
			jQuery(form).attr("action",jQuery(form).attr("action")+"/isXhr/1");
		}
	};

/*/AJAX FORM UPLOADING */


/**
 * urlencode
 * http://plugins.jquery.com/project/URLEncode
 */ 
$.extend({URLEncode:function(c){var o='';var x=0;c=c.toString();var r=/(^[a-zA-Z0-9_.]*)/;
while(x<c.length){var m=r.exec(c.substr(x));
  if(m!=null && m.length>1 && m[1]!=''){o+=m[1];x+=m[1].length;
  }else{if(c[x]==' ')o+='+';else{var d=c.charCodeAt(x);var h=d.toString(16);
  o+='%'+(h.length<2?'0':'')+h.toUpperCase();}x++;}}return o;},
URLDecode:function(s){var o=s;var binVal,t;var r=/(%[^%]{2})/;
while((m=r.exec(o))!=null && m.length>1 && m[1]!=''){b=parseInt(m[1].substr(1),16);
t=String.fromCharCode(b);o=o.replace(m[1],t);}return o;}
});

function nl2br (str, is_xhtml) {
    // Converts newlines to HTML line breaks  
    // 
    // version: 911.1619
    // discuss at: http://phpjs.org/functions/nl2br    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Philip Peterson
    // +   improved by: Onno Marsman
    // +   improved by: Atli Þór
    // +   bugfixed by: Onno Marsman    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Maximusya
    // *     example 1: nl2br('Kevin\nvan\nZonneveld');    // *     returns 1: 'Kevin\nvan\nZonneveld'
    // *     example 2: nl2br("\nOne\nTwo\n\nThree\n", false);
    // *     returns 2: '<br>\nOne<br>\nTwo<br>\n<br>\nThree<br>\n'
    // *     example 3: nl2br("\nOne\nTwo\n\nThree\n", true);
    // *     returns 3: '\nOne\nTwo\n\nThree\n'
	var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '' : '<br>';
 
    return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
}

/*** *** ***/


// POPUP JQUERY PLUGIN
// http://swip.codylindley.com/popupWindowDemo.html
(function($){ 		  
	$.fn.popupWindow = function(instanceSettings){
		
		return this.each(function(){
		
		$(this).click(function(){
		
		$.fn.popupWindow.defaultSettings = {
			centerBrowser:0, // center window over browser window? {1 (YES) or 0 (NO)}. overrides top and left
			centerScreen:0, // center window over entire screen? {1 (YES) or 0 (NO)}. overrides top and left
			height:500, // sets the height in pixels of the window.
			left:0, // left position when the window appears.
			location:0, // determines whether the address bar is displayed {1 (YES) or 0 (NO)}.
			menubar:0, // determines whether the menu bar is displayed {1 (YES) or 0 (NO)}.
			resizable:0, // whether the window can be resized {1 (YES) or 0 (NO)}. Can also be overloaded using resizable.
			scrollbars:0, // determines whether scrollbars appear on the window {1 (YES) or 0 (NO)}.
			status:0, // whether a status line appears at the bottom of the window {1 (YES) or 0 (NO)}.
			width:500, // sets the width in pixels of the window.
			windowName:null, // name of window set from the name attribute of the element that invokes the click
			windowURL:null, // url used for the popup
			top:0, // top position when the window appears.
			toolbar:0//, // determines whether a toolbar (includes the forward and back buttons) is displayed {1 (YES) or 0 (NO)}.
			//autoPrint:0 // determines whether to start print dialog
		};
		
		settings = $.extend({}, $.fn.popupWindow.defaultSettings, instanceSettings || {});
		
		var windowFeatures =    'height=' + settings.height +
								',width=' + settings.width +
								',toolbar=' + settings.toolbar +
								',scrollbars=' + settings.scrollbars +
								',status=' + settings.status + 
								',resizable=' + settings.resizable +
								',location=' + settings.location +
								',menuBar=' + settings.menubar;

				settings.windowName = this.name || settings.windowName;
				settings.windowURL = this.href || settings.windowURL;
				var centeredY,centeredX;
				
				var currentWindow;
			
				if(settings.centerBrowser){
						
					if ($.browser.msie) {//hacked together for IE browsers
						centeredY = (window.screenTop - 120) + ((((document.documentElement.clientHeight + 120)/2) - (settings.height/2)));
						centeredX = window.screenLeft + ((((document.body.offsetWidth + 20)/2) - (settings.width/2)));
					}else{
						centeredY = window.screenY + (((window.outerHeight/2) - (settings.height/2)));
						centeredX = window.screenX + (((window.outerWidth/2) - (settings.width/2)));
					}
					currentWindow = window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + centeredX +',top=' + centeredY).focus();
				}else if(settings.centerScreen){
					centeredY = (screen.height - settings.height)/2;
					centeredX = (screen.width - settings.width)/2;
					currentWindow = window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + centeredX +',top=' + centeredY).focus();
				}else{
					currentWindow = window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + settings.left +',top=' + settings.top).focus();	
				}


				return false;
			});
			
		});	
	};
})(jQuery);

/**
 * Upper case first letter
 * @return
 */
String.prototype.capitalize = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}
