﻿// Easing equation, borrowed from jQuery easing plugin
// http://gsgd.co.uk/sandbox/jquery/easing/
jQuery.easing.easeOutQuart = function(x, t, b, c, d) {
    return -c * ((t = t / d - 1) * t * t * t - 1) + b;
};

function initNav() {

    var sub_nav = $('#main_nav li.more');
    
    // show/hide sub nav
    sub_nav.mouseover(function() {
        $(this).addClass('active');
    });
  
    sub_nav.mouseout(function() {
        $(this).removeClass('active');
    });
}

function initTabs() {
    var tabs = $('#tabs_list li');
    var hash = window.location.hash;
	(!hash) ?  hideAllExcept('#' + $('#tab_toggle div.tab_wrapper:first').attr('id')) : hideAllExcept(window.location.hash);

	$('a.toggle').click(function(e) {
		var href = $(this).attr('href');
		hideAllExcept(href);
		return false; //don't scroll to tab content
	});
}

function initPulldowns() {

	$('.pulldown').hide();

    $('.pulldown-handle').click(function(){
        var drawer = '#' + this.parentNode.id + '-pulldown';
        $('.pulldown:visible').slideUp(200); //close any open drawers
        $('div.arrow').removeClass('arrowon');
        $('div.title').removeClass('red');
        //if this drawer is closed, open it. if it was open, don't reopen it.
        if ($(drawer + ':visible').length == 0) {
			$(drawer).slideDown(200);
		    $(this).addClass('arrowon');
		}
		
       return false; 
    });

}

function initContactForm() {
    jQuery.validator.messages.required = "*";
    jQuery.validator.messages.email = "*";
    jQuery.validator.messages.equalTo = "*";
    
    $('#uiQuestionsSubmit').click(function() {
        var d = "{'firstname':'" + escape($('#uiQuestionsFirstName').val()) + "'" + 
            ",'lastname': '" +  escape($('#uiQuestionsLastName').val()) + "'" +
            ",'email': '" + escape($('#uiQuestionsEmail').val())  + "'" +
            ",'confirm': '" + escape($('#uiQuestionsConfirmEmail').val())  + "'" +
            ",'address': '" + escape($('#uiQuestionsAddress').val())  + "'" +
            ",'city': '" + escape($('#uiQuestionsCity').val())  + "'" +
            ",'state': '" + escape($('#uiQuestionsState').val())  + "'" +
            ",'zipcode': '" + escape($('#uiQuestionsZipCode').val())  + "'" +
            ",'phone': '" + escape($('#uiQuestionsPhoneNumber').val())  + "'" +
            ",'message': '" + escape($('#uiQuestionsMessage').val())  + "'" +
            ",'subject': '" + escape(document.getElementById('uiQuestionsSubject').options[document.getElementById('uiQuestionsSubject').selectedIndex].value) + "'" +
            "}";
            
        var test = eval('(' + d + ')');
        
        $("#cForm").validate();

        if($("#cForm").valid()) {
            jQuery.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                data: d,
                url: '/webservices/scriptservices.asmx/ContactUs',
                timeout: 10000,
                dataType: "json",
                    error: function(xml) {
                        alert(xml);
                    },
                    success: function(r) { 
                        $('#contactForm').hide();
                        $('#contactThanks').show();                        
                   }
            });
        }
    });
    
    $('#uiQuestionsClear').click(function() {
        $('#uiQuestionsFirstName').val('');
        $('#uiQuestionsLastName').val('');
        $('#uiQuestionsEmail').val('');
        $('#uiQuestionsConfirmEmail').val('');  
        $('#uiQuestionsConfirmAddress').val('');
        $('#uiQuestionsConfirmCity').val('');
        $('#uiQuestionsConfirmState').val('');
        $('#uiQuestionsConfirmZipCode').val('');
        $('#uiQuestionsPhoneNumber').val('');
        $('#uiQuestionsMessage').val('');
        document.getElementById('uiQuestionsSubject').selectedIndex = 0;
        
    });
}

function initRollover() {

    $('.rollover').hover(function() {
        this.src = this.src.replace(/.gif/, "_on.gif");
    }, function() {
        this.src = this.src.replace(/_on/, "");
    });
    
    $('.rollover').click(function() {
        this.src = this.src.replace(/_on/, "");
    });

}

function initModals() {

    $('#ModalWindow').jqm({
        ajax:'@href',
        trigger:'a.showmodal',
        onLoad: setModal,
        onHide: hideModal
    });

    $('#RecommenderWindow').jqm({
        ajax:'/RecHolder.aspx',
        trigger:'a.showrec',
        overlay:50
    });
    
}

function initButtons() {

    var buttons = $(':button:visible');
    var submits = $(':submit:visible');
    
    $.extend(buttons, submits);
    
    buttons.each(function() {
        
        
        var r = $(this);
        if(!r.hasClass('notransform')) {
            var o = $('<div class="pevonia-button"><a href="javascript:void(0);">' + $(this).val() + '</a></div>');
            o.width (($(this).val().length * 6) + 22);
            
            $(this).hide();
            
            var newButton = $(this).parent().append(o);
            $(o).click(function() {
                r.trigger('click');
            });
        }
    });
    
    
}

function initSelects() {
    $('select:not(.standard)').selectbox();
    
}

function globalInit() {
    
    initButtons();
    initSelects();
    initNav();
    initTabs();
    initRollover();
    initModals();

    var $news = $('#news-ticker'); //we'll re use it a lot, so better save it to a var.
    var newsIdx = 0;
    var $defaultItem = $news;
    
    $news.serialScroll({
        items: 'div',
        duration: 1000,
        lock:false,
        force: true,
        axis: 'y',
        easing: 'linear',
        lazy: true, // NOTE: it's set to true, meaning you can add/remove/reorder items and the changes are taken into account.
        interval: 5000, // yeah! I now added auto-scrolling
        step: 1, // scroll x news each time,
        cycle:false, // cycle endlessly ( constant velocity )
		constant:true,
		onBefore: function(elem){
		    
		    if(newsIdx < 100) {
		        $item = $news.children("div")
		        $($item[newsIdx]).clone().appendTo($news);
		        
			    newsIdx++; 
		    }		    
		}
    });	

    try
    {
        initPulldowns();
    }catch (e) { }
    
    $('img.closebutton').click(function() {
        var holder = '#' + this.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.id;
        $(holder).fadeOut(200);
    });
    
    var config = {
        sensitivity:3,
        interval:200,
        over:function() {
            var drawer = '#' + this.id + 'Popup';
            $(drawer).fadeIn(200);
        }, 
        out:function() {
            var drawer = '#' + this.id + 'Popup';
            $(drawer).fadeOut(200);
        },
        timeout: 500
    };
    
    $('.popupover-handle').hoverIntent(config);
    $('.popupclick-handle').click(function() {
        var drawer = '#' + this.id + 'Popup';
        $('.popup').fadeOut(100);
        var offset = $(this).position();
        var width = $(this).width();
                
        $(drawer).css({left:(offset.left - $(drawer).width() + 100 + (width/2)), top:(offset.top + 10)});
        $(drawer).fadeIn(200);
    });
    
    $('.taf-handle').click(function() {
        var drawer = '#TAFPopup';
        $('.popup').fadeOut(100);
        var offset = $(this).position();
        var width = $(this).width();
        
        $(drawer).css({left:(offset.left - 340 + (width/2)), top:(offset.top + 10)});
        $(drawer).fadeIn(200);
        
    });
    
    $('.resetTAF').click(function() {
        $('#TAFContent').show(400);
        $('#TAFPanel').hide(200);
        $('#tafForm')[0].reset();
    });
    
    
    $('.quicklink').hoverIntent({
        sensitivity:3,
        interval:100,
        over:function() {
            var quick = $($(this).find('a:first').attr('href'));
            
            var position = $(this).position();
            var winT = position.top;
            var winL = position.left;
            var winH = $(quick).height();
            
            if(winL < 95) 
                winL = 95;
            
            $(quick).css({top: (winT - winH), left:(winL - 100)});
            $(quick).show();        
        }, 
        out:function() {
            var quick = $($(this).find('a:first').attr('href'));        
            $(quick).hide();        
        }
    });
    
    $('#tafSub').click(function () {
        checkValues(''); 
    });
    
    $('.feature').hover(function() {
            $(this).parent().parent().addClass('featureRollover');
        }, function() {
            $(this).parent().parent().removeClass('featureRollover');
        }
    );
}


$(document).ready(function() {
    globalInit();
});



function closeRecommendor() {
    $('#RecommenderWindow').jqmHide();
}

function hideAllExcept(el) {

    if(el[0] != '#') {
        el = '#' + el.split('#')[1];
    }

   $('#tab_toggle .tab_wrapper').addClass('hide');
   $(el).removeClass('hide');

   $('a.toggle').parent('li').removeClass('selected');
   $('a[href="' + el + '"]').parent('li').addClass('selected');
    
}

function hideModal() {
    $('#ModalWindow').hide();
    $('#ModalWindow').html('');
    $('.jqmOverlay').remove();
    
}

function setModal() {

   var w = $('#ModalWindow .scroll div:first').innerWidth(); 
   
   if (!w || w > 800 || w == 0) {
    w=800;
   }
   
   if(w < 400) {
    w = 400;
   }
   
   w+=50;
   
   
   $('#ModalWindow .modal').css({width:w, maxWidth:w});
   $('#ModalWindow .modal_br').css({width:(w - 18), maxWidth:(w - 18)});
   
   $('#ModalWindow').css({left:'50%', marginLeft:w/2*-1});
    
}

function submitTAF(formid) {
    
    var ourForm = $('#' + formid);
    
    var inputs = [];

    $(':input', ourForm).each(function() {
        inputs.push('"' + this.name + '":"' + escape(this.value) + '"');
    });
    var json_data = '{' + inputs.join(',') + '}';
    
    $.ajax({
        dataType: "json",
        type: "POST",
        url: "/services/ajaxmethods.asmx/TellAFriend",
        data: json_data,
        success: function(s) {
            if(s.value) {
                $('#TAFContent').hide();
                $('#TAFPanel').show();
            }
        }
    }); 
    
}

function checkEnter(e){ //e is event object passed from function invocation
    var characterCode; 

    if(e && e.which){ //if which property of event object is supported (NN4)
        e = e
        characterCode = e.which //character code is contained in NN4's which property
    }
    else{
        e = event
        characterCode = e.keyCode //character code is contained in IE's keyCode property
    }

    if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
        return true
    }
    else{
        return false
    }

}
//---Top Nav Search "Enter Button" Support---
$(document).ready(function() {
    $('#top_nav_search_text').keyup(function(e) {
          if(e.keyCode == 13) {
                window.location.href='/searchresults.aspx?s=' + $('#top_nav_search_text').val();
          }

    });
});