
var fsData, pkgTable, sysTable, pkgSystems, coverDetails;
var pkgSystems = new Array();

$(function() {
	setupStuff();

	// all the system and product info
	$.getJSON("js/fsData.json", function(d) {
		fsData = d;
		setupCategoriesSelectBox();
	});

	$.ajaxSetup({ cache: false });

	$.getJSON("?a=getMyDetails", function(d) {
		coverDetails = d.cover;
		pkgSystems   = d.systems;

		$.each(keys(d.cover), function(i, cField) {
			if (d.cover[cField]) 
				$("#c" + cField).val(d.cover[cField]);
		});

		updatePkgTable();
	});
	

	// initialize our flexigrids
    $("#sysTable").flexigrid({
        dataType: 'json',
        colModel: [
            { display:'',                 name:'actions',          width:70,  sortable:false, align:'left' },
            { display:'System',           name:'system',           width:70,  sortable:true, align:'left' },
            { display:'Description',      name:'description',      width:550, sortable:true, align:'left' },
            { display:'Rating',           name:'rating',           width:70,  sortable:true, align:'left' },
            { display:'Product',          name:'product',          width:100, sortable:true, align:'left' }
        ],
        sortname: "system",
        sortorder: "asc",
        singleSelect: true,
        height: 'auto',
        width: 'auto',
        rp: 1000,
        resizeable: false,
		nowrap: false,
		onChangeSort: function(name, order) { sortGrid("#sysTable", order); }
    }); 

    $("#pkgTable").flexigrid({
        dataType: 'json',
        colModel: [
            { display:'',                 name:'actions',          width:70,  sortable:false, align:'left' },
            { display:'System',           name:'system',           width:70,  sortable:true, align:'left' },
            { display:'Description',      name:'description',      width:550, sortable:true, align:'left' },
            { display:'Rating',           name:'rating',           width:70,  sortable:true, align:'left' },
            { display:'Product',          name:'product',          width:100, sortable:true, align:'left' }
        ],
        sortname: "system",
        sortorder: "asc",
        singleSelect: true,
        height: 'auto',
        width: 'auto',
        rp: 1000,
        resizeable: true,
		onChangeSort: function(name, order) { sortGrid("#pkgTable", order); }
    }); 



	//
	// remove a system from the package
	//
	$(".remSystem").live('click', function() {
		var sysNum = $(this).attr('id').replace('pkg_', '');
		var pos = $.inArray(sysNum, pkgSystems);		
		if (pos >= 0) 
			pkgSystems.splice(pos, 1);

		$("#sys_" + sysNum).attr("src", "icons/add.png");

		updatePkgTable();

		$.getJSON("?a=remSystem&system=" + sysNum, function(){});
	});


	//
	// add a system to the package
	//
	$(".addSystem").live('click', function() {
		var sysNum = $(this).attr('id').replace('sys_', '');
		if ($.inArray(sysNum, pkgSystems) >= 0)	return;
		pkgSystems.push(sysNum);

		$("#sys_" + sysNum).attr("src", "icons/tick.png");

		updatePkgTable();

		$.getJSON("?a=addSystem&system=" + sysNum, function(){});
	});


	// make the pdf package
	$("#makePackage").click(function() {
		window.location = 'http://flamesafe.rectorseal.com/sub/?a=makePackage';
	});


});


function remAllSystems() {
	$.each(pkgSystems, function(i, sysNum) {
		$("#sys_" + sysNum).attr("src", "icons/add.png");
	});

	pkgSystems = new Array();
	updatePkgTable();
	$.getJSON("?a=remAllSystems", function(){});
}


function keys(o) { var keys = []; for (var key in o) keys.push(key); return keys; }

function setupCategoriesSelectBox() {
	$.each( keys(fsData.categories).sort(), function(i, key) {
		$("#catSelect").addOption(key, fsData.categories[key]);
	});

	//updateSysTable( keys(fsData.systems) );

	$("#catSelect").change(function() {
		var curCat = $(this).selectedValues()[0];
		if (curCat == "") return;

		updateSysTable( systemsInCategory(curCat) );
	});

}



//
// replaces sysTable with the systems given
//
function updateSysTable(systems) {

	var newData = new Array();
	$.each(systems, function(i, sysNum) {
		var s = fsData.systems[sysNum];
		var actions = "<img src='icons/add.png' class='addSystem' id='sys_"+ sysNum +"' />&nbsp;&nbsp;&nbsp;";
		actions    += "<a href='systems/"+ sysNum.toLowerCase() +".pdf'><img src='icons/page.png' /></a>";
	
		newData.push({ 
			id:   s.number,
			cell: [ actions, s.number, s.description, s.rating, s.products.join(", ") ]
		});
	});

	$("#sysTable").flexAddData({ rows: newData });
	sortGrid("#sysTable", "asc");

	// highlight all the systems already in the package
	$.each( $("#sysTable").find("tbody > tr").get(), function(i, tr) {
		var sysNum = $(tr).attr("id").replace("row", "");
		if ($.inArray(sysNum, pkgSystems) >= 0) {
			$("#sys_" + sysNum).attr("src", "icons/tick.png");
			// the background isn't changing to the even rows which get a different color
			//$(tr).css("background-color", "#ecffeb");
			//$(tr).toggleClass("trUsing");
		}
	});


} // updateSysTable()



function updatePkgTable() {

    var newData = new Array();
    $.each(pkgSystems, function(i, sysNum) {
        var s = fsData.systems[sysNum];
        var actions = "<img src='icons/delete.png' class='remSystem' id='pkg_"+ sysNum +"' />&nbsp;&nbsp;&nbsp;";
        actions    += "<a href='systems/"+ sysNum.toLowerCase() +".pdf'><img src='icons/page.png' /></a>";

        newData.push({
            id:   s.number,
            cell: [ actions, s.number, s.description, s.rating, s.products.join(", ") ]
        });
    });

	$("#pkgTable").flexAddData({ rows: newData });
	sortGrid("#pkgTable", "asc");

}





//
// returns an array of all systems for the given category
//
function systemsInCategory(cat) {
	var systems = new Array();

	$.each(fsData.systems, function(sysNum, sysData) {
		if (sysData.category == cat)
			systems.push(sysNum);
	});

	return systems;
}








//////////////////////////////////////////////////////////////////////////////////////////////////////////////





function setupStuff() {
	// Fix IE z-index

		/*var zIndexNumber = 1000;
		$('div').each(function() {
			$(this).css('zIndex', zIndexNumber);
			zIndexNumber -= 10;
		});*/
		
	// Push footer down
	
		$('#container').append('<div id="push" />');

	// Custom <select>
	
		$('select').wrap('<div class="my-skinnable-select" />');
	
		$(document).ready(function() {
    		$('.my-skinnable-select').each(function(i) {
        		selectContainer = $(this);
        	    selectContainer.removeClass('my-skinnable-select');
		        selectContainer.addClass('skinned-select');
		        selectContainer.children().before('<div class="select-text">a</div>').each(function() {
		        	for (var i = 0; i < this.options.length; i++) {
		        		if(this.options[i].selected == true) {
		        			$(this).prev().text(this.options[i].innerHTML);
		        		}
		        	}
          		});
        	
	        	var parentTextObj = selectContainer.children().prev();
	    	    selectContainer.children().click(function() {
		        	parentTextObj.text(this.options[this.selectedIndex].innerHTML);
				})
			});
  		});
  		
/*
  	// Text inside textfield
  		var active_color = '#000'; // Color of user provided text
		var inactive_color = '#969696'; // Color of default text
	
		$('input[type="text"], input[type="password"]').each(function() {
			var value = $(this).parent().children('label').html();

			if($(this).attr("value") == "") {
				$(this).attr("value", value);
				$(this).css("color", inactive_color);
			}
		});
  	
  		var default_values = new Array();
  		
  		$('input[type="text"], input[type="password"]').focus(function() {
    		if (!default_values[this.id]) {
      			default_values[this.id] = this.value;
    		}
    		if (this.value == default_values[this.id]) {
      			this.value = '';
      			this.style.color = active_color;
    		}
    		
    		$(this).blur(function() {
      			if (this.value == '') {
        			this.style.color = inactive_color;
        			this.value = default_values[this.id];
      			}
    		});
  		});
*/

	// Modal box
	
		jQuery.fn.fadeToggle = function(speed, easing, callback) { // Custom fade toggle function
   			return this.animate({opacity: 'toggle'}, speed, easing, callback); 
		}; 
		
		$('a[rel="modal"]').each(function() {
			var id = $(this).attr("href");
			var modalbox = $(id).html();
			$(this).wrap('<div class="modal" />');
			$(this).parent().append(modalbox);
			$(id).remove();
		});
		
		$('a[rel="modal"]').click(function() {
			$('.modalbox').fadeOut(200);
			$(this).parent().children('.modalbox').fadeToggle(200);
			$('#overlay').show();
			return false;
		});
		
		$('body').append('<div id="overlay" />'); // Add overlay to DOM
	
		$('#overlay').click(function() { // When the overlay is clicked the mailbox will disappear
			$('#overlay').hide();
			$('.modalbox').fadeOut(200);
		});
	

	// Navigation tabs with smooth transitions:
	
		$('#main-nav > li > ul').hide(); // Hide all subnavigation
		$('#main-nav > li > a.current').parent().children("ul").show(); // Show current subnavigation	
			
		$('#main-nav > li > a[href="#"]').click( // Click!
			function() {
				$(this).parent().siblings().children("a").removeClass('current'); // Remove .current class from all tabs
				$(this).addClass('current'); // Add class .current
				$(this).parent().siblings().children("ul").fadeOut(150); // Hide all subnavigation
				$(this).parent().children("ul").fadeIn(150); // Show current subnavigation
				return false;
			}
		);
		
	// Subtitle fix
	
		var subtitle = $('#content > h2');
		$('#header').append(subtitle);
		$('#content > h2').remove();
	
	// Content tabs:
		
		$('.content-box-header ul li:first-child a').addClass('current'); // Add .current to the first class
		$('.content-box .tab-content').hide(); // Hide all .tab-content divs
		$('.content-box .tab-content:first-child').show(); // Show default tabs
	
		$('.content-box-header ul li a').click(function() {
			$(this).parent().siblings().find("a").removeClass('current'); // Remove .current from all tabs
			$(this).addClass('current'); // Set tab to current
			var tabcontent = $(this).attr('href'); // Get link to requested tab
			$(tabcontent).siblings().hide(); // Hide all other .tab-content divs
			$(tabcontent).show(); // Show content div
			return false;
		});
		
		
	// Check-all
	
/*
		$('thead th input[type="checkbox"]').click(function() { // Click a checkbox that's in the <thead>
			$(this).parent().parent().parent().parent().find("input[type='checkbox']").attr('checked', $(this).is(':checked')); // Find all checkboxes and check them if needed
		});
*/
		
	// Tooltip-confirmation
	
		$('.confirmation').wrap('<div class="confirm" />');
	
		$('.confirm > a').click(function() {
			$('.tooltip').fadeOut(200, function() { // Remove all tooltips
				$(this).remove();
			});
			var link = $(this).parent().children("a").attr('href'); // Get the requested link
			$(this).parent().append('<div class="tooltip"><p>Are you sure?</p><a href="' + link + '">Yes</a> | <a href="#" class="close">No</a></div>'); // Adding the tooltip to the DOM
			
			$('.close').click(function() { // Closing the tooltip
				$('.tooltip').fadeOut(200, function() {
					$(this).remove();
				});
				return false;
			});

			$(this).parent().children('.tooltip').fadeIn(200);
			return false; // Make sure it doesn't follow the link immediately
		});
	


	// Collapse content boxes:
/*	
		$('.content-box-header h3').click(function() {
			if($(this).parent().parent().hasClass('closed')) {
				$(this).parent().parent().children('.content-box-content').show();
				$(this).parent().parent().removeClass('closed');
			} else {
				$(this).parent().parent().children('.content-box-content').hide();
				$(this).parent().parent().addClass('closed');
			}
		});
*/

	// Close notifications:
	
		$('div.notification').click(function() {
			$(this).fadeOut(200, function() {
				$(this).hide();
			});
		});
		
} // setupStuff




function sortGrid(table, order) {
	// Remove all characters in c from s.
	var stripChar = function(s, c) {
		var r = "";
		for(var i = 0; i < s.length; i++) {
			r += c.indexOf(s.charAt(i))>=0 ? "" : s.charAt(i);
		}
		return r;
	}

	// Test for characters accepted in numeric values.
	var isNumeric = function(s) {
		var valid = "0123456789.,- ";
		var result = true;
		var c;
		for(var i = 0; i < s.length && result; i++) {
			c= s.charAt(i);
			if(valid.indexOf(c) <= -1) {
				result = false;
			}
		}
		return result;
	}

	// Sort table rows.
	var asc = order == "asc";
	var rows = $(table).find("tbody > tr").get();
	var column = $(table).parent(".bDiv").siblings(".hDiv").find("table tr th").index($("th.sorted", ".flexigrid:has(" + table + ")"));
	rows.sort(function(a, b) {
		var keyA = $(asc? a : b).children("td").eq(column).text().toUpperCase();
		var keyB = $(asc? b : a).children("td").eq(column).text().toUpperCase();
		if((isNumeric(keyA)||keyA.length<1) && (isNumeric(keyB)||keyB.length<1)) {
			keyA = stripChar(keyA,", ");
			keyB = stripChar(keyB,", ");
			if(keyA.length < 1) keyA = 0;
			if(keyB.length < 1) keyB = 0;
			keyA = new Number(parseFloat(keyA));
			keyB = new Number(parseFloat(keyB));
		}
		return keyA>keyB ? 1 : keyA<keyB ? -1 : 0;
	});

	// Rebuild the table body.
	$.each(rows, function(index, row) {
		$(table).children("tbody").append(row);
	});

	// Fix styles
	$(table).find("tr").removeClass("erow");  // Clear the striping.
	$(table).find("tr:odd").addClass("erow"); // Add striping to odd numbered rows.
	$(table).find("td.sorted").removeClass("sorted"); // Clear sorted class from table cells.
	$(table).find("tr").each( function(){
		$(this).find("td:nth(" + column + ")").addClass("sorted");  //Add sorted class to sorted column cells.
	});
} // sortGrid



