// global blogpath for ajax calls
var blogpath = "/icplus/wp-content/themes/icplus/";
var pager;  // used for pagination
/**
 * Show loading image + message
 */ 
function showLoading()
{
    $("#loading").show();
}

/**
 * Hide loading image + message
 */
function hideLoading()
{
    $("#loading").hide();
}

/**
 * after a multipart search, a select box becomes available
 * this function is attached to the select box in search results page
 */
function selectPartSearch(partKeyword)
{
	var url = blogpath + "ajax_searchPart.php";
	
	showLoading();

    $('#div_partResults').load(url, { "partKeyword": partKeyword }, function (data) {
	
		$('#in_partKeyword').val(partKeyword);
		hideLoading();
		paginateResults();
	});
}

/**
 * search for new part
 * this function is attached to search button in search results page
 */
function searchNewPart()
{
	var partKeyword = $('#in_partKeyword').val();
	var url = blogpath + "ajax_searchPart.php";
	
	showLoading();

	$('#div_partResults').load(url, { "partKeyword": partKeyword }, function (data) {
	   hideLoading();
	   paginateResults();
	});
}

/**
 * Make sure user checks at least one part to request quote
 */ 
function validateRequestQuote()
{
	var check = false;
	
    $(":checkbox:checked").each(function() {
		if (this.checked) {
		    check = true;
		    // break out of jQuery each
			return false;
		}
	});
	
	// at least one part was checked, return ok
    if (check) {
        return true;
    }
	
	var msg = "Please select the items that you would like to send RFQs for";
	$('#err_request_quote').text(msg);
	$('#err_request_quote').show();

	return false;
}

/**
 * Request quote for a single part
 */ 
function requestQuoteSingle(str)
{
    $('#singlePart').val(str);
    $('#requestQuoteOne').submit();
}

/**
 * Cancel Request For Quote
 */ 
function cancelRequest()
{
    if (confirm("Cancel RFQ?")) {
        history.go(-1);
    }
}

/**
 * Check inputs on RFQ form
 */ 
function checkRequestForm()
{
    var errmsg   = new Array();
    var partReqs = new Array();
    var partOk   = true;

    // check part number
    $('#submitRequest_form .requestPart').each(function() {

        if ($.trim(this.value) == '') {
        
            partReqs.push('Mfg Part #');
            this.focus();
            partOk = false;
            return false;
        }
    });
    
    // check qty requested
    $('#submitRequest_form .requestQty').each(function() {

        if ($.trim(this.value) == '') {
        
            partReqs.push('Qty per part');
            // focus on this if we have all part numbers filled,
            // if a part was blank, the focus was on that part
            if (partOk) {
                this.focus();
            }
            return false;
        }
    });

    // now check contact info
    var fieldsToCheck = new Array('Company', 'Contact', 'Phone', 'Email');
    var contactReqs = new Array();
    
    // check blank required fields
    for(var i=0; i<4; i++)
    {
        if ($.trim($('#'+fieldsToCheck[i]).val()) == '') {
        
            var msg = '';
            switch(fieldsToCheck[i]) {
                case 'Company': msg = "Company Name"; break;
                case 'Contact': msg = "Contact Person"; break;
                case 'Email': msg = "E-mail"; break;
                default: msg = fieldsToCheck[i]; break;
            }
            contactReqs.push(msg);
        }
    }
    
    // all required fields are filled
    if ((contactReqs.length == 0) && (partReqs.length == 0)) {
        return true;
    }
    
    if (partReqs.length > 0) {
        errmsg.push("For each part requested, please provide: " + partReqs.join(', '));
    }
    
    if (contactReqs.length > 0) {
        errmsg.push("Please fill in: " + contactReqs.join(', '));
    }

    $('#err_request_quote').html(errmsg.join("<br>"));
	$('#err_request_quote').show();
    
    return false;
}

/**
 * Remove part row
 */ 
function removePart(rowNum)
{
    $('#part-row-'+rowNum).remove();
}

/**
 * Add a new part row
 */ 
function addMoreParts()
{
    var nextRowNum = $('#nextRowNum').val();

    // clone the last table row, and append it to the table
    $('#partsTable tbody>tr:last').clone(true).insertAfter('#partsTable tbody>tr:last');
    // update new row id
    $('#partsTable tbody>tr:last').attr("id","part-row-"+nextRowNum);
    // empty part field
    $("#part-row-"+nextRowNum+ " input[type='text']").val('');
    // remove check on checkbox if checked
    $("#part-row-"+nextRowNum+ " td:last input").removeAttr('checked');
    // update checkbox's id
    $("#part-row-"+nextRowNum+ " td:last input").val('remove-row-'+nextRowNum);
    
    nextRowNum++;
    $('#nextRowNum').val(nextRowNum);
}

/**
 * User wants to remove rows
 */ 
function removeSelectedRows()
{
    var totalRows = totalChecked = 0;
    var removeRows = new Array();
    
    $('form input:checkbox').each(function(index) {
    
        totalRows++;
        if (this.checked) {
            // value would be 'remove-row-i'
            var arr = this.value.split('-');
            removeRows.push(arr[2]);
            totalChecked++;
        }
    });
    
    // nothing checked
    if (totalChecked == 0) {
        return;
    }
    
    if (totalRows == totalChecked) {
        alert("Cannot remove all parts");
        return;
    }
    
    var len = removeRows.length;
    // remove rows
    for(var i=0; i<len; i++) {
        removePart(removeRows[i]);
    }
}

// For pagination, called after table result is displayed
function paginateResults()
{
    pager = new Pager('partResultsTable', 20); 
    pager.init(); 
    pager.showPageNav('pager', 'pageNavPosition'); 
    pager.showPage(1);
    $('#partResultsTable').show();
}


/**
 * Pager class
 */ 
function Pager(tableName, itemsPerPage) {
    this.tableName = tableName;
    this.itemsPerPage = itemsPerPage;
    this.currentPage = 1;
    this.pages = 0;
    this.inited = false;
    
    this.showRecords = function(from, to) {        
        var rows = document.getElementById(tableName).rows;
        // i starts from 1 to skip table header row
        for (var i = 1; i < rows.length; i++) {
            if (i < from || i > to)  
                rows[i].style.display = 'none';
            else
                rows[i].style.display = '';
        }
    }
    
    this.showPage = function(pageNumber) {
    	if (! this.inited) {
    		alert("not inited");
    		return;
    	}

        var oldPageAnchor = document.getElementById('pg'+this.currentPage);
        oldPageAnchor.className = 'pg-normal';
        
        this.currentPage = pageNumber;
        var newPageAnchor = document.getElementById('pg'+this.currentPage);
        newPageAnchor.className = 'pg-selected';
        
        var from = (pageNumber - 1) * itemsPerPage + 1;
        var to = from + itemsPerPage - 1;
        this.showRecords(from, to);
        
        var pgNext = document.getElementById('pgNext');
        var pgPrev = document.getElementById('pgPrev');
        if (this.currentPage == this.pages)
            pgNext.style.display = 'none';
        else
            pgNext.style.display = '';
    	if (this.currentPage == 1)
            pgPrev.style.display = 'none';
        else
            pgPrev.style.display = '';
    }   
    
    this.prev = function() {
        if (this.currentPage > 1)
            this.showPage(this.currentPage - 1);
    }
    
    this.next = function() {
        if (this.currentPage < this.pages) {
            this.showPage(this.currentPage + 1);
        }
    }                        
    
    this.init = function() {
        var rows = document.getElementById(tableName).rows;
        var records = (rows.length - 1); 
        this.pages = Math.ceil(records / itemsPerPage);
        this.inited = true;
    }

    this.showPageNav = function(pagerName, positionId) {
    	if (! this.inited) {
    		alert("not inited");
    		return;
    	}
    	var element = document.getElementById(positionId);
    	
    	var pagerHtml = '<span id="pgPrev" onclick="' + pagerName + '.prev();" class="pg-normal">&#171 Prev</span>';
        for (var page = 1; page <= this.pages; page++) 
            pagerHtml += '<span id="pg' + page + '" class="pg-normal" onclick="' + pagerName + '.showPage(' + page + ');">' + page + '</span>';
        	pagerHtml += '<span id="pgNext" onclick="'+pagerName+'.next();" class="pg-normal"> Next &#187;</span>';            
        
        element.innerHTML = pagerHtml;
    }
}

/**
 * Check inputs on Excess Inventory form
 */ 
function checkInvForm()
{
    var errmsg   = new Array();
    var partReqs = new Array();

    // check contact info
    var fieldsToCheck = new Array('Company', 'Contact', 'Phone', 'Email');
    var contactReqs = new Array();
    
    // check blank required fields
    for(var i=0; i<4; i++)
    {
        if ($.trim($('#'+fieldsToCheck[i]).val()) == '') {
        
            contactReqs.push(fieldsToCheck[i]);
        }
    }
    
    if ($.trim($('#Inventory').val()) == '') {
        contactReqs.push('Inventory List');
    }
    
    // all required fields are filled
    if (contactReqs.length == 0) {
        return true;
    }
    
    if (contactReqs.length > 0) {
        errmsg.push("Please fill in: " + contactReqs.join(', '));
    }

    $('#err_inv').html(errmsg.join("<br>"));
	$('#err_inv').show();
    
    return false;
}

