/*

	Filename             sitewide.js
	Detail               Site functionality
	Author:              thunder::tech inc.
	License:             CLIENT is defined as the owner of online property from which this file resides or this code is referenced in.
						 ADDITIONAL PARTY is defined as anyone other than thunder::tech or CLIENT.
						 No right is granted to ADDITIONAL PARTY to sell, distribute, modify or otherwise transfer the following source code without explicit written permission by CLIENT or thunder::tech.

*/

/*  ================================
     Sitewide JavaScript
    ================================ */
var comparer = '/comparehandler.ashx';
var Project = {};
Project.topMenuItems;
Project.topMenuDropdown;
Project.isIE = false;
Project.currentBannerImage = 0;
Project.bannerImageCount = 1;
Project.bannerTimer;
Project.bannerInterval = 10000;

Project.pageLoaded = function () {
    //thunder.client.project.flashReplace();
    //thunder.client.modify.rollImages();
    //thunder.client.modify.linkOptions();
    //thunder.client.modify.tabSet();
    thunder.client.modify.treeMenu(false);
    //thunder.client.modify.treeMenu(false, [thunder.client.modes.separatorTreeMenu]);
    //thunder.client.modify.treeMenu(false, [thunder.client.modes.imageTreeMenu]);
    thunder.client.modify.selfLabelFields();
    //thunder.client.modify.requireFields();
    //thunder.client.modify.dropSelector(true);
    //thunder.client.modify.scrollFeature(640, 3000, 500);
    $('.menu-item').mouseenter(Project.handleMenuMouse).mouseleave(Project.handleMenuMouse);
    $('.menu-item').find('.menu-dropdown').find('.dropdown-mid').children('*').mouseenter(Project.handleDropdownMouse).mouseleave(Project.handleDropdownMouse)
    $('.page').find('.side-menu').children('.mid').children('.side-menu-item-on').each(Project.handleSideMenuMouse);
    $('.page').find('.inventory-container').find('.inventory-item').children('.pic').click(Project.handleInventoryMouseEnter);
    $('.page').find('.inventory-container').find('.inventory-item').mouseleave(Project.handleInventoryMouseLeave);
    $('.page').find('.inventory-container').find('.inventory-item:last-child').css({ 'border-bottom': 'none' });
    thunder.client.workarounds.alphaImages();
    thunder.client.workarounds.labelAsBrowser();
    $('.page').find('.home-menu').children('.home-menu-item').mouseenter(Project.handleHomeMenuItemMouse).mouseleave(Project.handleHomeMenuItemMouse);
    $('.page').find('.home-menu').children('.home-menu-item').children('.overstate').children('.dark').each(Project.initHomeMenuOverstateBack).mouseenter(Project.forceHomeMenuItem);
    Project.topMenuItems = $('.header').find('.header-top-menu-container').children('.top-menu').children('.top-menu-item-container').children('.top-menu-item');
    Project.topMenuItems.mouseenter(Project.handleTopMenuItemMouse).mouseleave(Project.handleTopMenuItemMouse);
    Project.topMenuDropdown = $('.header').find('.header-top-menu-container').children('.top-menu').children('.top-menu-item-container').parent().children('.dropdown-container');
    $('.header').find('.header-top-menu-container').mouseleave(Project.handleTopMenuContainerMouse);
    Project.isIE = navigator.userAgent.search("MSIE") >= 0 ? true : false;
    $('.header-search-input').focusin(Project.handleInputFocus).focusout(Project.handleInputFocus);

    //$('.contact-input').focusin(Project.handleInputFocus).focusout(Project.handleInputFocus);

    $('.footer-email-input').focusin(Project.handleEmailInputFocus).focusout(Project.handleEmailInputFocus);
    $('.product-page').find('.pic-container').children('.pic-small').click(Project.handlePicSmallClick);
   // $('.product-page').find('.contact-input').focusin(Project.handleProductInputFocus).focusout(Project.handleProductInputFocus);
    $('.product-page').find('.contact-textarea').focusin(Project.handleProductTextareaFocus).focusout(Project.handleProductTextareaFocus);
    $('.inv-item').mouseenter(Project.handleInventoryItemMouse).mouseleave(Project.handleInventoryItemMouse);

    Project.bannerImageCount = $('.home-image-container').children('.home-image-content').children('.hidden-content').size();
    if (Project.bannerImageCount > 1) {
        Project.bannerTimer = setInterval('Project.nextBannerImage()', Project.bannerInterval);
        $('.home-image-container').children('.image').css({ 'opacity': '0' });
        Project.doBannerImage();
    }
    else {
        $('.home-image-container').children('.image').css({ 'opacity': '0' });
        Project.doSubBannerImage();
    }


    if ($("#ctl00_ContentPlaceHolder1_unitnumber").length > 0) {
        Project.autocomplete("#ctl00_ContentPlaceHolder1_unitnumber", "unitnumber");
//        Project.autocomplete("#ctl00_ContentPlaceHolder1_length", "length");
//        Project.autocomplete("#ctl00_ContentPlaceHolder1_productyear", 'productyear');
        Project.autocomplete("#ctl00_ContentPlaceHolder1_year_low", 'productyear');
        Project.autocomplete("#ctl00_ContentPlaceHolder1_year_high", 'productyear');
//        Project.autocomplete("#ctl00_ContentPlaceHolder1_reardoor", 'reardoor');
//        Project.autocomplete("#ctl00_ContentPlaceHolder1_suspension", 'suspen');
//        Project.autocomplete("#ctl00_ContentPlaceHolder1_arspr", 'ar_spr');
//        Project.autocomplete("#ctl00_ContentPlaceHolder1_exterior", 'exter');
//        Project.autocomplete("#ctl00_ContentPlaceHolder1_roof", 'roof');
//        Project.autocomplete("#ctl00_ContentPlaceHolder1_posts", 'posts');
//        Project.autocomplete("#ctl00_ContentPlaceHolder1_interior_package", 'interior_package');
//        Project.autocomplete("#ctl00_ContentPlaceHolder1_make", 'make');
//        Project.autocomplete("#ctl00_ContentPlaceHolder1_model", 'model');
    }

    Project.enterkey($("#search"),$("#searchbtn"));
    Project.enterkey($("#ctl00_NewsletterControl1_TextBox1"),$("#ctl00_NewsletterControl1_ImageButton1"));

}
Project.enterkey = function (item, btn) {

    $(item).keypress(function (e) {
        if (e.which == 13 && enterglobe == false) {
            enterglobe = true;
            $(btn).click();
            return false;
        }
    });

}
Project.nextBannerImage = function()
{
	if( Project.currentBannerImage < Project.bannerImageCount - 1 )
	{
		Project.currentBannerImage ++;
	}
	else
	{
		Project.currentBannerImage = 0;
	}
	
	$('.home-image-container').children('.image').stop( true,false ).animate( {'opacity':'0'}, 400, function(){
		Project.doBannerImage();
	} );
	
	$('.home-image-container').children('.home-image-content').stop( true,false ).animate( {'opacity':'0'}, 300);
	
	if( Project.isIE )
	{
		$('.home-image-container').children('.arrow-overflow').children('.arrow').css({'left':'-1200px'});
	}
	else
	{
		$('.home-image-container').children('.arrow-overflow').children('.arrow').stop(true,false).animate({left:'100px', opacity:0}, 300);
	}
	
	//Project.bannerTimer = setInterval( 'Project.nextBannerImage()', Project.bannerInterval );
}

Project.doBannerImage = function()
{
	Project.doBannerPicture();
	Project.doBannerArrow();
}

Project.doSubBannerImage = function()
{
	Project.doSubBannerPicture();
	Project.doBannerArrow();
}

Project.doBannerArrow = function()
{
	if( Project.isIE )
	{
		$('.home-image-container').children('.arrow-overflow').children('.arrow').stop(true,false).css({'left':'-1200px'}).animate({left:'0px'}, 800, function(){
			Project.doBannerText();
		});

	}
	else
	{
		$('.home-image-container').children('.arrow-overflow').children('.arrow').stop(true,false).css({'opacity':'0','left':'-1200px'}).animate({left:'0px', opacity:1}, 800, function(){
			Project.doBannerText();	
		});
	}
}

Project.doSubBannerPicture = function()
{
	var t = $('.home-image-container').children('.image');
	t.animate( {'opacity': '1'}, 400 );
}

Project.doBannerPicture = function()
{
	var t = $('.home-image-container').children('.image');
	t.children('*').attr('src', '/themes/main/images/home-image-'+ (Project.currentBannerImage + 1).toString() + '.jpg' );
	t.animate( {'opacity': '1'}, 400 );
}

Project.doBannerText = function()
{
	var t = $('.home-image-container').children('.home-image-content');
	var hiddens = t.children('.hidden-content');	
	//alert( 
	t.children('.active-content').html( hiddens.eq( (Project.currentBannerImage ) ).html() );
	t.stop( true,false ).animate({opacity:1}, 400);
}

Project.handleInventoryItemMouse = function( event )
{
	if( Project.isIE )
	{
		return;
	}
	if( event.type == "mouseenter" )
	{
		$('.inv-item').not($(this)).stop(true,false).animate({'opacity':'0.7'}, 300);	
	}
	else
	{
		$('.inv-item').stop(true,false).animate({'opacity':'1'}, 300);
	}
}

Project.handleProductTextareaFocus = function( evt )
{
	var t = $(this);
	if( evt.type == "focusin" )
	{
		if( t.val() == t.attr('original') ) 
		{	
			t.val("");
		}
	}
	else
	{
		if( t.val().length == 0 ) 
		{
			t.val( t.attr('original') );
		}
	}
}

Project.handleProductInputFocus = function( evt )
{
	var t = $(this);
	if( evt.type == "focusin" )
	{
		if( t.val() == t.attr('original') ) 
		{	
			t.val("");
		}
	}
	else
	{
		if( t.text() == "" ) 
		{
			t.val( t.attr('original') );
		}
	}
}

Project.handlePicSmallClick = function( event )
{
	var t = $(this);
	t.parent().find('.pic-big').fadeOut('fast');
	t.parent().find('.pic-big').attr('src', t.attr('large') );
	t.parent().find('.pic-big').fadeIn('fast');
}

Project.handleInventoryMouseEnter = function( event )
{
	$('.page').find('.inventory-container').find('.inventory-item').css({'z-index':'1000'});
	$(this).parent().css({'z-index':'1001'});
	var rollover = $(this).parent().children('.rollover');
	if( rollover.size() == 0 )
	{
		return;	
	}

	rollover.css(	{'opacity':'0','display':'block'});
	//animate opacity in
	rollover.stop( true, false ).animate( {opacity:1}, 300);
	
	
}

Project.handleInventoryMouseLeave = function( event )
{
	$('.page').find('.inventory-container').find('.inventory-item').css({'z-index':'1000'});
	$(this).css({'z-index':'1001'});
	var rollover = $(this).children('.rollover');
	if( rollover.size() == 0 )
	{
		return;	
	}
	
	rollover.stop( true, false ).animate( {opacity:0}, 300, function(){rollover.css({'display':''});} );
	
}

Project.handleTopMenuContainerMouse = function( event )
{
	dropdownContent = null;
	Project.topMenuDropdown.html( dropdownContent );
	Project.handleTopMenuItemMouse( event );
}

Project.handleTopMenuItemMouse = function( event )
{
	var dropdownContent = dropdownContent = $(this).children('.dropdown').html();
	//style menu elements
	if( event.type == "mouseenter" )
	{
		Project.topMenuItems.children('*').css({'color':'', 'text-decoration':'none', 'font-weight':'normal'});
		Project.topMenuItems.not(this).children('*').css({'color':'#999999'});
		$(this).children('*').css({'color':'#9A0134', 'text-decoration':'underline', 'font-weight':'bold'});
		dropdownContent = $(this).children('.dropdown').html();
		Project.topMenuDropdown.html(dropdownContent);

		var r = parseInt($(this).children('.dropdown').attr('thunder:right'));

		if (r) {
		    Project.topMenuDropdown.css({ 'right': r.toString() + 'px' });
		}
		else {
		    Project.topMenuDropdown.css({ 'right': '' });
		}



	}
	else
	{
		if( dropdownContent == null )
		{
			Project.topMenuItems.children('*').css({'color':'', 'text-decoration':'none', 'font-weight':'normal'});
		}
		else
		{
			
		}
	}
	
	//show/hide dropdown
	
	
}

Project.forceHomeMenuItem = function( event )
{
	$(this).parent().parent().trigger('mouseleave');
	//Project.handleHomeMenuItemMouse( event )
}

Project.initHomeMenuOverstateBack = function( i, obj )
{
	var thisLeft = -1 * $(obj).parent().parent().position().left;
	if( i != 0 ){thisLeft += 9;}
	$(obj).css({'left':thisLeft});
}

Project.handleHomeMenuItemMouse = function( event )
{
	$('.page').find('.home-menu').children('.home-menu-item').css({'z-index':'1000'});
	$(this).css({'z-index':'1500'});
	var overstate = $(this).children('.overstate');

	if( event.type == "mouseenter" )
	{
		if( Project.isIE )
		{
			//opacity was making IE7 freak out
			overstate.css({'display':'block'});
		}
		else
		{
			overstate.css({'opacity':'0', 'display':'block'});
			overstate.stop( true,false ).animate( {'opacity': 1}, 200 );
		}
	}
	else
	{
		if( Project.isIE )
		{
			//opacity was making IE7 freak out
			overstate.css({'display':'none'});
		}
		else
		{
			/*overstate.stop( true,false ).animate( {'opacity': 0}, 200, function(){
				overstate.css({'display':''});
			 });*/
			 overstate.css({'display':'none'});
		}
	}
	/*overstate.stop( true,false ).animate( {'opacity': event.type == "mouseenter" ? 1 : 0}, 200, function(){
		if( event.type == "mouseleave" )
		{
			overstate.css({'display':''});
		}
	 });*/
}

Project.handleDropdownMouse = function( event )
{
	var newTop = $(this).position().top + 9;
	var dot = $(this).parent().find('.hover-dot');
	dot.css({'top':newTop.toString() + 'px', 'display': event.type == "mouseenter" ? 'block' : ''});
}

Project.handleSideMenuMouse = function( i, obj )
{
	var newTop = $(obj).position().top + 9;
	var dot = $(obj).parent().find('.hover-dot');
	dot.css({'top':newTop.toString() + 'px', 'display': 'block'});
}

Project.handleMenuMouse = function( event )
{
	$(this).find('.menu-item-over').css({'display':event.type == 'mouseenter' ? 'block' : '' });
	if( event.type == 'mouseenter' )
	{
		$(this).find('.menu-dropdown').addClass('menu-dropdown-on');
		$(this).addClass('menu-item-on');
	}
	else
	{
		$(this).find('.menu-dropdown').removeClass('menu-dropdown-on');
		$(this).removeClass('menu-item-on');
	}
}

Project.handleInputFocus = function( evt )
{
	if( evt.type == "focusin" )
	{
		if( $(this).val() == "search our site" ) 
		{	
			$(this).val("");
		}
	}
	else
	{
		if( $(this).val() == "" ) 
		{
			$(this).val("search our site");
		}
	}
}

Project.handleEmailInputFocus = function( evt )
{
	if( evt.type == "focusin" )
	{
		if( $(this).val() == "enter e-mail address" ) 
		{	
			$(this).val("");
		}
	}
	else
	{
		if( $(this).val() == "" ) 
		{
			$(this).val("enter e-mail address");
		}
	}
}

Project.flashReplace = function()
{
	var so;
	so = new SWFObject("/themes/main/flash/swf1.swf", "swf-obj-1", "300", "250", "9", "");
	so.addParam("quality", "high");
	so.addParam("wmode", "transparent");
	so.write("swf-holder-1");
}

Project.contactTSI = function (inventoryid) {
    
    $(this).jBox().showWindow('<iframe src="/dialogs/contact.aspx?inventoryid=' + inventoryid + '" frameborder="0" id="contactframe" border="0"></iframe>');

}

Project.siteSearch = function () {

    window.location = '/search.aspx?s=' + $("#search").val();

}

//compare items
Project.compare = function (box, inventoryid) {
    action = '';

    if ($(box).is(':checked')) {
        action = 'addCompare';
    }
    else {
        action = 'removeCompare';
    }


    $.ajax({
        //       type: "GET",
        dataType: 'json',
        url: comparer + '?action=' + action + '&inventoryid=' + inventoryid,
        complete: function () {
           
        },
        success: function (data) {
             showmsg("<h2>Compare list has been modified. <br><br><a href='/compare.aspx'>Compare Now</a></h2>");
            $('#comparelink').show("fast");


        }
    });


}

//immediately remove the column from the compare table
Project.removeColumn = function (el) {
    var cell = $(el);
    var index = 0;
    var found = null;
    cell.parent().parent('tr').children('td').each(function () {
        //alert($(this).html());

        if (cell.parent()[0] == $(this)[0]) {
            found = index;
        } //alert(index);
        index = index + 1;
    }
    );

    cell.parents("table").find("tr").each(function () {
        $(this).find("td:eq(" + found + ")").fadeOut('slow');
    });

}

///remove an item from the compare list
Project.compareRemove = function (inventoryid, el) {

    $.ajax({
        //       type: "GET",
        dataType: 'json',
        url: comparer + '?action=removeCompare&inventoryid=' + inventoryid,
        complete: function () {
          //  showmsg("<h2>Item has been removed from your compare list</h2>");
            Project.removeColumn(el);
        },
        success: function (data) {


        }
    });

} 

//JBOX SHOW MESSAGE DEPENDENCY jquery.jbox.js
function showmsg(message) {
    //alert(message);
    //var msg =
    $(this).jBox().showWindow('<div id="msgbox">' + message + '</div>');
    //  setTimeout(msg.close, 5000);

}


//    ///AUTOCOMPLETE
function findValue(li) {
    if (li == null) return alert("No match!");

    // if coming from an AJAX call, let's use the CityId as the value
    if (!!li.extra) var sValue = li.extra[0];

    // otherwise, let's just display the value in the text box
    else var sValue = li.selectValue;

    // alert("The value you selected was: " + sValue);
}

function selectItem(li) {
    findValue(li);
}

function formatItem(row) {
    return row[0];
}

Project.autocomplete = function (el, name) {
    $(el).autocomplete(
    "/searchhelp.ashx",
        {
            delay: 10,
            minChars: 1,
            matchSubset: 1,
            matchContains: 1,
            cacheLength: 10,
            onItemSelect: selectItem,
            onFindValue: findValue,
            formatItem: formatItem,
            autoFill: true,
            width: 147,
            extraParams: { name: name }
        }
    );
}

Project.resetSearch = function () {

    $(':input')
        .not(':button, :submit, :reset, :hidden')
        .val('')
        .removeAttr('checked')
        .removeAttr('selected');
    return false;

}

//requires site.map.js 2011.4.1.0
Project.getDirections = function (location) {


    var m = $(this).thunderMap({"startpoint": $(location).val(), "endpoint" : '10499 Royalton Rd. Cleveland, Ohio 44133'});

    m.showDirections();


    //  setTimeout(msg.close, 5000);


}


ItemRequest = function () {
    // alert("whooo");
    //we send request out to handler
    var fname = $("#ctl00_ContentPlaceHolder1_ContactForm1_fname").val();
    var lname = $("#ctl00_ContentPlaceHolder1_ContactForm1_lname").val();
    var email = $("#ctl00_ContentPlaceHolder1_ContactForm1_email").val();
    var message = $("#ctl00_ContentPlaceHolder1_ContactForm1_comments").val();
    var numb = $("#itemid").val();
    var form = $("#ctl00_ContentPlaceHolder1_ContactForm1_Panel1");
    // alert(document.getElementById("prop_numb").value);
    // alert(numb);
    // return false;
    if (fname == '' || email == '' || lname == '') {
        alert('Please enter your name and email so we may follow up with you.');
        return false
    }
    form.html('<h2>Processing...Please wait.</h2>');
    // $("#wheel").show();
    var url = "/request.ashx?pn=" + numb + "&fname=" + fname + "&email=" + email + "&lname=" + lname + "&comments=" + message ;
       //alert(url);
    //    return false;
    $("#ctl00_ContentPlaceHolder1_ContactForm1_ImageButton1").hide();
    $.ajax({
        type: "GET",
        url: url,
        complete: function () {
            // $("#submit-btn").show();
            // $("#wheel").hide();
            form.html('<h2>Your request for additional information was successfully submitted. A Transport Services representative will respond to your request soon. Thank you.</h2>');
        },
        success: function (msg) {
            if (msg == '1') {
                //success

                //if we are plotting to a TBD then we throw in, if not, we swap
                form.html('<h2>Your request for additional information was successfully submitted. A Transport Services representative will respond to your request soon. Thank you.</h2>');

            }
            else {

                form.html('Sorry, please try again later. We are experiencing technical difficulties.');

            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {


            form.html('Sorry, please try again later. We are experiencing technical difficulties.');
        }
    });


    return false;

}


$(Project.pageLoaded);
