/*
 *
 * set_up_trade
 * General JavaScript File By: Paul Grimes
 *      Set Focus to main input
 *      Set Accordion Handler for side menu
 *      Set ajax handler for submission
 *      Set Drop Down Handler for top menu
 *      Set Modal class for submit, upload, etc...
 *      Set Delete function for table items
 *      Set Sum function for calculating totals
 *
 * set_up_thanks
 *      Set up Drop Down handler for Top Menu
 *      Set Validation Handler
 *
 */

/*
 * set_up_trade
 *
 * JavaScript functions for calculator.php
 */
function set_up_trade() {
    window.addEvent('domready', function() {
	    SetFocus();
	    AccordionHandler();
	    DropDownHandler();
	    AjaxHandler();
	    Modal();
	    add_delete();
	    calcSum();
	    show_referral_other();
	});
}

/*
 * set_up_thanks
 *
 * JavaScript functions for thank-you.php
 */
function set_up_thanks() {
    window.addEvent('domready', function() {
	    DropDownHandler();
	});
}

/*
 * AjaxHandler
 *
 * We need to add an event to utilize a
 * ajax feed to push/get results of the
 * calculator
 *
 */
function AjaxHandler() {
    //Do not show validation pop ups if IE7/IE6
    if (valid_browser())
        validation = new FormCheck("abundaInput");

    $('abundaInput').addEvent('submit', function(e) {
	    e.stop();
	    // Stop posting to "process/request.php
	    if (valid_input() && consolidateDuplicates()) {

		$('main_content').addClass('ajax-loading');
		var res = $('abundaCalcBody_request').empty();

		// Get the results back when completed
		this.set('send', {
			//Set on complete function
			onComplete : function(response) {

			    // Remove the ajax loading class
			    res.removeClass('ajax-loading');

			    res.set('html', response);
			    var _placeHolder = document
				.getElementById("abundaCalcBody_process");

			    var placeholder = $(_placeHolder);
			    var reqChild = res.getFirst();

			    if (reqChild != null)
				reqChild.inject(placeholder, 'top');
			    add_delete();
			    $('product_code').value = "";
			    calcSum();
			    SetFocus();
			}

		    });
		this.send();
	    } else
		if (valid_browser())
		    validation.reinitialize();

	});
}

/*
 * add_delete
 *
 * We need a way to add the delete capabilities to table rows if applicable
 */
function add_delete() {
    $$('img.delete').each( function(el) {
	    el.addEvent('click', function() {
		    $upc = $(this).getParent().getParent().getElements('td.upc');
		    delete_item($upc[0].get('text'));
		    $(this).getParent().getParent().dispose();
		    calcSum();
		    SetFocus();
		});
	});
}

/*
 * Accordion Handler
 *
 * We need to add an event to handle
 * the side menu accordion.
 *
 */
function AccordionHandler() {
    var myAccordion = new Accordion($('accordion'), $$('h3.toggler'), $$('div.element'), {
	    display : -1,
	    opacity : true,
	    onActive : function(toggler, element) {
		toggler.removeClass('toggler');
		toggler.addClass('toggler_selected');
		SetFocus();
	    },
	    onBackground : function(toggler, element) {
		toggler.removeClass('toggler_selected');
		toggler.addClass('toggler');
	    }
	});
}

/*
 * DropDownHandler
 *
 * We need to set an event to handle the
 * main menu drop down effects.
 */
function DropDownHandler() {
    if ($('drop_down_menu')){
        $('drop_down_menu').getElements('li.menu').each( function(elem) {
		var list = elem.getElement('ul.links');
		var myFx = new Fx.Slide(list).hide();
		elem.addEvents( {
			'mouseenter' : function() {
			    myFx.cancel();
			    myFx.slideIn();
			},
			    'mouseleave' : function() {
				myFx.cancel();
				myFx.slideOut();
				elem.addClass('');
			    }
		    });
	    });

        $$('img.mo').each( function(el) {
		var src = el.getProperty('src');
		var extension = src.substring(src.lastIndexOf('.', src.length));
		el
                    .addEvent('mouseenter', function() {
			    el.setProperty('src', src
					   .replace(extension, '_hover' + extension));
			});
		el.addEvent('mouseout', function() {
			el.setProperty('src', src);
		    });
	    });
    }
}

/*
 * ValidationHandler
 *
 * We need to add an event to validate all form inputs.
 */
function ValidationHandler() {
    validation = new FormCheck("abundaInput", {
	    submitByAjax : false,
	    onAjaxRequest : AjaxHandler(),
	    display : {
		showErrors : 0,
		fixPngForIe : 1,
		scrollToFirst : false,
		checkValueIfEmpty : 0
	    }
	});
}

/*
 * Modal
 *
 * We need a way to show and hide the Modal form
 * from the calculator page.
 *
 */

function Modal() {
    $("submitList").addEvent("click", function() {
	    valid_submit = new FormCheck('submit_valuation', {
		    display  : {
			fixPngForIe : 1
		    }
		});
	    showModal("submitModal");
	});
    $("submitCancel").addEvent("click", function() {
	    hideModal("submitModal");
	});
}

/*
 * showModal
 *
 * We need a generic function to add the events
 * to show a modal box.
 */
function showModal(value) {
    var effect = new Fx.Morph(value, {
	    duration : 'long',
	    transition : Fx.Transitions.Sine.easeOut
	});

    effect.start( {
	    'display' : 'block'
		});
}

/*
 * hideModal
 *
 * We need a generic function to add the events
 * to hide a modal box
 */
function hideModal(value) {
    var effect = new Fx.Morph(value, {
	    duration : 'long',
	    transition : Fx.Transitions.Sine.easeOut
	});

    effect.start( {
	    'display' : 'none'
		});
}

/*
 * Sets focus on product_code
 *
 * You can change the element to focus on by passing the element id
 * --This is a string for that represents the element id
 * --Defalut is currently product_code, yes hard coded.
 *
 */
function SetFocus(value) {
    value = (value == undefined) ? 'product_code' : value;
    if ($(value))
        $(value).focus();
}

/*
 * Find Duplicate UPC/ISBN
 *
 * This function will find all duplicate UPC codes
 * This will then add it to the current table.
 */

function consolidateDuplicates() {
    var upcs = $$('td.upc');
    var quantities = $$('td.quantity');
    var upc = $('product_code').value;
    var qty = $('product_qty').value;

    for ( var idx = 0; idx < upcs.length; idx++) {
        if (upc == $(upcs[idx]).get('text')) {
            var value = $(quantities[idx]).get('text');
            value = parseInt(value);
            value += parseInt(qty);
            update_item_qty(value, $(upcs[idx]).get('text'));
            $(quantities[idx]).set('text', value);
            $('product_code').value = "";
            $('product_qty').value = "1";
            calcSum();
            SetFocus();
            return false;
        }
    }
    return true;
}

/*
 * calcSum
 *
 * Takes all values in the table (td.values)
 * for each td.values
 * 		Removes the dollar sign ($)
 * 		Converts it to a float
 * 		Accumulates a total.
 *
 * Assign the toal to the footer, th#grand_total
 *
 */
function calcSum() {
    var lines = $$('td.line_number');
    var values = $$('td.values');
    var quantity = $$('td.quantity');
    var item = $$('td.item');
    var grandTotal = 0;
    var idx;
    for (idx = 0; idx < values.length; idx++) {
        var value = $(item[idx]).get('text');
        value = parseFloat(value.replace('$', ''));
        var qty = parseInt($(quantity[idx]).get('text'));
        var total = qty * value;
        grandTotal += total;
        $(values[idx]).set('text', numberFormat(2, '.', ',', total));
        $(lines[idx].set('text', idx + 1));
    }
    $('item_count').set('text', idx)
	$('grand_total').set('text', numberFormat(2, '.', ',', grandTotal));
}

/*
 * numberFormat
 *
 * Define number of decimals to format for
 * Define the style of the decimal point
 * Define the style of the seperator
 *syb
 * takes a number (980987.838)
 * turns the number into ($980,987.84)
 *
 */
function numberFormat(decimals, dec_point, thousands_sep, total) {
    decimals = Math.abs(decimals) + 1 ? decimals : 2;
    dec_point = dec_point || '.';
    thousands_sep = thousands_sep || ',';

    var matches = /(-)?(\d+)(\.\d+)?/.exec(total + ''); // returns matches[1] as
    // sign, matches[2] as
    // numbers and
    // matches[2] as
    // decimals
    var remainder = matches[2].length > 3 ? matches[2].length % 3 : 0;
    return '$' + (matches[1] ? matches[1] : '') + (remainder ? matches[2]
						   .substr(0, remainder) + thousands_sep : '') + matches[2]
	.substr(remainder).replace(/(\d{3})(?=\d)/g, "$1" + thousands_sep) + (decimals ? dec_point + (+matches[3] || 0)
									      .toFixed(decimals).substr(2) : '');
}

/*
 * Delete Item
 *
 * We need a method to delete items from the database.
 */
function delete_item(code) {
    var req = new Request( {
	    method : 'get',
	    url : 'process/deleteItem.php',
	    async : false,
	    onRequest : function() {
            },
	    onComplete : function() {
            }
	});
    req.send('product=' + code);
}
/*
 * Update Item Quantity
 *
 * We need a way to update the quantity in the database
 */
function update_item_qty(qty, product) {
    var req = new Request( {
	    method : 'get',
	    url : 'process/updateItem.php',
	    async : false
	});
    req.send('product=' + product + '&quantity=' + qty);
}

function valid_input() {

    var alphanum = new RegExp("^[dD]?\\d{5,13}[xX]?$");
    var digit = new RegExp("^[0-9]*$");
    var product = $('product_code').get('value');

    product = product.replace(" ", "");
    product = product.replace("-", "");

    if (alphanum.test(product) == false) {
        return false;
    }

    if (digit.test($('product_qty').get('value')) == false)
        return false;

    var num = $('product_qty').get('value');
    if (parseInt(num) == 0 || isNaN(parseInt(num)))
        return false;

    if (num < 0 && num > 25)
        return false;

    return true;
}

/*
 * show_referral_other
 *
 * We need a way to show the other box and field
 * when someone selects a referral option that
 * has a value of 1.
 *
 */
function show_referral_other() {

    $('txtOther').setStyle('display', 'none');
    $('lblOther').setStyle('display', 'none');
    $('hvReferral').set('value', $('ddlReferrals').get('text'));
    $("ddlReferrals").addEvent('change', function() {
	    if ($('ddlReferrals').value == 1) {
			$('txtOther').setStyle('display', 'block');
			$('lblOther').setStyle('display', 'block');
			$('modal').setStyle('height','430px');
	    } else {
			$('txtOther').setStyle('display', 'none');
			$('lblOther').setStyle('display', 'none');
			$('modal').setStyle('height','370px');
	    }

	});

}

function get_ie_version(){
    var version = -1;
    if (navigator.appName == 'Microsoft Internet Explorer') {
        var agent = navigator.userAgent;
        var regex = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (regex.exec(agent) != null)
            version = parseFloat(RegExp.$1);
    }

    return version;

}

function valid_browser(){
    var valid = true;
    var version = get_ie_version();
    if (version >= 8.0)
        valid = true;
    else
        valid = false;

    return valid;
}
