function requestFullScreen() {

  var el = document.body;

  // Supports most browsers and their versions.
  var requestMethod = el.requestFullScreen || el.webkitRequestFullScreen 
  || el.mozRequestFullScreen || el.msRequestFullScreen;

  if (requestMethod) {

    // Native full screen.
    requestMethod.call(el);

  } else if (typeof window.ActiveXObject !== "undefined") {

    // Older IE.
    var wscript = new ActiveXObject("WScript.Shell");

    if (wscript !== null) {
      wscript.SendKeys("{F11}");
    }
  }
};

function addnewFocus() {
	$('#media_type').focus().fadeOut(30).fadeIn(30).fadeOut(30).fadeIn(30).fadeOut(30).fadeIn(30);
	
};

/*
function initializeCheckboxStyler() {
	$('input[type=checkbox]').checkboxpicker({
	html: true,
	offLabel: '<span class="glyphicon glyphicon-remove">',
	onLabel: '<span class="glyphicon glyphicon-ok">'
	});
};
*/

function moneyMask() {
	$('.price_fields').maskMoney();
};

function numberMask() {
	$('.dimensions').maskMoney();
	//$('.weight').maskMoney();
	//$('.weight').mask('000.00000');
};

function clearModal() {
	$('#modalPopup h4').html('Modal Header');
	$('#modalPopup p').html('Modal Message');
	$('#modalWorkArea h4').html('Modal Header');
	$('#modalWorkArea #work_area').html('Loading...');
	$('#confirmDelete .modal-body p').html('Loading...');
	$('#modalWorkArea .modal-dialog').removeClass('modal-lg');
	$('#modalWorkArea #savechangesbutton, #confirmDelete #confirm').unbind();
	$('.status_messages').html('');
};

function addMediaEntry(entryType) {
	var mediaOriginType = '';
	$('#form_add_media_'+entryType).children().css({'display':'none'});
	$.ajax({
		url: 'add_media_'+entryType+'/index',
		success: function(data) {
			$('#form_add_media_'+entryType).html(data);
			$('#form_add_media_'+entryType).children().fadeIn(300);
			if ($('#arr_origin_type').length) {
				var arrOriginType = '';
				$('#cb_origin_type input[type="checkbox"]').live('click', function() {
					arrOriginType = '';
					$('#cb_origin_type input[type="checkbox"]').each(function() {
						if ($(this).prop('checked') === true) {
							if (arrOriginType !== '') {
								arrOriginType = arrOriginType + ',';
							};
							arrOriginType = arrOriginType + $(this).attr('value');
						};
						$('#arr_origin_type').val(arrOriginType);
					});
				});
			};
			$('#submit_add_media_'+entryType).live('click', function() {
				$('#mask').fadeIn();
				$.ajax({
					type: 'POST',
					url: 'add_media_'+entryType+'/index',
					data: {
						media_entry: $('#media_'+entryType).val(),
						arr_origin_type: arrOriginType,
						mediaentry_description: $('#media'+entryType+'_description').val().replace(/\n/g, ' ')
					},
					success: function(data) {
						$('#form_add_media_'+entryType).html(data);
						$('#mask').fadeOut(200);
						$('#form_add_media_'+entryType).children().fadeIn(300);
						listMediaEntries(entryType);
					}
				});
			});
		}
	});
};

function listMediaEntries(entryType) {
	$('#table_list_media_'+entryType+'s').fadeOut(0);
	$.ajax({
		url: 'list_media_'+entryType+'s/index',
		success: function(data) {
			$('#table_list_media_'+entryType+'s').html(data);
			$('#table_list_media_'+entryType+'s').fadeIn(300);
			$('#table_list_media_'+entryType+'s a').tooltip();
		}
	});
};

function addEvent() {
	$('#form_add_event').children().css({'display':'none'});
	$.ajax({
		url: 'add_event/index',
		success: function(data) {
			$('#form_add_event').html(data);
			$('#form_add_event').children().fadeIn(300);
			$('#submit_add_event').live('click', function() {
				$('#mask').fadeIn();
				$.ajax({
					type: 'POST',
					url: 'add_event/index',
					data: {
						media_event: $('#media_event').val(),
						event_year: $('#event_year option:selected').val()
					},
					success: function(data) {
						$('#form_add_event').html(data);
						$('#mask').fadeOut(200);
						$('#form_add_event').children().fadeIn(300);
						listEvents();
					}
				});
			});
		}
	});
};

function listEvents() {
	$('#table_list_events').fadeOut(0);
	$.ajax({
		url: 'list_events/index',
		success: function(data) {
			$('#table_list_events').html(data);
			$('#table_list_events').fadeIn(300);
			$('#table_list_events a').tooltip();
		}
	});
};
function addVat(vatPercentage, context) {
	if (context !== '') {
		context = context+'_';
	};
	var thisVal = $('#'+context+'price_ex_vat').val().replace('R', '').replace(/ /g, '');
	var vatInc = parseFloat(thisVal * parseFloat('1.'+vatPercentage)).toFixed(2);
	console.log(('1.'+vatPercentage));
	$('#'+context+'price_inc_vat').val('R '+vatInc);
};
function stripVat(vatPercentage, context) {
	if (context !== '') {
		context = context+'_';
	};
	var thisVal = $('#'+context+'price_inc_vat').val().replace('R', '').replace(/ /g, '');
	var vatExcl = parseFloat(((thisVal*100) / parseInt('1'+vatPercentage))).toFixed(2);
	$('#'+context+'price_ex_vat').val('R '+vatExcl);
};

function addProduct() {
	$('#form_add_product').children().css({'display':'none'});
	$.ajax({
		url: 'add_product/index',
		success: function(data) {
			$('#form_add_product').html(data);
			$('#form_add_product').children().fadeIn(300);
			moneyMask();
			numberMask();
			$('#quantity').mask('0000000');
			var vatPercentage = $('#vat_rate').val();
			$('#price_ex_vat').bind('keyup', function() {
				addVat(vatPercentage, '');
			});
			$('#price_inc_vat').bind('keyup', function() {
				stripVat(vatPercentage, '');
			});
			var arrPhysicalMedium = '';
			$('#cb_physmed input[type="checkbox"]').live('click', function() {
				arrPhysicalMedium = '';
				$('#cb_physmed input[type="checkbox"]').each(function() {
					if ($(this).prop('checked') === true) {
						if (arrPhysicalMedium !== '') {
							arrPhysicalMedium = arrPhysicalMedium + ',';
						};
						arrPhysicalMedium = arrPhysicalMedium + $(this).attr('value');
					};
					$('#arr_phys_med').val(arrPhysicalMedium);
				});
			});
			var kidsItem = 'N';
			$('#kids_item').live('click', function() {
				if ($('#kids_item').prop('checked') === true) {
					kidsItem = 'Y';
				};
			});
			var dynamis = 'N';
			$('#dynamis_item').live('click', function() {
				if ($('#dynamis_item').prop('checked') === true) {
					dynamis = 'Y';
				};
			});
			$('#submit_add_product').live('click', function() {
				$('#mask').fadeIn();
				$.ajax({
					type: 'POST',
					url: 'add_product/index',
					data: {
						product_name: $('#product').val(),
						product_description: $('#product_description').val(),
						media_type: $('#select_media_type option:selected').val(),
						media_origin: $('#select_media_origin option:selected').val(),
						media_event: $('#select_event option:selected').val(),
						physical_medium: arrPhysicalMedium,
						reference: $('#reference').val(),
						price_ex_vat: $('#price_ex_vat').val().replace('R', '').replace(/ /g, ''),
						price_inc_vat: $('#price_inc_vat').val().replace('R', '').replace(/ /g, ''),
						width: $('#width').val(),
						height: $('#height').val(),
						depth: $('#depth').val(),
						weight: $('#weight').val(),
						kids: kidsItem,
						dynamis: dynamis, 
						external_url_text: $('#external_url_text').val(),
						external_url: $('#external_url').val(),
						quantity: $('#quantity').val()
					},
					success: function(data) {
						$('#form_add_product').html(data);
						$('#price_ex_vat').bind('keyup', function() {
							addVat(vatPercentage, '');
						});
						$('#price_inc_vat').bind('keyup', function() {
							stripVat(vatPercentage, '');
						});
						moneyMask();
						numberMask();
						$('#mask').fadeOut(200);
						if ($('#product_id').length > 0) {
						var productId = $('#product_id').html();
						$('#modalWorkAreaLabel').html('Edit Product');
						editProduct(productId, 'y');
						};
						//listProducts();
					}
				});
			});
		}
	});
};

function editProduct(thisId, isNew) {
	$.ajax({
		url: 'edit_product/index',
		data: {
			id: thisId,
			isnew: isNew
		},
		success: function(data) {
			$('#modalWorkArea #work_area').html(data);
			if (isNew === 'y') {
				$('#modalWorkArea').modal('show');
				$('#modalWorkArea .modal-dialog').addClass('modal-lg');
				$('#edit_product_form').children().fadeIn(300);
				var textAreaLength = $('#edit_product_description').val().length;
				$('#edit_product_description_length').html(textAreaLength+'/1000');
				var priceExVat = $('#display_price_ex_vat span').html();
				var vatRate = $('#edit_vat_rate').val();
				$('#display_price_inc_vat').html('R<span>'+(priceExVat * parseFloat('1.'+vatRate).toFixed(2)).toFixed(2)+'</span>');
				$('#disp_price_wrapper .display_vat_rate_label span').html(vatRate+'%');
				$('#btn_change_price').bind('click', function() {
					$('#add_new_price_popup').fadeIn(300);
				});
				$('[data-toggle="tooltip"]').tooltip();
				$('#btn_save_price').bind('click', function() {
					var existingPrice = $('#pricecompare').val();
					var newPrice = $('#new_price_ex_vat').val();
					if (existingPrice === newPrice) {
						alert('Price not changed');
					}
					else {
						$('#ajax_add_price').html('Updating...');
						$.ajax({
							url: 'add_price/index',
							data: {
								new_price_ex_vat: newPrice.replace('R', '').replace(/ /g, ''),
								product_id: $('#edit_product_id').val()
							},
							success: function(data) {
								$('#ajax_add_price').html(data);
								$('#add_new_price_popup').fadeOut(300);
								$('#pricecompare').val($('#new_price_ex_vat').val());
								if ($('#ajax_add_price').html().split('<')[0] === 'New price applied') {
									$('#display_price_ex_vat').html('R<span>'+newPrice.replace('R', '').replace(/ /g, '')+'</span>');
									$('#display_price_inc_vat').html('R<span>'+(newPrice.replace('R', '').replace(/ /g, '') * parseFloat('1.'+vatRate).toFixed(2)).toFixed(2)+'</span>');
									$('#pricelastupdated').html('Last updated: '+$('#ajax_add_price div').html());
									setTimeout(function() {
										$('#ajax_add_price div').html('');
									}, 100);
								};
							}
						});
					};
				});
				numberMask();
				moneyMask();
				$('#savechangesbutton').bind('click', function() {
					updateProduct();
				});
			};
		}
	});
};

function updateProduct() {
	var productId, productName, productDescription, mediaType, mediaOrigin, mediaEvent, arrPhysicalMedium, reference, shippingWidth, shippingHeight, shippingDepth, shippingWeight, kidsItem, dynamis, externalUrlText, externalUrl;
	arrPhysicalMedium = '';
	$('#edit_cb_physmed input[type="checkbox"]').each(function() {
		if ($(this).prop('checked') === true) {
			if (arrPhysicalMedium !== '') {
				arrPhysicalMedium = arrPhysicalMedium + ',';
			};
			arrPhysicalMedium = arrPhysicalMedium + $(this).attr('value');
		};
		$('#edit_arr_phys_med').val(arrPhysicalMedium);
	});
	kidsItem = 'N';
	if ($('#edit_kids_item').prop('checked') === true) {
		kidsItem = 'Y';
	};
	dynamis = 'N';
	if ($('#edit_dynamis_item').prop('checked') === true) {
		dynamis = 'Y';
	};
	productId = $('#edit_product_id').val();
	productName = $('#edit_product_name').val();
	productDescription = $('#edit_product_description').val();
	mediaType = $('#edit_select_media_type option:selected').val();
	mediaOrigin = $('#edit_select_media_origin option:selected').val();
	mediaEvent = $('#edit_select_media_event option:selected').val();
	shippingWidth = $('#edit_width').val();
	shippingHeight = $('#edit_height').val();
	shippingDepth = $('#edit_depth').val();
	shippingWeight = $('#edit_weight').val();
	reference = $('#edit_reference').val();
	externalUrlText = $('#edit_external_url_text').val();
	//alert(productId);
	$('#mask').fadeIn(300);
	$.ajax({
		url: 'update_product/index',
		type: 'POST',
		data: {
			isnew: 'n',
			id: productId,
			product_name: productName,
			product_description: productDescription,
			media_type: mediaType,
			media_origin: mediaOrigin,
			media_event: mediaEvent,
			physical_medium: arrPhysicalMedium,
			reference: reference, 
			shipping_width: shippingWidth,
			shipping_height: shippingHeight,
			shipping_depth: shippingDepth,
			shipping_weight: shippingWeight,
			kids_item: kidsItem,
			dynamis: dynamis
		},
		success: function(data) {
			$('#mask').fadeOut(300);
			$('#ajax_update_product').html(data);
			$('#modalWorkArea').modal('hide');
			clearModal();
			listProducts();
		}
	});
};

function deleteProduct(productId, productName) {
	$('#confirmDelete .modal-body p').html('Are you sure you want to delete <b>'+productName+'</b>?');
	$('#confirmDelete').modal('show');
	$('#confirmDelete #confirm').bind('click', function() {
		$.ajax({
			url: 'delete_product/index',
			data: {
				id: productId
			},
			success: function(data) {
				$('#pr_'+productId+' .display_status').html(data);
				$('#confirmDelete').modal('hide');
				clearModal();
				listProducts();
			}
		});
	});
};

function listProducts() {
	$('#table_list_products').fadeOut(0);
	$.ajax({
		url: 'list_products/index',
		success: function(data) {
			$('#table_list_products').html(data);
			$('#table_list_products').fadeIn(300);
			$('#table_list_products a').tooltip();
		}
	});
};

function editQuantity(productId, productName) {
	$('#modalWorkAreaLabel').html(productName);
	$('#modalWorkArea').modal('show');
	$.ajax({
		url: 'list_quantities',
		data: {
			product_id: productId
		},
		success: function(data) {
			$('#modalWorkArea .modal-body').html(data);
			$('#modalWorkArea #form_quantity #quantity').mask('0000000');
			$('#modalWorkArea #form_quantity #quantity').bind('focus', function() {
				$('#modalWorkArea #quantity_error').html('');	
			});
			$('#modalWorkArea #savechangesbutton').bind('click', function() {
				var quantity = parseInt($('#modalWorkArea #form_quantity #quantity').val());
				if (isNaN(quantity)) {
					//$('#modalWorkArea #quantity_error').html('Please enter a valid quantity');
					$('[data-toggle="popover"]').popover({placement:'top'});
					$('[data-toggle="popover"]').popover('show');
					$('#modalWorkArea #form_quantity').bind('click', function() {
						$('[data-toggle="popover"]').popover('hide');	
					});
					$('#modalWorkArea #form_quantity #quantity').bind('focus', function() {
						$('[data-toggle="popover"]').popover('hide');
					});
				}
				else {
					$.ajax({
						url: 'update_quantity',
						data: {
							product_id: productId,
							quantity: quantity, 
							transaction_type: '3'
						},
						success: function(data) {
							$('#modalWorkArea #form_quantity #ajax_update_quantity').html(data);
							if (data === 'updated') {
								$('#modalWorkArea').modal('hide');
								clearModal();
								setTimeout(function() {
									$('#modalPopup h4').html('Updated');
									$('#modalPopup .modal-body p').html('Quantity updated successfully');
									$('#modalPopup').modal('show');
								}, 300);
								listProducts();
							};
						}
					});
				};
			});
		}
	});
};

function listOrders() {
	$('#table_list_orders').fadeOut(0);
	$.ajax({
		url: 'list_orders/index',
		success: function(data) {
			$('#table_list_orders').html(data);
			$('#table_list_orders').fadeIn(300);
			$('#table_list_orders a').tooltip();
		}
	});
};

function listCustomers() {
	$('#table_list_customers').fadeOut(0);	
	$.ajax({
		url: 'list_customers/index',
		success: function(data) {
			$('#table_list_customers').html(data).fadeIn(300);
			$('#table_list_customers a').tooltip();
		}
	});
};

function alertOrders() {
	$.ajax({
		url: 'alert_orders',
		success: function(data) {
			$('#alert_new_order').html(data);	
		}
	});	
};

function alertUsers() {
	$.ajax({
		url: 'alert_users',
		success: function(data) {
			$('#alert_new_user').html(data);	
		}
	});	
};

function insertLatestLinesBefore(latestId) {
	$.ajax({
		url: 'insert_latest_orders',
		data: {
			latest_id: parseInt(latestId)	
		},
		success: function(data) {
			if (data.length > 0) {
				$(data).insertBefore('#or_'+('000000'+latestId).slice(-6));
				var latestInserted = $('#latest_inserted').val();
				$('#latest_id').val(latestInserted);
				var oldCount = parseInt($('#order_rowcount_value').val());
				$('#order_rowcount_value').val(oldCount + 1)
			};
		}
	});
};

function showNewUsers() {
	$('#modalWorkAreaLabel').html('Users just registered');
	$('#modalWorkArea #savechangesbutton').bind('click', function() {
		alert('No changes were made');	
	});
	$.ajax({
		url: 'show_new_users',
		success: function(data) {
			$('#modalWorkArea #work_area').html(data);
			$('#alert_new_user').html('');
			$('#modalWorkArea').modal('show');
		}
	});
};

$(document).ready(function() {
	
	var windowWidth = parseInt($(window).width());
	var windowHeight = parseInt($(window).height());	
	
	$('[data-toggle="tooltip"]').tooltip();
	
	$.ajaxSetup({cache:false});
	
	//Make later versions of jQuery compatible with ().live
	jQuery.fn.extend({
		live: function (event, callback) {
		   if (this.selector) {
				jQuery(document).on(event, this.selector, callback);
			}
		}
	});

	$('#menu_shipping_vat ul li a').bind('click', function() {
		var thisId = $(this).attr('id');	
		switch(thisId) {
			case 'shipping_link':
				$('#modalWorkAreaLabel').html('Shipping Rates');
				$('#modalWorkArea #work_area').html('Loading...');
				$('#modal_ajax_actions').fadeIn(200);
				$.ajax({
					url: 'add_shipping_rate/index',
					data: {
						isnew: 'y'
					},
					success: function(data) {
						$('#modalWorkArea #work_area').html(data);
						$('#modal_ajax_actions').fadeOut(200);
						$('#savechangesbutton').bind('click', function() {
							if (parseFloat($('#first_kg').val().replace('R', '').replace(/ /g, '')).toFixed(2) !== '0.00' && !(isNaN(parseFloat($('#first_kg').val().replace('R', '').replace(/ /g, '')).toFixed(2))) && parseFloat($('#per_additional_kg').val().replace('R', '').replace(/ /g, '')).toFixed(2) !== '0.00' && !(isNaN(parseFloat($('#per_additional_kg').val().replace('R', '').replace(/ /g, '')).toFixed(2)))) {
								$('#modal_ajax_actions').fadeIn(200);
								$.ajax({
									type: 'POST',
									url: 'add_shipping_rate/index',
									data: {
										isnew: 'n', 
										first_kg: $('#first_kg').val().replace('R', '').replace(/ /g, ''),
										per_additional_kg: $('#per_additional_kg').val().replace('R', '').replace(/ /g, '')
									},
									success: function(data) {
										$('#modal_ajax_actions').fadeOut(200);
										$('#modalWorkArea #work_area').html(data);
										$('#first_kg, #per_additional_kg').maskMoney();
										$('#form_add_shipping_rate_per_kg').after('<div style="color:#26b99a;">Shipping rate updated and effective immediately</div>');
									}
								});
							}
							else {
								alert('Zero value not allowed!');	
							};
						});
						$('#modalWorkArea').modal('show');
						$('#first_kg, #per_additional_kg').maskMoney();
					}
				});
				break;
			case 'vat_link':
				break;
		};
	});

	$('#modalPopup button, .modal-backdrop, #modalWorkArea .close, #modalWorkArea #closebutton, #confirmDelete #canceldelete, #confirmDelete .close').bind('click', function() {
		setTimeout(clearModal, 600);
	});

	$('#add_new_price_popup .close').live('click', function() {
		$('#add_new_price_popup').fadeOut(300);
	});

	$('#media_type, #media_origin, #media_event, #edit_media_type, #edit_media_origin, #edit_media_event').live('keypress', function (e) {
		var regex = new RegExp('^[a-zA-Z0-9_ ]+$');
		var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
		if (regex.test(str)) {
			return true;
		}
		e.preventDefault();
		return false;
	});

	var pageId = $('#page_id').html();
	switch(pageId) {
		case 'media_types':
			addMediaEntry('type');
			listMediaEntries('type');
			break;
		case 'media_origins':
			addMediaEntry('origin');
			listMediaEntries('origin');
			break;
		case 'events':
			addEvent();
			listEvents();
			break;
		case 'products':
			addProduct();
			listProducts();
			break;
		case 'orders':
			listOrders();
			break;
		case 'customers':
			listCustomers();
			break;
	};
	
	$('#mediatype_description[maxlength], #edit_mediatype_description[maxlength], #mediaorigin_description[maxlength], #edit_mediaorigin_description[maxlength], #product_description[maxlength], #edit_product_description[maxlength]').live('keyup input paste', function() {
		var thisId = $(this).attr('id');
		var limit = parseInt($(this).attr('maxlength'));
		var text = $(this).val();
		var chars = text.length;
		if (chars > limit) {
			$(this).val(new_text);
		};
		$('#'+thisId+'_length').html(chars+'/'+limit);
		if (limit - chars <= 15) {
			$('#'+thisId+'_length').addClass('errors');
		}
		else {
			$('#'+thisId+'_length').removeClass('errors');
		};
	});
	
	var liPos = '';
	$('#table_list_media_types tr td li, #table_list_media_origins tr td li, #table_list_events tr td li').live('click', function() {
		var context = $(this).parents().eq(3).attr('id');
		var contextUrl, modalh4, entryType;
		var thisId = $(this).parents().eq(2).attr('id');
		liPos = $(this).index();
		switch(liPos) {
			case 0:
				switch(context) {
					case 'table_list_media_types':
					contextUrl = 'change_media_type_state';
					modalh4 = 'Media Type Status';
					entryType = 'type';
					break;
				case 'table_list_media_origins':
					contextUrl = 'change_media_origin_state';
					modalh4 = 'Media Origin Status';
					entryType = 'origin';
				break;
				case 'table_list_events':
					contextUrl = 'change_event_state';
					modalh4 = 'Media Event Status';
					entryType = 'event';
				break;
				case 'table_list_producs':
					contextUrl = 'change_product_state';
					modalh4 = 'Product Status';
					entryType = 'product';
				break;
				};
				
				var action = $(this).children('a').attr('data-original-title').replace('Click\u00a0to\u00a0', '');
				var modalMessage;
				if (action === 'show') {
					modalMessage = 'DISPLAYED';
				}
				else {
					modalMessage = 'HIDDEN';
				};
				$(this).children('a').children('i').removeClass().addClass('fa fa-cog fa-spin trans_bg');
				$.ajax({
					url: contextUrl+'/index',
					data: {
						id: thisId,
						state: action
					},
					success: function(data) {
						$('#'+thisId+' .display_status').html(data);
						$('#modalPopup h4').html(modalh4);
						$('#modalPopup .modal-body p').html('Media '+entryType+' '+modalMessage);
						$('#modalPopup').modal('show');
						if (modalMessage === 'DISPLAYED') {
							$('#'+thisId+' td ul li:nth-child(1) a i').removeClass('fa fa-cog fa-spin trans_bg').addClass('fa fa-eye').parent().attr({'title':'Click\u00a0to\u00a0hide', 'data-original-title':'Click\u00a0to\u00a0hide'});
						};
						if (modalMessage === 'HIDDEN') {
							$('#'+thisId+' td ul li:nth-child(1) a i').removeClass('fa fa-cog fa-spin trans_bg').addClass('fa fa-eye-slash').parent().attr({'title':'Click\u00a0to\u00a0show', 'data-original-title':'Click\u00a0to\u00a0show'});
						};
					}
				});
				break;
			case 2:
				var textAreaId;
				var textInputId;
				var originType;
				switch(context) {
					case 'table_list_media_types':
					contextUrl = 'edit_media_type';
					modalh4 = 'Media Type';
					entryType = 'type';
					textAreaId = 'edit_mediatype_description';
					textInputId = 'edit_media_type';
					break;
				case 'table_list_media_origins':
					contextUrl = 'edit_media_origin';
					modalh4 = 'Media Origin';
					entryType = 'origin';
					textAreaId = 'edit_mediaorigin_description';
					textInputId = 'edit_media_origin';
					break;
				case 'table_list_events':
					contextUrl = 'edit_event';
					modalh4 = 'Media Event';
					break;
				};
				
				$('#modalWorkArea h4').html(modalh4);
				$('#modalWorkArea').modal('show');
				
				if (contextUrl !== 'edit_event') {
					$.ajax({
						url: contextUrl+'/index',
						data: {
							id: thisId,
							isnew: 'y'
						},
						success: function(data) {
							$('#work_area').html(data);
							var textAreaLength = $('#'+textAreaId).val().length;
							$('#'+textAreaId+'_length').html(textAreaLength+'/255');
							
							if ($('#edit_arr_origin_type').length) {
								var arrOriginType = '';
								$('#edit_cb_origin_type input[type="checkbox"]').live('click', function() {
									arrOriginType = '';
									$('#edit_cb_origin_type input[type="checkbox"]').each(function() {
										if ($(this).prop('checked') === true) {
											if (arrOriginType !== '') {
												arrOriginType = arrOriginType + ',';
											};
											arrOriginType = arrOriginType + $(this).attr('value');
										};
										$('#edit_arr_origin_type').val(arrOriginType);
									});
								});
							};
			
							$('#savechangesbutton').bind('click', function() {
								$('#modal_ajax_actions').fadeIn(300);
								var mediaEntry = $('#'+textInputId).val();
								var mediaEntryDesc = $('#'+textAreaId).val();
								var arrOriginType;
								if ($('#edit_arr_origin_type').length) {
									arrOriginType = $('#edit_arr_origin_type').val();
								};
								$.ajax({
									url: contextUrl+'/index',
									data: {
										id: thisId,
										isnew: 'n',
										media_entry: $('#'+textInputId).val(),
										arr_origin_type: arrOriginType,
										media_description: $('#'+textAreaId).val()
									},
									success: function(data) {
										$('#work_area').html(data);
										$('#modal_ajax_actions').fadeOut(100);
										textAreaLength = $('#'+textAreaId).val().length;
										$('#'+textAreaId+'_length').html(textAreaLength+'/255');
										listMediaEntries(entryType);
									}
								});
							});
						}
					});
				}
				else {
					$.ajax({
						url: contextUrl+'/index',
						data: {
							id: thisId,
							isnew: 'y'
						},
						success: function(data) {
							$('#work_area').html(data);
							$('#savechangesbutton').bind('click', function() {
								$('#modal_ajax_actions').fadeIn(300);
								$.ajax({
									url: contextUrl+'/index',
									data: {
										id: thisId,
										isnew: 'n',
										media_event: $('#edit_event_name').val(),
										event_year: $('#edit_event_year option:selected').val()
									},
									success: function(data) {
										$('#work_area').html(data);
										$('#modal_ajax_actions').fadeOut(100);
										listEvents();
									}
								});
							});
						}
					});
				};
				break;
			case 3:
				switch(context) {
					case 'table_list_media_types':
						entryType = 'type';
						break;
					case 'table_list_media_origins':
						entryType = 'origin';
						break;
					case 'table_list_events':
						entryType = 'event';
						break;
				};
				var recordName = $('#me_'+thisId.split('_')[1]).html();
				$('#confirmDelete .modal-body p').html('Are you sure you want to delete <b>'+recordName+'</b>?');
				$('#confirmDelete #confirm').bind('click', function() {
					if (entryType !== 'event') {
						$.ajax({
							url: 'delete_media_entry/index',
							data: {
								id: thisId,
								entry_type: entryType
							},
							success: function(data) {
								$('#'+thisId+' .display_status').html(data);
								if ($('#'+thisId+' .display_status').html() === 'Fail') {
									$('#modalPopup h4').html('Deletion Error!');
									$('#modalPopup .modal-body p').html('Linked products exist');
									$('#confirmDelete').modal('hide');
									$('#modalPopup').modal('show');
								}
								else {
									listMediaEntries(entryType);
									$('#confirmDelete').modal('hide');
									modalClear();
								};
							}
						});
					}
					else {
						$.ajax({
							url: 'delete_event/index',
							data: {
								id: thisId
							},
							success: function(data) {
								$('#'+thisId+' .display_status').html(data);
								if ($('#'+thisId+' .display_status').html() === 'Fail') {
									$('#modalPopup h4').html('Deletion Error!');
									$('#modalPopup .modal-body p').html('Linked products exist');
									$('#confirmDelete').modal('hide');
									$('#modalPopup').modal('show');
								}
								else {
									listEvents();
									$('#confirmDelete').modal('hide');
									modalClear();
								};
							}
						});
					};
				});
				$('#confirmDelete').modal('show');
				break;
		};
	});
	
	$('#table_list_products tr td li').live('click', function() {
		liPos = '';
		var productId = $(this).parents().eq(2).attr('id').replace('pr_', '');
		var productName = $(this).parents().eq(2).children('td').html();
		var modalh4 = 'Product Status';
		liPos = $(this).index();
		switch(liPos) {
			case 0:
				var action = $(this).children('a').attr('data-original-title').replace('Click\u00a0to\u00a0', '');
				var modalMessage;
				if (action === 'show') {
					modalMessage = 'DISPLAYED';
				}
				else {
					modalMessage = 'HIDDEN';
				};
				$(this).children('a').children('i').removeClass().addClass('fa fa-cog fa-spin trans_bg');
				$.ajax({
					url: 'change_product_state/index',
					data: {
						id: productId,
						state: action
					},
					success: function(data) {
						$('#'+productId+' .display_status').html(data);
						$('#modalPopup h4').html(modalh4);
						$('#modalPopup .modal-body p').html('Product '+modalMessage);
						$('#modalPopup').modal('show');
						if (modalMessage === 'DISPLAYED') {
							$('#pr_'+productId+' td ul li:nth-child(1) a i').removeClass('fa fa-cog fa-spin trans_bg').addClass('fa fa-eye').parent().attr({'title':'Click\u00a0to\u00a0hide', 'data-original-title':'Click\u00a0to\u00a0hide'});
						};
						if (modalMessage === 'HIDDEN') {
							$('#pr_'+productId+' td ul li:nth-child(1) a i').removeClass('fa fa-cog fa-spin trans_bg').addClass('fa fa-eye-slash').parent().attr({'title':'Click\u00a0to\u00a0show', 'data-original-title':'Click\u00a0to\u00a0show'});
						};
					}
				});
				break;
			case 1:
				editQuantity(productId, productName);
				break;
			case 2:
				$('#modalWorkAreaLabel').html('Edit Product');
				editProduct(productId, 'y');
				break;
			case 3:
				deleteProduct(productId, productName);
				break;	
		};
	});
	
	$('#saveimagebutton').bind('click', function() {
		if (!($(this).hasClass('disabled'))) {
			$.ajax({
				url: 'crop_image/index',
				data: {
					x1: $('#x1').val(),
					y1: $('#y1').val(),
					x2: $('#x2').val() - $('#x1').val(),
					y2: $('#y2').val() - $('#y1').val(),
					image_name: $('#working_image').attr('src').replace('public/media/product_images/woking_image_', '').replace('.jpg', '')
				},
				success: function(data) {
					$('#image_ajax_actions').html(data);
					if ($('#img_proc_msg').length) {
						if ($('#img_proc_msg').html() === 'Success') {
							$('.imgareaselect-outer').addClass('zero_index');
							$('.imgareaselect-selection').parent().addClass('zero_index');
							$('#working_image').attr('src', 'public/media/img/work_area_bg.gif');
							$('#x1, #y1, #x2, #y2').val('');
							$('#modalImageProcess').modal('hide');
							$('#image_upload_frame').attr('src', 'image_upload?guid='+$('#edit_guid').val().toLowerCase().replace('{', '').replace('}', ''));
						};
					};
					
				}
			});
		};
	});
	
	$('#mask i').removeClass('fa-cog');
	$('#mask i').css({'top':(windowHeight/2)-100+'px'});
	setTimeout(function() {
		$('#mask i').addClass('fa-cog');
	}, 200);
	
	$('.state_change').live('change', function() {
		var orderId = $(this).attr('id').split('_')[1];
		if ($('#os_'+orderId+' option:selected').val() === $('#cs_'+orderId).val()) {
			$('#osbtn_'+orderId).addClass('disabled').unbind();
		}
		else {
			$('#osbtn_'+orderId).show();
			$('#osbtn_'+orderId).removeClass('disabled').bind('click', function() {
				$('#mask').fadeIn();
				var stateId = $('#os_'+orderId+' option:selected').val();
				$.ajax({
					url: 'change_order_state',
					data: {
						order_id: parseInt(orderId),
						state_id: stateId
					},
					success: function(data) {
						$('#mask').fadeOut();
						$('#ajax_state_change_'+orderId).html(data);
						if (data === parseInt(stateId)+'_success') {
							$('#osbtn_'+orderId).addClass('disabled').unbind();
							$('#cs_'+orderId).val(parseInt(stateId));
							$('#os_'+orderId+' option').each(function() {
								if ($(this).val() === stateId) {
									$(this).attr('selected', true);
								}
								else {
									$(this).attr('selected', false);
								};
							});
							$('#or_'+orderId).removeClass('bold pitch_black');
							alertOrders();
						};
					}
				});	
			});
		};
	});
	
	$('.vo_lnk').live('click', function() {
		var thisId = $(this).attr('id');
		var orderId = parseInt(thisId.split('_')[1]);
		$('#modalWorkAreaLabel').html('View Order');
		$.ajax({
			url: 'view_order_details',
			data: {
				order_id: orderId
			},
			success: function(data) {
				$('#modalWorkArea #work_area').html(data);
				$('#modalWorkArea #work_area .state_history:last-child').addClass('green');
				var paddedId = $('#vo_order_id').val();
				var created = $('#vo_created').val();
				var price = $('#vo_price').val();
				var customerName = $('#vo_customer_name').val();
				var email = $('#vo_email').val();
				var phone = $('#vo_phone').val();
				$('#modalWorkAreaLabel').html('Order #'+paddedId+' created '+created);
				$('#modalWorkArea #savechangesbutton').bind('click', function () {
					alert('No changes were made.');
				});
				$('#modalWorkArea').modal('show');
				$('#or_'+paddedId).removeClass('bold pitch_black');
				alertOrders();
			}
		});
	});
	
	$('#table_list_customers .login_allowed').live('click', function() {
		var customerId = $(this).attr('id').split('_')[1];
		loginAllowed = 'Y';
		if ($(this).prop('checked') === true) {
			loginAllowed = 'Y';
		}
		else {
			loginAllowed = 'N';
		};
		if (loginAllowed !== 'Y' && loginAllowed !== 'N') {
			loginAllowed = 'Y';
		};
		$('#mask').fadeIn(300);
		$.ajax({
			url: 'change_login_ability',
			data: {
				customer_id: customerId,
				login_allowed: loginAllowed	
			},
			success: function(data) {
				$('#ajax_login_allow_'+customerId).html(data);
				$('#mask').fadeOut(300);	
			}
		});
	});
	
	$('#table_list_customers tr td li').live('click', function() {
		var liPos = '';
		liPos = $(this).index();
		var customerId = $(this).parents().eq(2).attr('id').replace('cu_', '');
		var customerName = $(this).parents().eq(2).children('td').html();
		switch(liPos) {
			case 0:
				$('#modalWorkAreaLabel').html('Order History');
				$.ajax({
					url: 'customer_order_history',
					data: {
						customer_id: customerId	
					},
					success: function(data) {
						$('#modalWorkArea #work_area').html(data);
						var customerName = $('#h_customer_name').val();
						$('#modalWorkAreaLabel').html(customerName);
						$('#modalWorkArea #savechangesbutton').bind('click', function () {
							alert('No changes were made.');
						});
						$('#customer_phone').mask('000 000 0000');
						$('#modalWorkArea .customer_orders').bind('click', function() {
							lineId = $(this).attr('id')
							orderId = parseInt(lineId.split('_')[1]);
							var orderNumberCellContent;
							$('.customer_order_lines').remove();
							$('.customer_orders').removeClass('bold green');
							$('.co_id_cells').each(function() {
								orderNumberCellContent = $(this).html();
								$(this).html(orderNumberCellContent.replace('<br /><i class="fa fa-chevron-down green" aria-hidden="true"></i>', '').replace('<br><i class="fa fa-chevron-down green" aria-hidden="true"></i>', ''));
							});
							setTimeout(function() {
								$('#'+lineId).addClass('bold green');
								$('#co_id_'+orderId).append('<br /><i class="fa fa-chevron-down green" aria-hidden="true"></i>');
								$('<tr class="customer_order_lines" style="background:#f5f5f5;"><td colspan="5" id="ajax_customer_order_lines_'+orderId+'"></td></tr>').insertAfter('#'+lineId);
								$('#mask').fadeIn(300);
								$.ajax({
									url: 'customer_order_lines',
									data: {
										order_id: orderId	
									},
									success: function(data) {
										$('#mask').fadeOut(300);
										$('#ajax_customer_order_lines_'+orderId).html(data);
										$('#close_'+orderId).bind('click', function() {
											$('.customer_order_lines').remove();
											$('.customer_orders').removeClass('bold green');
											$('.co_id_cells').each(function() {
												orderNumberCellContent = $(this).html();
												$(this).html(orderNumberCellContent.replace('<br /><i class="fa fa-chevron-down green" aria-hidden="true"></i>', '').replace('<br><i class="fa fa-chevron-down green" aria-hidden="true"></i>', ''));
											});
										});	
									}
								});
							}, 200);
						});
						$('#modalWorkArea').modal('show');
					}
				});
				break;
			case 1:
				$('#modalWorkAreaLabel').html('View Customer Details');
				$.ajax({
					url: 'view_customer_details',
					data: {
						customer_id: customerId	
					},
					success: function(data) {
						$('#modalWorkArea #work_area').html(data);
						var customerName = $('#h_customer_name').val();
						$('#modalWorkAreaLabel').html(customerName);
						$('#modalWorkArea #savechangesbutton').bind('click', function () {
							alert('No changes were made.');
						});
						$('#customer_phone').mask('000 000 0000');
						$('#modalWorkArea').modal('show');
					}
				});
				break;
		};
	});

	alertOrders();	
	
	setInterval(alertOrders, 15 * 1000);
	
	setInterval(function() {
		var latestId = $('#latest_id').val();
		insertLatestLinesBefore(latestId);	
	}, 15 * 1000);
	
	alertUsers();
	setInterval(alertUsers, 15 * 1000);
	
	$('#show_new_users').bind('click', function() {
		showNewUsers();	
	});
});

