/**
 * Created by JetBrains PhpStorm.
 * User: xangelo
 * Date: 2/17/11
 * Time: 10:54 AM
 * We've implemented each object based on availability
 */
if($('#register_txtTelephone').length > 0) {
    // We are on the register page, lets do a check to make sure all the fields are
    // appropriately filled out

    $('#register').submit(function(){
        if($('#register_txtName').val() == '' || $('#register_txtEmail').val() == '') {
            alert('The name and email fields are required during registration');
            return false;
        }
    });

    var parsed = false;
    $('#register_txtTelephone').blur(function(e){
        var number = $(this).val().split('');
        if(number.length < 9) {
            alert('Please enter at least a 9 digit phone number');
            parsed = false;
        }
        else {
            if(!parsed) {
                number.splice(3,0,'-');
                number.splice(7,0,'-');
                parsed = true;
                $(this).val(number.join(''));
            }
        }
    });
}

/**
 * 
 * This is the tracking script. Onclick, it fires of a request to a url. Then
 * it does nothing. Which logs it as a click. It doesn't supress or take-over, 
 * it's async.
 */
if($('#raq-button').length > 0) {
	// hokay, less do dis.
	$('#raq-button').click(function(e){
		$.ajax({
			url: 'index.php?q=Default/tracker'
			, async: false
			, type: 'post'
			, dataType: 'json'
			, data: {product_url: window.location.search}
			, beforeSend: function() {
				//console.log('sending');
			}
			, complete: function() {
				//console.log(arguments);
			}
		});
	});
}


/*
Had to pull out the timer code to preserve the appropriate namespace
 */
var Switcher = function() {
    this.cache = {
        _data: null,
        _cb: null,
        _last: null,
        _interval: null
    };

    this.ParseOutput = function(callback) {
        this.cache._cb = callback;
    }

    this.DoSwitch = function(on) {
        if(this.cache._interval == null) {
            var str = on+".DoSwitch()";
            this.cache._interval = setInterval(str,10000);
        }
        // Set up the switch conditions
        var rand = Math.floor(Math.random()*11);
        rand -= (10-this.cache._data.length);
        if(rand < 0) {
            rand = 0;
        }
        if(rand >= this.cache._data.length) {
            rand = this.cache._data.length - 1;
        }
        if(this.cache._last != rand) {    // time to switch, run our cb set by ParseOutput()
            this.cache._last = rand;
            this.cache._cb(this.cache._last);
        }
    }

    this.Populate = function(inData) {
        this.cache._data = inData;
    }
}


if($('.col3').length > 0) {
    var qna = new Switcher;

    qna.ParseOutput(function(id) {
        var html = '<a href="index.php?q=AskExperts/question/'+this._data[id][0]+'">'+this._data[id][1]+'</a>';
            html += '<div id="switcher-question">'+this._data[id][2]+'</div>';
            html += '<div><a href="index.php?q=AskExperts/question/'+this._data[id][0]+'">Read Full Question</a></div>';
        $('#qna').html(html);
    });

    $.ajax({
        url: 'index.php?q=AskExperts/Switcher/json',
        dataType: 'json',
        type: 'POST',
        success: function(data) {
            qna.Populate(data);
            qna.DoSwitch('qna');
        },
        error: function(data) {
            //console.log(data.responseText);
        }
    });
}

if($('.js-placeholder').length > 0) {
    var prod = new Switcher;
    var elem = $('.js-placeholder')[1];

    prod.ParseOutput(function(id) {
        var d = this._data[id];
        var html = '<table width="100%" cellspacing="0" class="question-switcher">' +
                   '<tr><th rowspan="2"><a href="index.php?q=Products/Details/'+d.product_id+'"><img src="'+d.link+'" align="top"></a></th>' +
                   '<td class="title">'+d.product_name+'</td></tr><tr><td>'+d.desc+'</td></tr>' +
                   '</table>';
        $(elem).html(html);
    });

    $.ajax({
        url: 'index.php?q=Products/Switcher/json',
        dataType: 'json',
        success: function(data) {
            prod.Populate(data);
            prod.DoSwitch('prod');
        },
        error: function(data) {
            //console.log(data.responseText);
        }
    });

}

/**
 * Product Image Magnifier
 */
if($('.product-image').length > 0) {

    $.each($('.product-image img'),function(i,x) {
        $(x).hover(function(e){
            $(this).prev().show();
        },
        function(e){
            $(this).prev().hide();
        });
    });
}


/**
 * ROI Calculator
 */
if($('#roi-calc').length > 0) {
    $('#sidebar').remove();
    $('#main-content').css('width','100%');

    var roicalc = {
        txtIndustry: {
            automotive: [15000,46722,85200]
            , foodnbev: [16420, 46722, 85200]
            , plastic: [7600, 46722, 85200]
            , machinery: [24700, 46722, 85200]
            , metals: [23000, 46722, 85200]
            , cellular: [14000, 46722, 85200]
            , telephone: [72000, 46722, 85200]
            , airline: [90000, 46722, 85200]
        }
        , txtSystems: {
            basic: 6000
            , medium: 24000
            , large: 60000
            , ultimate: 100000
        }
        , to_currency: function(num,sym,del) {
            
            sym = sym || '$';
            del = del || ',';
            num = (Math.abs(num)+'').split('');     // corerce number into string[]
            if(num.length > 21)                     // number too long? Scientific notation
                return sym+num.join('');
            for(var i = 1, l = num.length, splits = Math.floor(l/3); i <= splits; ++i)
                num.splice(l-(3*i),0,del);
            return sym+((num[0]===del)?num.slice(1):num).join('');
            
           return num;
        }
        , to_int: function(currency,sym,del) {
            currency+='';
            sym = sym || '$';
            del = del || ',';
            
            var no_sym = (currency.charAt(0) === sym)?currency.slice(1):currency;
            no_sym = no_sym.split(del).join('');
            
            return parseInt(no_sym);
        }
        , calculate: {
            tic: function() {
                var _1 = roicalc.to_int($('#roi-calc_ia-interruption-cost').val())
                    , _2 = parseInt($('#roi-calc_txtia-hours-down').val()) || 0
                    , _3 = roicalc.to_int($('#roi-calc_txtia-avg-equip-damage').val())
                    , _4 = roicalc.to_int($('#roi-calc_txtia-avg-lost-time').val())
                    , _5 = roicalc.to_int($('#roi-calc_txtia-other-costs').val().split(',').join('')) || 0
                    , _tic = _1*_2 + (_3+_4) + _5;
                        
                    $('#roi-calc_txtia-total-costs').val(roicalc.to_currency(_tic));
                    return _tic;
            }
            , payback: function(){
                var system = parseInt(roicalc.txtSystems[$('#roi-calc_txtHrgSystem').val()])
                    , total = (system/roicalc.to_int($('#roi-calc_txtia-total-costs').val())) * 12 || 0;

                $('#roi-calc_txtia-payback').val(Math.ceil(total));
                return total;
            }
            , tpp: function(tic) {
                var system = parseInt(roicalc.txtSystems[$('#roi-calc_txtHrgSystem').val()])
                    , has_arc = $('#roi-calc_chkHRG').prop('checked')
                    , _tic = roicalc.calculate.tic()
                    , total;

                total = ((system+6100)/_tic)*12;
                $('#roi-calc_txtia-total-payback').val(Math.ceil(total));
            }
        }
        , init: function() {
            $('#roi-calc_txtIndustry').change(function(e){
                var entry = roicalc.txtIndustry[$(this).val()];
                if(entry !== undefined) {
                    $('#roi-calc_ia-interruption-cost').val(roicalc.to_currency(entry[0]));
                    $('#roi-calc_txtia-avg-equip-damage').val(roicalc.to_currency(entry[1]));
                    $('#roi-calc_txtia-avg-lost-time').val(roicalc.to_currency(entry[2]));

                    $('#roi-calc_yf-interruption-cost').val(roicalc.to_currency(entry[0]));
                    $('#roi-calc_txtyf-avg-equip-damage').val(roicalc.to_currency(entry[1]));
                    $('#roi-calc_txtyf-avg-lost-time').val(roicalc.to_currency(entry[2]));

                    roicalc.calculate.tic();
                    roicalc.calculate.payback();
                    roicalc.calculate.tpp();
                }
            });

            $('[id^=roi-]').blur(function(e){
                var tic = roicalc.calculate.tic();
                roicalc.calculate.payback();
                roicalc.calculate.tpp();
            });

            $('#roi-calc_chkHRG').change(function(e){
                if($(this).prop('checked')) {
                    $('#roi-calc_txtia-falcon-costs').val(roicalc.to_currency(6100));
                }
                else {
                    $('#roi-calc_txtia-falcon-costs').val(roicalc.to_currency(0));
                }
                roicalc.calculate.tpp();
            });

            $('#roi-calc_txtHrgSystem').change(function(e){
               var entry = roicalc.txtSystems[$(this).val()];
               if(entry) {
                   $('#roi-calc_txtia-hrg-system').val(roicalc.to_currency(entry));
               }
            });
        }
    }

    roicalc.init();
}
