// These scripts are powered by jQuery...

// execute when DOM is ready
jQuery(document).ready(function($) {

// table sorter
$("body.Products table.sort").tablesorter({ 
	// disable headers (zero index, i.e. 0 = 1st column) 
	headers: { 
		0: { sorter: false }, 
		3: { sorter: false }, 
		4: { sorter: false }, 
		5: { sorter: false }, 
		6: { sorter: false }, 
		7: { sorter: false }, 
		8: { sorter: false }, 
		9: { sorter: false }   
	} 
});

// table row hover
$("table.style tr").hover(
	function() {$(this).addClass("hover");},
	function() {$(this).removeClass("hover");}
);

// inline labels
$(':input.inlinelabel').inlineLabel();

// date picker
$(".datepicker").datepicker({
			showOn: 'button',
			buttonImage: 'public/js/calendar.gif',
			buttonImageOnly: true
		});



// ADD/EDIT DIALOG BOXES
// ------------------------------------------------------------------------------

$("#eventhide").hide();
var dialogBox = $("#dialog"),
	msg = $("#dialog-message"),
	msgOrigText = msg.text(),
	allFields = $(":input:not(:radio, :button)", dialogBox);
	defaultCheckedFields = $(":checked", dialogBox);
	
// Admin page
var	adminDialogBox = $("#dialog"),
	adminName = $(":input#txtName", adminDialogBox),
	adminEmail = $(":input#txtEmail", adminDialogBox),
	adminPassword = $(":input#txtPassword", adminDialogBox),
	adminPasswordConfirm = $(":input#txtPasswordConfirm"),
	adminRole = $(":input#selRole", adminDialogBox),
	adminStore = $(":input#txtStore", adminDialogBox),
	adminActiveYes = $(":input#radActiveYes", adminDialogBox),
	adminActiveNo = $(":input#radActiveNo", adminDialogBox),
	adminFields = $([]).add(adminName).add(adminEmail).add(adminPassword).add(adminStore);
	
// dialog messages
function updateMessage(t) {
	msg.text(t).effect("highlight",{},1500);
}

// form field length validator
function checkLength(o,n,min,max) {
	var min = (min == null) ? 4 : min; // default value
	var max = (max == null) ? 100 : max; // default value
	if ( o.val().length > max || o.val().length < min ) {
		o.addClass("ui-state-error");
		updateMessage("Length of " + n + " must be between "+min+" and "+max+" characters.");
		return false;
	} else {
		return true;
	}
}

// initialize dialog
dialogBox.dialog({
	bgiframe: true,
	autoOpen: false,
	width: 400,
	modal: true,
	close: function() {
		allFields.val("").removeClass("ui-state-error");
		// return all checkboxes and radio buttons back to default state
		defaultCheckedFields.each(function() {
			$(this)[0].checked = true;
		});
		msg.text(msgOrigText);
	}
});

adminDialogBox.dialog('option', 'width', 960);

// 'update' button - Admin page
$("button.update", adminDialogBox).click(function() {
	var bValid = true;
	allFields.removeClass("ui-state-error");

	bValid = bValid && checkLength(adminName,"user name");
	bValid = bValid && checkLength(adminEmail,"email");
	bValid = bValid && checkLength(adminPassword,"password",6,10);
	bValid = bValid && checkLength(adminStore,"store #",3,8);
	
	if (bValid) {
		dialogBox.dialog("close");
	}
});	

// 'cancel' button
$("button.cancel", dialogBox).click(function() {
	dialogBox.dialog("close");
});	


// 'edit/update' mode - Admin page
$("body.admin button.edit").click(function() {
	var nameEdit = $(this).parent().siblings(".userName").text(),
		roleEdit = $(this).parent().siblings(".userRole").text(),
		storeEdit = $(this).parent().siblings(".userStore").text(),
		activeEdit = $(this).parent().siblings(".userActive").text();
	adminName.val(nameEdit);
	adminStore.val(storeEdit);
	if (activeEdit == "Yes") {
		adminActiveYes[0].checked = true;
	}
	else {
		adminActiveNo[0].checked = true;
	}
});

// 'edit/update' mode
$("button.edit").click(function() {
	changeDialogMode("edit");
	dialogBox.dialog("open");
});	

// 'add new' mode
$("button.add").click(function() {
	changeDialogMode("add");
	dialogBox.dialog("open");
});

// change dialog mode
var dialogTitle = $(".ui-dialog-title"),
	dialogButton = $("button.update"),
	defaultTitleText = dialogTitle.text(),
	defaultButtonText = dialogButton.text();
function changeDialogMode(mode) {
	switch (mode) {
		case "add":
			var titleReplaceText = "Add New",
				titleText = defaultTitleText.replace("Update", titleReplaceText),
				buttonText = "Add";
			dialogBox.dialog("option", "title", titleText);
			dialogButton.text(buttonText);
			break;
		case "edit":
			dialogBox.dialog("option", "title", defaultTitleText);
			dialogButton.text(defaultButtonText);
			break;
	}
}


// PREVIEW DIALOG BOXES
// ------------------------------------------------------------------------------

var dialogPreview = $("#dialog-preview"),
	dialogPreviewCart = $("body.cart #dialog-preview"),
	dialogPreviewCustom = $("body.custom #dialog-preview");

// initialize dialog
dialogPreview.dialog({
	autoOpen: false,
	width: 800,
	modal: true,
	open: function() {
	// load pdf
	var src = $("iframe", this).attr("src");
	$("iframe", this).attr("src", src);
	}
});





	// multi-item message toggle
	var apparelMessage = $("#message .row.apparel"),
		sameMessage = $("#message .row.same");
	apparelMessage.hide();
	sameMessage.hide();
	$("#message input[name='radType']").click(function(){
		if ($("input[name='radType']:checked").val() == 'apparel') {
			sameMessage.fadeOut("fast", function() {
				apparelMessage.fadeIn("fast");
			});
		}
		else {
			apparelMessage.fadeOut("fast", function() {
				sameMessage.fadeIn("fast");
			});
		}
	});
	

});
// end DOM ready execution


// FUNCTIONS
// ------------------------------------------------------------------------------

// return largest value from array
Array.max = function(array){
	return Math.max.apply( Math, array );
};

// capitalize word
String.prototype.capitalize = function(){
    return this.replace(/\w+/g, function(a){
        return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase();
    });
};

// make question and answer same height
(function($){
	$.fn.faqAdjustHeight = function() {
		return this.each(function() {
			var thisQuestion = $(this),
				thisAnswer = thisQuestion.next(),
				questionHeight = thisQuestion.height(),
				answerHeight = thisAnswer.height();
			if (questionHeight > answerHeight) {
				thisAnswer.height(questionHeight);
				thisQuestion.height(questionHeight);
			}
			else {
				thisQuestion.height(answerHeight);
				thisAnswer.height(answerHeight);
			}
		});
	}
})(jQuery);

// inline form field label
(function($){
	$.fn.inlineLabel = function() {
		return this.each(function() {
			var label = $(this).attr('title');
			if ($(this).val() === '') {
				$(this).val(label)
					.addClass('inlinelabel');
			}
			$(this).focus(function() {
					if ($(this).val() === label) {
						$(this).val('').removeClass('inlinelabel');
					}
				})
				.blur(function() {
					if ($(this).val() === '') {
						$(this).val(label).addClass('inlinelabel');
					}
				});
		 });	
	}
})(jQuery);

// width equalizer
(function($){
	$.fn.equalizer = function() {
		var max = 0;
		this.each(function(){
			if ($(this).width() > max)
				max = $(this).width();    
		});
		return this.width(max);	
	}
})(jQuery);


function numberValidation(event) {
	
	var charCode = (event.which) ? event.which : event.keyCode
	
	if (charCode > 31 && (charCode < 48 || charCode > 57))
	{
		return false;
	}
	else
	{
		return true;
	}
}

//---------------------- Start  custom function -----------------------------//


function getTableNameAndColumn(){
	var v_table_name = $("#vtable_name").val();
	//alert('Table Name '+v_table_name);
	$("#table_name").text(' '+v_table_name);

	$.ajax({
			type:'post',
	  		url:'/test/table_desc.php',
	  		data : '&v_table='+v_table_name,
	  		cache:false,
	  		async:true,
	  		success:function(html) {
				$("#div_column_name").empty();
	      		$("#div_column_name").append(html);
				//alert(html);
			}
	});
}



function toProperCaseStr(){
	//alert('text');
	var v_field= $("#vcolumn_name").val();
	var v_table_name = $("#vtable_name").val();	
	var msg=v_field; 
	msg=msg.replace(/_/g," ");
	v_text = toTitleCase(msg.toLowerCase());
	$("#vcolumn_text").val(v_text);
	$("#vcolumn_hint").val('Enter '+ v_text);
	//alert('text: '+v_text);

	$.ajax({
		type:'post',
  		url:'/test/table_field_type.php',
  		data : '&v_table='+v_table_name+'&v_field_name='+v_field,
  		cache:false,
  		async:true,
  		success:function(html) {
			//$("#div_column_name").empty();
      		$("#vdata_type").val(html);
			//alert(html);
		}

	});

	$.ajax({
		type:'post',
  		url:'/test/table_field_length.php',
  		data : '&v_table='+v_table_name+'&v_field_name='+v_field,
  		cache:false,
  		async:true,
  		success:function(html) {
				//alert(html);
			//$("#div_column_name").empty();
      		$("#vdata_length").val(html);
			
		}

	});
}

function toTitleCase(str)
{
    return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
//---------------------- End  custom function -----------------------------//
