var bannerFunctions =
{
    activeFrame: 0,
    bannerContentsWidth: 960,
    bannerTransitionTime: 1000,
    bannerTimeoutLength: 7000,
    frameLength: null,
    frameRotateTimer: null,
    frameTimeoutLength: 7000,
    goToFrameTimer: null,

    frameRotate: function ()
    {
        if (bannerFunctions.activeFrame >= bannerFunctions.frameLength - 1)
        {
            bannerFunctions.goToFrame(0);
        }
        else
        {
            bannerFunctions.goToFrame(bannerFunctions.activeFrame + 1);
        }
    },
    goToFrame: function (frameNumber, direction)
    {
        clearTimeout(bannerFunctions.frameRotateTimer);
        $('.promo_frame').stop(true, true);
        var showDirection = 'right';
        var hideDirection = 'left';
        if( direction == 'back') {
	        var showDirection = 'left';
	        var hideDirection = 'right';
        }
                
        bannerFunctions.frameRotateTimer = setTimeout('bannerFunctions.frameRotate()', bannerFunctions.bannerTimeoutLength);
        $('.promo_bookmarks').removeClass('promo_bookmarks_active');
        $('.promo_frame').eq(bannerFunctions.activeFrame).hide('slide', {direction: hideDirection}, 500, function() {
        	$(this).clearQueue();
        }).removeClass('promo_frame_active');
        bannerFunctions.activeFrame = frameNumber;
        $('.promo_frame').eq(bannerFunctions.activeFrame).show('slide', {direction: showDirection}, 500, function() {
			$(this).clearQueue();        	
        }).addClass('promo_frame_active');
        $('.promo_bookmarks').eq(frameNumber).addClass('promo_bookmarks_active');
    }
};
var productFunctions =
{
    displayConfigurations: function (data)
    {
        var configWrapper = $('<div id="product_configure_wrapper">');
        $(configWrapper).append($('<div id="product_configure_header">').html('Please Select a Configuration'));
        $(data.configurations).each(function ()
        {
            var configItem = $('<div class="product_configure_row">');
            var configImage = $('<div class="product_configure_img">').append('<img width="90" height="90" alt="' + this.product_name + '" title="' + this.product_name + '" src="http://vault.trilithic.com/eas/images/products/90/' + this.product_image_name + '" />');
            var configInfo = '<div class="product_configure_info">' + 
            	'<div class="product_configure_name">' + this.product_name + '</div>' + 
            	'<div class="product_configure_subtitle">' + (this.product_subtitle ? this.product_subtitle + '<br />' : '') + 'P/N: ' + this.product_number + '</div>' + '	<a class="input_button input_button_mini product_request_button" name="' + this.product_id + '">Request a Quote</a>' + '</div>';
            $(configItem).append(configImage).append(configInfo);
            $(configWrapper).append(configItem);
        });
        generalFunctions.displayNotice(configWrapper, '610', null, '460', 'Select a Configuration');
    },
    displayOptions: function (data, productId)  {
        var customWrapper = '<div id="product_configure_wrapper">';

        switch (data.baseproduct.baseproductid) {
        	//Customize EASyCAP Economy
	        case '9044':
	        case '9046':
	        customWrapper += '<form id="form_product_configure">' + 
	        	'<div id="product_configure_header">Configure Your EASyCAP System</div>'; 
	
	        $(data.options).each(function(){
				customWrapper += '<div class="product_configure_row result_row">' + 
	            	'<div class="product_configure_functions">' + 
	            		'<input class="product_configure_productId" type="hidden" value="' + this.product_id + '" />' + 
	            		'<input class="product_configure_selected" type="checkbox" name="' + data.baseproduct.baseproductid + '" value="' + this.product_id + '" ' + (this.pre_select == 1 ? 'checked="checked"' : '') + ' /> ' + 
	        		'</div>' + 
	        		'<div class="product_configure_meta">' + 
	        			'<div class="product_configure_name">' + this.product_name + '</div>' + 
	        			//'<div class="product_configure_shortdesc">' + this.product_desc + '</div>' + 
        			'</div>' +
	    		'</div>';
	        });
	
	        customWrapper += '<hr />' +
	        '<input id="product_configure_submit" class="input_button" type="submit" value="Add to Basket" />' + 
	        '<input id="product_configure_skip" class="input_button input_button_secondary" type="button" value="Skip Configuration" />' + 
	        '</form></div>';
	        break;
			
			//Customize EASyCAP Premium
			case '9045':
			case '9047':
			
			var customOptions = {
	            'checkbox': [],
	            'quantity': []
	        };
	        
	        $(data.options).each(function() {
	        	switch(this.product_id){
	        		case '9049': //Audio Board
	        		case '9042': //Expansion 1
	        		case '9043': //Expansion 2
	        		customOptions.checkbox.push(this);
	        		break;
	        		case '9041': //Radio Board
	        		customOptions.quantity.push(this);
	        		break;
	        	}
	    	});
			
			customWrapper += '<form id="form_product_configure">' + 
	        	'<div id="product_configure_header">Configure Your EASyCAP System</div>';
	
			//Print checkbox options
	        $(customOptions.checkbox).each(function() {
				customWrapper += '<div class="product_configure_row result_row">' + 
	            	'<div class="product_configure_functions">' + 
	            		'<input class="product_configure_productId" type="hidden" value="' + this.product_id + '" />' + 
	            		'<input class="product_configure_selected" type="checkbox" name="' + data.baseproduct.baseproductid + '" value="' + this.product_id + '" ' + (this.pre_select == 1 ? 'checked="checked"' : '') + ' /> ' + 
	        		'</div>' + 
	        		'<div class="product_configure_meta">' + 
	        			'<div class="product_configure_name">' + this.product_name + '</div>' + 
	        			//'<div class="product_configure_shortdesc">' + this.product_desc + '</div>' + 
        			'</div>' + 
	    		'</div>';
	        });
	        
	        customWrapper += '<hr />';
	        
	        //Print quantity options
	        $(customOptions.quantity).each(function() {
				customWrapper += '<div id="product_configure_header">Number of AM/FM/NOAA Radio Boards (0 - 2)</div>' + 
				'<div class="product_configure_row result_row">' + 
					'<div class="product_configure_name">' + 
						'<input class="product_configure_productId" type="hidden" value="' + this.product_id + '" />' + 
						'Quantity: <input class="product_configure_quantity input_text" type="text" size="2" value="0" /> ' + 
					'</div>' + 
				'</div>';
	        });
	
	        customWrapper += '<hr />' + 
	        '<input id="product_configure_submit" class="input_button" type="submit" value="Add to Basket" />' + 
	        '<input id="product_configure_skip" class="input_button input_button_secondary" type="submit" value="Skip Configuration" />' + 
	        '</form></div>';
	        break;    
        }
        generalFunctions.displayNotice(customWrapper, '450', null, null, 'Configure Your Product');

        // Product Configuration Submit
        $('#form_product_configure').bind('submit', function (e)
        {
            e.preventDefault();
            var aSelectedOptions = [];
            var upgradeQuantity;
            $('.product_configure_quantity').each(function(){
            	upgradeQuantity = $(this).val();
            	if(upgradeQuantity >= 1){
                	for ($r = 0; $r < upgradeQuantity; $r++){
						aSelectedOptions.push($(this).siblings('.product_configure_productId').val());
					}
            	}
            
            });
            $(':checked', this).each(function ()
            {
                aSelectedOptions.push($(this).val());
            });
            $.getJSON('/_inc/_ajx/ajxQuoteActions.php', {
                action: 'product_configure_submit',
                jaProductOptions: JSON.stringify(aSelectedOptions),
                jProductID: data.baseproduct.baseproductid,
                jProductQuantity: upgradeQuantity
            }, function (data)
            {
                switch (data.outcome)
                {
                case '0':
                    var configureError = $('<ul id="product_configure_error_list">');
                    if ($.isArray(data.message))
                    {
                        for (var i = 0; i < data.message.length; i++)
                        {
                            configureError.append($('<li>').append(data.message[i]));
                        }
                    }
                    else
                    {
                        configureError.append($('<li>').append(data.message));
                    }
                    if ($('#product_configure_error').length)
                    {
                        $('#product_configure_error').html(configureError);
                    }
                    else
                    {
                        $('#alert').prepend($('<div id="product_configure_error">').html(configureError));
                    }
                    if (data.required)
                    {
                        $(data.required).each(function ()
                        {
                            $('input.product_configure_selected[value=' + this + ']').attr('checked', 'true');
                        });
                    }
                    break;
                case '1':
                    generalFunctions.hideNotice();
                    window.location = "/Request/review.html";
                }
            });
        });
    }
}    

    var quoteFunctions =
    {
        configureData: null,
        formatCurrency: function (num)
        {
            num = parseFloat(num);
            num = isNaN(num) || num === '' || num === null ? 0 : num.toFixed(2);
            num += '';
            x = num.split('.');
            x1 = x[0];
            x2 = x.length > 1 ? '.' + x[1] : '';
            var rgx = /(\d+)(\d{3})/;
            while (rgx.test(x1))
            {
                x1 = x1.replace(rgx, '$1' + ',' + '$2');
            }
            return x1 + x2;
        }
    }

    $(document).ready(function ()
    {
        ////////////////////////////////////
        // Homepage Banner
        ////////////////////////////////////
        bannerFunctions.frameLength = $('.promo_frame').length;
        
        //Banner click tracking
        $('.promo_frame').click(function(e){
        	e.preventDefault();
        	_gaq.push(['_trackEvent', 'Banner', 'EAS Home', $(this).attr('id')]);
        	window.location = $(this).find('a').attr('href');
		});
        
        var bannerBookmarks = $('<div id="promo_bookmarks_wrapper">');
		
        // Initialize banner bookmarks
        for (i = 1; i <= bannerFunctions.frameLength; i++)
        {
            bannerBookmarks.append($('<div class="promo_bookmarks">'));
        }
        bannerBookmarks.appendTo('#promo');

        // Banner bookmark listener
        $('.promo_bookmarks').live('click', function ()
        {
            var thisBookmark = $(this).index('.promo_bookmarks');
            bannerFunctions.goToFrame(thisBookmark);
        });

        bannerFunctions.frameRotateTimer = setTimeout('bannerFunctions.frameRotate()', bannerFunctions.bannerTimeoutLength);
        
        $('.promo_prev').bind('mouseover mouseout click', function(e){
        	switch(e.type){
        		case 'mouseover':
        		$(this).addClass('promo_prev_hover');
        		break;
        		case 'mouseout':
	        	$(this).removeClass('promo_prev_hover');
	        	break;
	        	case 'click':
	            var thisBookmark = bannerFunctions.activeFrame <= 0 ? (bannerFunctions.frameLength - 1) : (bannerFunctions.activeFrame - 1);
	            bannerFunctions.goToFrame(thisBookmark, 'back');
	            break;
            }
        });
        
        $('.promo_next').bind('mouseover mouseout click', function(e){
        	switch(e.type){
        		case 'mouseover':
        		$(this).addClass('promo_next_hover');
        		break;
        		case 'mouseout':
	        	$(this).removeClass('promo_next_hover');
	        	break;
	        	case 'click':
	            var thisBookmark = bannerFunctions.activeFrame >= (bannerFunctions.frameLength - 1) ? 0 : (bannerFunctions.activeFrame + 1);
	            bannerFunctions.goToFrame(thisBookmark);
	            break;
            }
        });
        
        

        ////////////////////////////////////
        // Slider
        ////////////////////////////////////
        var handleWidth = parseInt($('#featured_slider_handle').css('width'));
        var sliderWidth = $('.featured_product').outerWidth(true) * $('.featured_product').length;
        var wrapperWidth = $('#featured').width();
        $('#featured_slider').css('width', sliderWidth + 'px');

        $('#featured_slider_handle').draggable(
        {
            containment: 'parent',
            drag: function (event, ui)
            {
                var handlePosition = parseInt($('#featured_slider_handle').css('left'));
                var handlePercent = handlePosition / (wrapperWidth - handleWidth);
                $('#featured_slider').css('right', (sliderWidth - wrapperWidth) * handlePercent + 'px');
            }
        });

		////////////////////////////////////
        // Product List Page
        ////////////////////////////////////
        $('.productlist_product').hover(function(){
        	$(this).addClass('productlist_product_hover');
        }, function(){
        	$(this).removeClass('productlist_product_hover');
        });
        $('.productlist_product').click(function(e){
        	window.location = $(this).find('.productlist_product_title').find('a').attr('href');
    	});

        ////////////////////////////////////
        // Product Page
        ////////////////////////////////////
        $('#product_tab_wrapper').tabs();

        //Show Documents when category is clicked
        $('.product_documents_type').click(function ()
        {
            $(this).next('.product_documents_file_list').toggle('blind', 250);
        });

        //Set the number of documents to display for each type
        var productDocumentsDisplayed = 2;

        $('.product_documents').each(function ()
        {
            var productDocuments = $(this).find('.product_documents_file');

            //Hide any documents greater than the quantity defined by productDocumentsDisplayed
            productDocuments.each(function ()
            {
                if ($(productDocuments).index(this) > productDocumentsDisplayed - 1)
                {
                    $(this).hide();
                }
            });

            //Create a "More" link if more documents are available
            if (productDocuments.length > productDocumentsDisplayed)
            {
                productDocuments.last().after($('<li class="product_documents_more product_documents_file">').html('<a href="#more">' + (productDocuments.length - productDocumentsDisplayed) + ' More available</a>'));
            }
        });
        
        //Display more documents
        $('.product_documents_more').click(function(e) {
        	var theseDocs = $(this).parents('ul').clone();
        	theseDocs.find('.product_documents_more').remove();
        	theseDocs.find('li').show();
        	generalFunctions.displayNotice(theseDocs, '480', null, '360', 'More Documents');
		});
 
        //Request a Quote
        $('.product_request_button').live('click', function (e)
        {
            e.preventDefault();
            var productId = $(this).attr('name');
            $.getJSON('/_inc/_ajx/ajxQuoteActions.php', {
                action: 'product_add',
                jProductID: productId
            }, function (data)
            {
                if (data.configurations)
                {
                    productFunctions.displayConfigurations(data);
                }
                else if (data.options)
                {
                    productFunctions.displayOptions(data, productId);
                }
                else if (data.outcome == '0')
                {
                    generalFunctions.displayNotice(data.message);
                }
                else if (data.outcome == '1')
                {
                    window.location = "/Request/review.html";
                }
            });
        });

        //Initialize Product Videos
        var thisVid = $('#product_video').attr('name');
        if (thisVid != '')
        {
            swfobject.embedSWF("http://www.youtube.com/e/" + thisVid + "?enablejsapi=1&playerapiid=product_video", "product_video", "300", "251", "8", null, null, generalFunctions.videoParams, generalFunctions.videoAtts);
        }

        ////////////////////////////////////
        // Quote Summary
        ////////////////////////////////////
        $('#summary_contact_new').hide().find('input, select, textarea').removeClass('required');

        //Change product quantity
        $('.input_quantity').change(function (e)
        {
            e.preventDefault();
            var thisProductID = $(this).parents('.summary_product_quantity').siblings('.summary_product_functions').find('.summary_product_id').val();
            $.getJSON('/_inc/_ajx/ajxQuoteActions.php', {
                action: 'product_update',
                jProductID: thisProductID,
                jQuantity: $(this).val()
            }, function (data)
            {
                //Do something?
            });
        });

        //Validate email address against database
        $('#summary_email').change(function ()
        {
            if (generalFunctions.validateField(this))
            {
                $(this).addClass('input_loading');
                $.getJSON('/_inc/_ajx/ajxQuoteActions.php', {
                    action: 'validate',
                    jEmailAddress: $(this).val()
                }, function (data)
                {
                    //sfFunctions.sfQuery('query', "SELECT Id, FirstName FROM Contact WHERE Email = '" + $(this).val() + "'", function (data)
                    $(this).removeClass('input_loading');
                    switch (data.outcome)
                    {
                    case '0':
                        generalFunctions.displayNotice(data.message, '480', 10);
                        break;
                    case '1':
                        if (data.contactid == 0)
                        {
                        	$('#summary_contact_id').val(null);
                            $('#summary_contact_new').show('blind', 250).find('.input_required_wrapper').find('input, select, textarea').addClass('required');
                        }
                        else if (data.contactid > 0)
                        {
                            $('#summary_contact_id').val(data.contactid);
                            $('#summary_contact_new').hide('blind', 250).find('input, select, textarea').removeClass('required');
                        }
                        break;
                    }
                });
            }
        });

        //Insert new contact
        $('#summary_contact_new_submit').click(function (e)
        {
            e.preventDefault();
            if (generalFunctions.validateForm($(this).parents('form')))
            {
                $.getJSON('/_inc/_ajx/ajxQuoteActions.php', {
                    action: 'add_contact',
                    jFirstName: $('input[name="FirstName"]').val(),
                    jLastName: $('input[name="LastName"]').val(),
                    jCompany: $('input[name="AccountName"]').val(),
                    jTitle: $('input[name="Title"]').val(),
                    jEmailAddress: $('input[name="Email"]').val(),
                    jPhone: $('input[name="Phone"]').val(),
                    jAddress: $('textarea[name="MailingStreet"]').val(),
                    jCity: $('input[name="MailingCity"]').val(),
                    jStateID: $('select[name="MailingState"]').val(),
                    jPostalCode: $('input[name="MailingPostalCode"]').val(),
                    jCountryID: $('select[name="MailingCountry"]').val()
                }, function (data)
                {
                    switch (data.outcome)
                    {
                    case '0':
                        generalFunctions.displayNotice(data.message, '480', 10);
                        break;
                    case '1':
                        $('#summary_contact_id').val(data.contactid);
                        $('#summary_contact_new').hide().find('input, select, textarea').removeClass('required');
                        generalFunctions.displayNotice('Thank you for registering with Trilithic.<br />You may now proceed with your quote.', '480', 10);
                        break;
                    }
                });
            }
        });

        $('#form_summary').submit(function (e)
        {
            e.preventDefault();
            $('.input_error').html('');
            if (generalFunctions.validateForm(this))
            {
                $.getJSON('/_inc/_ajx/ajxQuoteActions.php', {
                    action: 'send_quote',
                    jComments: ($('#summary_comments').val() == 'Enter additional comments here...' ? '' : $('#summary_comments').val()),
                    jEmailAddress: $('#summary_email').val(),
                    jContactID: $('#summary_contact_id').val()
                }, function (data)
                {
                    switch (data.outcome)
                    {
                    case '0':
                        generalFunctions.displayNotice(data.message, null, 10);
                        break;
                    case '1':
                        generalFunctions.displayNotice('<h3>Your request for quote has been submitted.</h3><p>A Trilithic representative will be in touch with you.</p><p>You will be redirected to the Trilithic Emergency Alert Systems homepage shortly.</p>');
                        setTimeout(function ()
                        {
                            window.location = "http://eas.trilithic.com";
                        }, 10000);
                        break;
                    }
                });
            }
        });

        // Remove product from quote
        $('.summary_product_remove').click(function (e)
        {
            e.preventDefault();
            var thisProductWrapper = $(this).parents('.summary_product');
            $.getJSON('/_inc/_ajx/ajxQuoteActions.php', {
                action: 'product_delete',
                jProductID: $(this).siblings('.summary_product_id').val()
            }, function (data)
            {
                if (data.outcome == '1')
                {
                    thisProductWrapper.hide('blind', 250, function ()
                    {
                        if (data.items.length === 0)
                        {
                            location.reload();
                        }
                        else
                        {
                            thisProductWrapper.remove();
                        }
                    });
                }
            });
        });

        ////////////////////////////////////
        // Firmware Stuff
        ////////////////////////////////////
        $('#form_firmware_signup').submit(function (e)
        {
            e.preventDefault();
            if (generalFunctions.validateForm(this))
            {
                $.getJSON('/_inc/_ajx/ajxQuoteActions.php', {
                    action: 'et_signup',
                    jListID: $('#form_firmware_lid').val(),
                    jEmail: $('#form_firmware_email').val()
                }, function (data)
                {
                    switch (data.outcome) {
	                    case '0':
	        			var xmlDoc = $.parseXML(data.response);
	        			generalFunctions.displayNotice($(xmlDoc).find('error_description').text(), '480');
	        			break;
	        			case '1':
	        			generalFunctions.displayNotice(data.message, '480');
	        			break;
                    }
                });
            }
        });
                
        ////////////////////////////////////
        // Newsletter Signup
        ////////////////////////////////////
        
        $('#form_usergroup').submit(function(e){
        	e.preventDefault();
        	$.getJSON('/_inc/_ajx/ajxQuoteActions.php', {
        		action: 'et_signup',
        		jListID: '1665893',
        		jEmail: $('#footer_usergroup_email').val()
        	}, function(data){
        		switch(data.outcome){
        			case '0':
        			var xmlDoc = $.parseXML(data.response);
        			generalFunctions.displayNotice($(xmlDoc).find('error_description').text(), '480');
        			break;
        			case '1':
        			generalFunctions.displayNotice(data.message, '480');
        			break;
        		}
        	});
        });
    });

