/*
 *  AVMATS Surplus Shopping DOM
 *  Version 1.02
 *  Date: March 4, 2010
 *  Author: Jason Noll
 *
 *  Copyright 2010 U4EA. All Rights Reserved.
 *
 * ***************************************************************************
 *
 */

var oTable;

function iGallery(images, gallery){
		// images length
		var max = $(images).length;
		// at least 1 image exist
		if (max > 0) {
			// create the UL element
			var tb = $('<div id="thumbs_' + gallery + '"></div>');
			var sw = '#slidewrapper_' + gallery;
			var pt = $('<div id="pointer_' + gallery + '"></div>');
			// append to div#wrapper and put the div.clear after
			$(tb).appendTo($(sw)).after($('#clear_' + gallery));
			// load the first image
			LoadImage(0, max);
			$(pt).appendTo(tb).after($('#clear' + gallery));
			$(pt).animate({
				width: 185,
				opacity: 0,
				easing: "easein"
			}, 1000, "linear");
			//.fadeOut(1500);
		}
		// function of loading image
		// params: (int) index of image in array, (int) length of images array
		function LoadImage(index, max){
			// if current index is lower then max element (max-1)
			if (index < max) {
				// identify root div
				var rdiv = 'div#thumbs_' + gallery;
				// create the container, add link,add loading class
				var con = $('<div id=icontainer><a id="thumb_' + index + '" href="' + images[index] + '"></a></div>').attr('class', 'loading');
				//var con = $('<div id=icontainer' + index + '><a id="thumb_' + index + '" href="' + images[index] + '"></a></div>').attr('class', 'loading');
				// append to root div
				$(rdiv).append(con).after($('#pointer_' + gallery));
				// current container
				var dcurr = $(rdiv + " div#icontainer");
				//var dcurr = $(rdiv + " div#icontainer" + index);
				// current link
				var curr = $(rdiv + " div#icontainer a#thumb_" + index);
				//var curr = $(rdiv + " div#icontainer"+ index +" a#thumb_" + index);
				// new image object
				var img = new Image();
				// image onload
				$(img).load(function(){
					$(this).hide();
					$(curr).append(this);
					$(dcurr).removeClass('loading');
					$(this).fadeIn('slow', function(){
						// once the current loaded, trigger the next image
						LoadImage(index + 1, max);
					});
				}).error(function(){
					// on error remove current
					$(curr).remove();
					// trigger the next image
					LoadImage(index + 1, max);
				}).attr({
					'src': images[index]
				}).jScale({
					h: "50px"
				});
			};
			$('#clear_'+gallery).html('<img src="../images/jQuery/datatables/mag.png" style="padding: 0; height:0.95em">Click Images to Enlarge.');
			$('#pointer_'+gallery).remove();
		}
}

/* Formating function for row details */
function fnFormatDetails ( nTr )
{
	var aData = oTable.fnGetData( nTr );
	var sOut = '<div class="dgroup"><table width="100%" cellpadding="2" cellspacing="0" border="0">';
		sOut +='<tr><td class="dheading" width="5%" align="right">Name:</td><td colspan="3" style="font-weight:bolder">'+ aData[4] +'</td><td class="dheading" width="5%" align="right">Model:</td><td>'+ aData[5] +'</td><td class="dheading" align="right"></td><td width="30%">('+ aData[14] +')</td></tr>';
		sOut +='<tr><td class="dheading" width="5%" align="right">Manufacturer:</td><td colspan="3" style="font-weight:bold">'+ aData[3] +'</td><td class="dheading" width="5%" align="right">P/N:</td><td>'+ aData[6] +'</td><td class="dheading" align="right"></td><td width="30%"></td></tr>';
		sOut +='<tr><td class="dheading" width="5%" align="right">Dimensions:</td><td>'+ aData[9] +'</td><td class="dheading" align="right">Weight (lbs):</td><td>'+ aData[10] +'</td><td class="dheading" width="5%" align="right">S/N:</td><td>'+ aData[7] +'</td><td class="dheading" align="right">Condition:</td><td>'+ aData[11] +'</td></tr>';
		sOut +='<tr><td class="dheading" width="5%" align="right">Description:</td><td colspan="7">'+ aData[8] +'</td></tr>';
		sOut +='</table>';
	    sOut += '<table width="100%" cellpadding="2" cellspacing="0" border="0">';
	    sOut += '<tr><td colspan="8"><div id="slidewrapper_' + aData[1] + '" style="border: 1px dashed gray; font-family: verdana, arial, sans-serif; font-weight: bold; margin: 10px; padding:5px; text-align: center; width: auto;">';
	    sOut += 'Images Loading...</div><div id="clear_' + aData[1] + '"></div></td></tr>';
		sOut += '</table></div>';
	
	return sOut;
}

/* Event handler function */
function fnOpenClose ( sTable ){
    /* Open/Close Event Listener */
    $('#open', sTable.fnGetNodes()).each(function(){
		$(this).click(function(){
            var nTr = this.parentNode.parentNode;
            if (this.src.match('close')) {
                /* This row is already open - close it */
                this.src = "../images/jQuery/datatables/open.gif";
                $('td.details').remove();
            }
            else {
                /* Open this row */
                $('td.details').remove();
				$('.tag').attr({src: "../images/jQuery/datatables/open.gif"});
                var iIndex = sTable.fnGetPosition(nTr);
                var aData = sTable.fnSettings().aoData[iIndex]._aData;
                this.src = "../images/jQuery/datatables/close.gif";
				$(this).addClass("tag");
                sTable.fnOpen(nTr, fnFormatDetails(nTr), 'details');
				if(eval('typeof images_'+aData[1]+'!="undefined"')){
					var imageArr = eval('$(images_' + aData[1] + ')');
					$('#slidewrapper_'+aData[1]).each(function(){$(this).text('');$(this).removeAttr('style');});
	                iGallery(imageArr, aData[1]);
				}
            }
        });
    });	
}

/* Search Modification */
function fnSEM(sTable){
	$('div:[id$="_filter"]').empty().append('<input class="avSrbox" type="text"><div class="avSrEx"></div>');
	$('.avSrEx').click(function(){
		sTable.fnFilter($('.avSrbox').val());
	});
}
	
/*
 *  Shopping Cart Controls
 */
function fnShopping(action){
	var url = 'http://shopsite.readyhosting.com/ss10.0/sc/order.cgi?storeid=*16e5949d4f7d71f80702be5f0a';
	var ploc = '&prevlocation=http://www.avmats.com/surplus/shopping.htm';
	
    $('#oSelect').hide();
	$('#oExpoLoader').show();
	$('#exposeMask').show();
	$('#oExpo').show("slow");	
	
	if (action == 'show') {
		window.location.href = url + "&function=show";
	}
	else {
		window.location.href = url + "&dbname=products&sku=" + action + "&function=add";
	}
}

/*
 *  Opening Filter
 */
function tfilter(pos){
    $('ul.tabs').tabs().click(pos);
    switch (pos) {
        case 0:
            var str = '';
            break;
        case 1:
            var str = '1';
            break;
        case 2:
            var str = '2';
            break;
        default:
            var str = '';
    }
    oTable.fnFilter(str, 17);
}

/*
 *  Login form
 */
function fnlogin(){
	var iform = '<div id="sign">';
		iform += '<input name="user" class="input" type="text" value="User Name">';
		iform += '<input name="pass" class="input" type="password" value="password">'; 
		iform += '<button id="submit">Login</button>';
		iform += '</div>';
	$('#c_login').hide();
	$('#c_login').before($(iform));
	if(jQuery.browser.mozilla == true){
		$('#submit').css('top','2px');
	}
	$('.input').focus(function(){
		if (($(this).val() == 'User Name')||($(this).val()=='password')) {
			$(this).val('');
			$(this).css({
				'color': '#F30'
			});
		}
	});
	$('.input').blur(function(){
		if ($(this).val().length == 0) {
			$(this).val('User Name');
			$(this).css({'color': '#999'});
		}
	});
	$('#submit').click(function(){
		$(this).hide();
		$(this).before('<img src="../images/jQuery/ajax-loader.gif" style="height: 1.5em;position: relative;top:-2px;">');
		var tag = "?r=" + $('input[name="user"]').val() + "&a=" + $.md5($('input[name="pass"]').val());
		$.getScript('../scripts/shoppingEditor.php' + tag);
	});
	$('.input:[name="pass"]').bind('keypress', function(e) {
		if(e.keyCode==13){
			$(this).blur();
			$('#submit').trigger('click');
	}
});
}

/*
 * Identify Currency
 */
jQuery.fn.dataTableExt.aTypes.push(function(sData){
    var sValidChars = "0123456789.-,";
    var Char;
    
    /* Check the numeric part */
    for (i = 1; i < sData.length; i++) {
        Char = sData.charAt(i);
        if (sValidChars.indexOf(Char) == -1) {
            return null;
        }
    }
    
    /* Check prefixed by currency */
    if (sData.charAt(0) == '$' || sData.charAt(0) == 'Â£') {
        return 'currency';
    }
    return null;
});

/* 
 *  Asending Sort Currency
 */
jQuery.fn.dataTableExt.oSort['currency-asc'] = function(a, b){
    /* Remove any commas (assumes that if present all strings will have a fixed number of d.p) */
    var x = a == "-" ? 0 : a.replace(/,/g, "");
    var y = b == "-" ? 0 : b.replace(/,/g, "");
    
    /* Remove the currency sign */
    x = x.substring(1);
    y = y.substring(1);
    
    /* Parse and return */
    x = parseFloat(x);
    y = parseFloat(y);
    return x - y;
};

/* 
 *  Desending Currency Sort
 */
jQuery.fn.dataTableExt.oSort['currency-desc'] = function(a, b){
    /* Remove any commas (assumes that if present all strings will have a fixed number of d.p) */
    var x = a == "-" ? 0 : a.replace(/,/g, "");
    var y = b == "-" ? 0 : b.replace(/,/g, "");
    
    /* Remove the currency sign */
    x = x.substring(1);
    y = y.substring(1);
    
    /* Parse and return */
    x = parseFloat(x);
    y = parseFloat(y);
    return y - x;
};

/* 
 *  Desending Sort Formated Number
 */
jQuery.fn.dataTableExt.oSort['formatted-num-desc'] = function(x, y){
    x = x.replace(/[^\d\-\.\/]/g, '');
    y = y.replace(/[^\d\-\.\/]/g, '');
    if (x.indexOf('/') >= 0) 
        x = eval(x);
    if (y.indexOf('/') >= 0) 
        y = eval(y);s
    return x / 1 - y / 1;
};

/* 
 *  Assending Sort Formated Number
 */
jQuery.fn.dataTableExt.oSort['formatted-num-asc'] = function(x, y){
    x = x.replace(/[^\d\-\.\/]/g, '');
    y = y.replace(/[^\d\-\.\/]/g, '');
    if (x.indexOf('/') >= 0) 
        x = eval(x);
    if (y.indexOf('/') >= 0) 
        y = eval(y);
    return y / 1 - x / 1;
};

$(document).ready(function() {
    /*
     * Load iGallery directory
     */
    $.ajax({
		type: "GET",
		url: "../scripts/iGallery.php?item=../surplus/images",
		datatype: "script",
		cache: false,
		success: function(){
			if($('.details').length>0){
				var iTem = $('.details').parent().prev().children().first();
				var aPos = oTable.fnGetPosition(iTem[0]);
				var aData = oTable.fnGetData( aPos[0] );
				var imageArr = eval('$(images_' + aData[1] + ')');
				$('#slidewrapper_'+aData[1]).each(function(){$(this).text('');$(this).removeAttr('style');});
                iGallery(imageArr, aData[1]);
			}
		}
	});
	   
	/* load Tabs */
    $("ul.tabs").tabs("div.panes > div");

    /* Initialize Opening Category Menu */
    $("#oSelect").lavaLamp({
        fx: 'easeInBack',
        speed: 700,
        returnHome: true,
        homeLeft: -100,
        homeTop: -25,
        homeWidth: 600,
        homeHeight: 10
    });
	
    /* Initalize Table Filtering Menu */
    $("ul[id^='llvi']").lavaLamp({
        fx: 'easeInBack',
        speed: 700,
        returnHome: false,
        homeLeft: -100,
        homeTop: -25,
        homeWidth: 600,
        homeHeight: 10
    });
	
     /*
     *  Expose Datatable Filter Menu
     */

    $("#oExpo").each(function(){
        $(this).show("slow");
		$('#exposeMask').show().fadeTo('fast', 0.8);
		$('#navcon, #pagecell1').show();
    });

	$(':[id^="thumb_"]').live('mouseover',function(){
		$(this).fancybox({
			'overlayShow': false,
			'zoomSpeedIn': 600,
			'zoomSpeedOut': 500,
			'easingIn': 'easeOutBack',
			'easingOut': 'easeInBack',
			'callbackOnStart': function(){
				$('#fancy_overlay').css('z-index','303');
				$('#fancy_outer').css('z-index','311');
				$('#fancy_close').css('z-index','381');
				$('#fancy_bg').css('z-idex','307');
			}
		});
	});
			
	oTable = $('#spares').dataTable( {
		"bProcessing": true,
		"bAutoWidth": false,
		"sAjaxSource": "../scripts/shopping.php",	
		"sPaginationType": "full_numbers",
		"aoColumns": [ 
	/* [0]Details */		{ "bSearchable": false, "bVisible": true, "bSortable": false, "sClass": "center", "sWidth": "70px" },
	/* [1]ID  */ 			{ "bSearchable": false, "bVisible": false },
	/* [2]Image */ 			{ "bSearchable": false, "bVisible": true, "bSortable": false, "sClass": "center" },
	/* [3]Manufacturer */  	{ "bVisible": false },
	/* [4]Name */  			{ "bVisible": true, "sClass": "bold" },
	/* [5]Model */	  		{ "bVisible": false },
	/* [6]Part */	  		{ "bVisible": false },
	/* [7]Serial */  		{ "bVisible": false },
	/* [8]Description */  	{ "bVisible": false },
	/* [9]Dimensions */  	{ "bVisible": false },
	/* [10]Weight */  		{ "bVisible": false },
	/* [11]Condition */  	{ "bVisible": true, "sClass": "center", "sWidth": "6em" },
	/* [12]New Retail */  	{ "bVisible": true, "sClass": "right", "sWidth": "6em" },
	/* [13]Our Price */  	{ "bVisible": true, "sClass": "currency", "sWidth": "6em" },
	/* [14]Employee */  	{ "bVisible": false },
	/* [15]Category */  	{ "bVisible": false },
	/* [16]Cart */			{ "bSearchable": false, "bVisible": true, "bSortable": false, "sClass": "center", "sWidth": "70px" },
	/* [17]CType */			{ "bSearchable": false, "bVisible": false }
		],
		"aaSorting": [[1, 'asc']],
       "fnDrawCallback": function(){
            $('#spares_processing').hide();
		    /* Initialize Contact Overlay */
            $(".call").fancybox({
				'hideOnOverlayClick':false,
				'hideOnContentClick':false,
				'zoomSpeedIn': 600,
				'zoomSpeedOut': 500,
				'easingIn': 'easeOutBack',
				'easingOut': 'easeInBack',
				'callbackOnShow': function(){
					$('#fancy_overlay').css('z-index','303');
					$('#fancy_close').css('z-index','381');
					$('#fancy_bg').css('z-idex','307');
					$('#fancy_ajax').css('overflow','hidden');
					var cH = $('#conInfo').height()+20+'px';
					$('#fancy_outer').css({
						'z-index': '311',
						'height':cH
					});
				}
			});
			$('#spares_processing').show();
        },
		"fnInitComplete":function(){
			//fnSEM(oTable);
			fnOpenClose(oTable);
			$("#oExpoLoader").hide();
			$('#spares_processing, #oSelect, #NavTip').show();
			/*
		 *  Close Expose Mask & Hide ToolTip
		 */
			$("#oSelect").click(function(){
				$("#exposeMask").hide(); /* $(this).exposedetails().close(); - Not Supported by IE 7 */
				$("#NavTip, #oExpo").hide("slow");
			});
			/*
		 *  Clean Tool Tip
		 */
			$("#NavTip").mousedown(function(){
				$(this).hide("slow");
			});
			$("#exposeMask").click(function(){
				$(this).hide(); /* IE 7 limitations require closeOnClick to be disabled */
				$("#NavTip").hide("slow");
				$("#oExpo").hide("slow");
			});
			var av_User = $.cookies.get( 'av_User' );
			if ($(av_User).length>0){
				$('#utility').append('<span id="uMsg">Welcome back '+av_User[1]+'! <a  href="javascript:void(0);" onclick="fnlogout();" style="color:#005FA9">Log-out</a>');
				$('#c_login, #NavTip').hide();
				$.ajax({
					type:'GET',
					url:'../scripts/shoppingADOM.js',
					dataType:'script',
					cache:false
				});
			}		
		}
	} );
	
	var lform = ' | <a id="c_login"  href="javascript:void(0);" onclick="fnlogin();">Login</a>';
		lform +='<a id="c_logout"  href="javascript:void(0);" onclick="fnlogout();" style="display:none;">Log-out</a>';
	
	$('#siteInfo').children('p:first').append(lform);
	
	
} );
