// ===============================// Main javascript file for West Tennessee Home Search // ===============================
// ===============================// by Bryan Dease for sodiumhalogen.com // ====================================
// ************ safe document ready loading ************ //	
jQuery(document).ready(function($)
 {
    // load up the cufon text replacement
    Cufon.replace('#content h1'); 
	Cufon.replace('body.home #content h2'); 
	Cufon.replace('body.home #content h3');
	Cufon.replace('blockquote p');
	
	// iframe the results page with ad blocks
	if ($('body').hasClass('search'))
	{
		$('a.iframe').iframe();
		// change the results page
		giveIdentity();
	}


	// slide the selected nav elements
	$('#nav li').hoverstay();

    // prepare the contact form
    if ($('#contact_form').length) {
        setForm('contact_form');
    }

    // prepare the image fader on the home page
    if ($('#slide-images').length) {
        $('#slide-images').cycle({
            fx: 'fade',
            delay: -3000,
            timeout: 7000,
            speed: 1700,
            pause: true
        });
		$('#slide-caption').cycle({
            fx: 'fade',
            delay: -3000,
            timeout: 7000,
            speed: 1700,
            pause: true,
            cleartypeNoBg: true
        });
    }
    
    // remove all inline style tags from the stupid yourmls inserts.  This is stupid.
	if ($('.listingsborder').length)
	{
    	$('style').remove();
	}
});

// window load funtion to make sure the images from the MLS search don't blink
$(window).load(function () {
  $('table').show();
});


// ===============================// Site Functions // ===============================

function setForm(formID)
 {
    // set options for ajaxing the contact form
    var options = {
        beforeSubmit: showRequest,
        success: showResponse
    };
    // hide the spam checking textbox
    $('#spam-check').hide();
    $('#' + formID).ajaxForm(options);
    // for usablilty you should never do this - but who cares?  It's my site and I hate the stupid FF outline on buttons.
    $('#submitbutton').mouseup(function() {
        this.blur();
    }).mouseout(function() {
        this.blur();
    });
}

function giveIdentity()
{
	$('strong:contains("Address")').parent().addClass('description_check').attr('width','245');
	$('table:contains("Currently")').attr('width','100%');
	$('img[alt^="Listing Photo"]').addClass('img_hero').attr({'width':216,'height':162});
	$('#YMLSSortTable img,#YMLSToolTableLinks img').remove();
	$('img[src^="/images"],img[src^="Http"],#ymlsSearchHeaderSpacer').remove();
	$('#imouter0').attr('id','search-menu');
	$('td[width="100"]').remove();
	$('td').attr({'onmouseout':'','onmouseover':''});
	$('.listingsborder2 a:contains("Save"),.listingsborder a:contains("Save")').addClass('save_link').siblings().remove();;
	$('a.save_link').parent().parent().parent().parent().attr('class','button_cluster');
	$('.button_cluster a:contains("Details")').addClass('detail_link').siblings().remove();
	$('.button_cluster a:contains("Inquire")').addClass('inquire_link').siblings().remove();
	$('a[href="#MainImage"]').parent().removeAttr('nowrap');
	$('a[name="MainPhoto"]').attr('id','main_photo').siblings().attr({'width':'300','height':'225'});
	$('#search-menu').remove();
	$('td.description_check').parent().next().children('td').addClass('description_also');
	$('td').removeAttr('noWrap');
	//$('#CFForm_1,#CFForm_2').parent().remove();
	if ($('a#main_photo').length)
	{
		$('div#content').addClass('detail_page');
		$('#main_photo').hide();
		$('a:contains("Inquire about this Listing")').attr('id','icon_inquire');
		$('a:contains("Add to Saved Listings")').attr('id','icon_add');
		$('a:contains("View/Manage Saved Listings")').attr('id','icon_manage');
		$('a:contains("My Assistant")').not('#search-menu a').attr('id','icon_assistant');
		$('a:contains("Email this page to a friend")').attr('id','icon_email');
		$('a:contains("Mortgage Calculator")').attr('id','icon_calculator');
		$('a:contains("Printer friendly version")').attr('id','icon_print');
		$('a:contains("See a map of this listing")').attr('id','icon_map');
	}
	if ($('#vcPassword').length)
	{
		$('div#content').addClass('sign_in');
		$('#form input[type="submit"]').addClass('submit');
		$('table[width="90%"],table[width="85%"]').attr('width','100%');
	}
}


// ************ functions for ajax forms ************ //
function showRequest(formData, jqForm, options) {
    if (ValidateForm() == false) {
        return false;
    }
    $('#submitbutton').val('sending...').css('backgroundColor', '#990000');
    return true;
}

function showResponse(responseText, statusText) {
    if (responseText == 'contact')
    {
        $('#submitbutton').val('Message Sent!').css('backgroundColor', '#C38F2C').wait(2).then.val('Contact Us');
    }
    else
    {
        $('#submitbutton').val('Request Sent!').css('backgroundColor', '#C38F2C');
        setTimeout(function() {
            tb_remove();
        },
        4000);
    }
    $('#form').resetForm();
}

// ************ some simple email validation ************ //
function echeck(str) {
    var at = '@';
    var dot = '.';
    var lat = str.indexOf(at);
    var lstr = str.length;
    var ldot = str.indexOf(dot);
    if (str.indexOf(at) == -1) {
        alert('Invalid E-mail Address');
        return false;
    }
    if (str.indexOf(at) == -1 || str.indexOf(at) == 0 || str.indexOf(at) == lstr) {
        alert('Invalid E-mail Address');
        return false;
    }
    if (str.indexOf(dot) == -1 || str.indexOf(dot) == 0 || str.indexOf(dot) == lstr) {
        alert('Invalid E-mail Address');
        return false;
    }
    if (str.indexOf(at, (lat + 1)) != -1) {
        alert('Invalid E-mail Address');
        return false;
    }
    if (str.substring(lat - 1, lat) == dot || str.substring(lat + 1, lat + 2) == dot) {
        alert('Invalid E-mail Address');
        return false;
    }
    if (str.indexOf(dot, (lat + 2)) == -1) {
        alert('Invalid E-mail Address');
        return false;
    }
    if (str.indexOf(' ') != -1) {
        alert('Invalid E-mail Address');
        return false;
    }
    return true;
}


// ************ make sure the fields are filled out properly ************ //
function ValidateForm() {
    var nameID = $('#name').val();
    if ((nameID == null) || (nameID == '')) {
        alert('Please Enter your First Name');
        $('#name').focus();
        return false;
    }
    var phoneID = $('#phone').val();
    if ((phoneID == null) || (phoneID == '')) {
        alert('Please Enter your Phone Number');
        $('#phone').focus();
        return false;
    }
    var emailID = $('#email').val();
    if ((emailID == null) || (emailID == '')) {
        alert('Please Enter your Email Address');
        $('#email').focus();
        return false;
    }
    if (echeck(emailID) == false) {
        $('#email').val('');
        $('#email').focus();
        return false;
    }
    var subjectID = $('#subject').val();
    if ((subjectID == null) || (subjectID == '')) {
        alert('Please Enter a Subject');
        $('#subject').focus();
        return false;
    }
    return true;
}

(function($)
 {
    $.fn.hoverstay = function()
    {
        return this.each(function()
        {
            var main_config = {
                sensitivity: 3,
                interval: 100,
                over: showSub,
                timeout: 100,
                out: hideSub
            };
            var sub_config = {
                sensitivity: 7,
                interval: 100,
                over: makeActive,
                timeout: 100,
                out: notActive
            };
            var subID = $('#' + $(this).attr('id') + '_sub')
            var $this = $(this);

            $this.hoverIntent(main_config);

            function showSub()
            {
                // unhide the subnavs
                $('div.subs').show();

                // clear all active menus
                $('#nav li').css('background-position', 'left top');

                subID.animate({
                    'top': '239px'
                },
                'fast').mouseover(function() {
					makeActive();
				}).mouseleave(function() {
					notActive();
				});
                $this.children('a').addClass('active');
            }

            function hideSub()
            {
                if (!subID.hasClass('activated'))
                {
                    subID.animate({
                        'top': '-31px'
                    },
                    'fast');
                    $this.children('a').removeClass('active');
                }
            }

            function makeActive()
            {
                subID.addClass('activated');
                $this.children('a').addClass('active');
            }

            function notActive()
            {
                subID.removeClass('activated');
                hideSub();
            }

        });
    }
})(jQuery);

// ************ replace fonts with Cufon ************ //
function loadCufon()
 {
    Cufon.replace('#content h1'); 
	Cufon.replace('body.home #content h2'); 
	Cufon.replace('body.home #content h3');
	Cufon.replace('blockquote p');
}

/**
* @author Remy Sharp
* @url http://remysharp.com/2007/01/25/jquery-tutorial-text-box-hints/
*/

 (function($) {

    $.fn.hint = function(blurClass) {
        if (!blurClass) {
            blurClass = 'blur';
        }

        return this.each(function() {
            // get jQuery version of 'this'
            var $input = $(this),

            // capture the rest of the variable to allow for reuse
            title = ($.cookie('search') != null) ? $.cookie('search') + ' search': 'model search';
            $form = $(this.form),
            $win = $(window);

            function remove() {
                if ($input.val() === title && $input.hasClass(blurClass)) {
                    $input.val('').removeClass(blurClass);
                }
            }

            // only apply logic if the element has the attribute
            if (title) {
                // on blur, set value to title attr if text is blank
                $input.blur(function() {
                    if (this.value === '') {
                        $input.val(title).addClass(blurClass);
                    }
                }).focus(remove).blur();
                // now change all inputs to title
                // clear the pre-defined text when form is submitted
                $form.submit(remove);
                $win.unload(remove);
                // handles Firefox's autocomplete
            }
        });
    };

})(jQuery);



// ************ 960 gridder settings ************ //
var gOverride = {
    urlBase: 'http://gridder.andreehansson.se/releases/latest/',
    gColor: '#333',
    gColumns: 12,
    gOpacity: 0.45,
    gWidth: 10,
    pColor: '#C0C0C0',
    pHeight: 15,
    pOffset: 108,
    pOpacity: 0.55,
    center: true,
    gEnabled: true,
    pEnabled: true,
    setupEnabled: true,
    fixFlash: true,
    size: 960
};
