//twitter feed
getTwitters('tweets', {
	id : 'agentace_com',
	count : 3,
	enableLinks : true,
	ignoreReplies : false,
	clearContents : true,
	newwindow : true,
	template : '%text% <br/><span class="meta"><a target="_blank" href="http://twitter.com/%user_screen_name%/statuses/%id_str%/">%time%</a></span>'
});

var ConfigOptions =
{
	autoCompleteUrl		: 'http://db.agentace.com/auto_complete',
	agentStatsUrl		: 'http://db.agentace.com/agent_stats',
	topAgentStatsUrl	: 'http://db.agentace.com/top_agent_stats',
	userContactUrl		: 'http://db.agentace.com/user_contact_info',
	userEnquiryUrl		: 'http://db.agentace.com/user_inquiry',
	fadeInTime			: 300,
	fadeOutTime			: 300
};

var AgentAce =
{
    /**
     * Data
     */
    contentUrls: {
        smallScreen		: 'wp-content/themes/agentace/app/smallscreen.php',
        largeScreen		: 'wp-content/themes/agentace/app/largescreen.php'
    },
	formUrls: {
		buyHome			: 'wp-content/themes/agentace/app/forms/buyhome.php',
        sellHome		: 'wp-content/themes/agentace/app/forms/sellform.php',
		invalid			: 'wp-content/themes/agentace/app/forms/invalid.php',
		noResult		: 'wp-content/themes/agentace/app/forms/noresult.php',
		outOfRange		: 'wp-content/themes/agentace/app/forms/outofrange.php',
		success			: 'wp-content/themes/agentace/app/forms/success.php'
	},

    /**
     * Properties
     */
    currentUrl: '',         // cache current url to prevent form reloading
    sliderObj: null,        // reference to the flexslider object instance
    formParameters: null,   // cached form parameters as submitted by the user in first step
    smallScreen: false,     // are we working on a small screen (single column layout)
    statsData: null,        // cache current stats data

	/**
	 ********************************************************************************************
	 * FORM VALIDATION
	 ********************************************************************************************
	 */

	/**
	 * General contact form validation
	 */
	generalContactFormValidation: function(onSubmit)
	{
		$('#general-contact').validate({
			rules: {
				full_name 	: { required: true, notPlaceholder:true },
				email		: { required: false, email: true },
				phone 		: { required: true, notPlaceholder:true, regex:'^\\(?[0-9]{3}\\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}$' },
				message		: { required: true, notPlaceholder:true }
			},
			messages: {
				full_name 	: {
					required		: 'Please provide your name',
					notPlaceholder	: 'Please provide your name'
				},
                email 		: {
                    email           : 'Please enter a valid email address.'
                },
				phone 		: {
					required		: 'we need either a phone number, or an email to contact you.',
					notPlaceholder	: 'we need either a phone number, or an email to contact you.',
                    regex           : 'Please enter a valid telephone number.'
				},
				message		: {
					required        : 'Please enter a message',
					notPlaceholder  : 'Please enter a message'
				}
			},
			submitHandler: function(form) {
				onSubmit();
			}
		});
	},

	/**
	 * Sell form validation
	 */
	sellFormValidation: function(onSubmit)
	{
		$('#sellform').validate({
			rules: {
				address 	: { required: true, notPlaceholder:true },
				price_range : { required: true }
			},
			ignore: "",
			messages: {
				address 	: {
					required		: 'Please enter your address or zipcode',
					notPlaceholder	: 'Please enter your address or zipcode'
				},
				price_range : { required: 'Please select your price range' }
			},
			submitHandler: function(form){
				onSubmit();
			}
		});
	},

	/**
	 * Buy form validation
	 */
	buyFormValidation: function(onSubmit)
	{
        $('#buyform').validate({
            rules: {
                address 	: { required: true, notPlaceholder:true },
                price_range : { required: true }
            },
            ignore: "",
            messages: {
                address 	: {
                    required		: 'Please enter your address or zipcode',
                    notPlaceholder	: 'Please enter your address or zipcode'
                },
                price_range : { required: 'Please select your price range' }
            },
            submitHandler: function(form){
                onSubmit();
            }
        });
    },

	/**
	 * Contact form validation
	 */
	contactFormValidation: function(onSubmit)
	{
		$('#contactinfo').validate({
			rules: {
				full_name 	: { required: true, notPlaceholder:true },
				email		: { required: false, email: true },
				phone 		: { required: true, notPlaceholder:true, regex:'^\\(?[0-9]{3}\\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}$' },
				best_time 	: { required: false },
				agree 		: { required: true }
			},
			ignore: "",
			messages: {
				full_name 	: {
					required		: 'Don\'t forget your name here',
					notPlaceholder	: 'Please provide your name'
				},
                email 	: {
                    email		    : 'Please enter a valid email address.'
                },
				phone 		: {
					required		: 'How can we call you?',
					notPlaceholder	: 'We a phone number to continue.',
					regex		    : 'Please enter a valid telephone number.'
				},
				agree 		: {
                    required: '...And the legal stuff, please.'
                }
			},
			submitHandler : function(form) {
				onSubmit();
			}
		});
	},

	/**
	 ********************************************************************************************
	 * STATS ANIMATION
	 ********************************************************************************************
	 */

	/**
	 * Sell stats form animation
	 */
	sellStatsAnimation: function(data)
	{
        var animData = {
            status: data.status,
            top_stats_volume: data.top_sell_stats.volume,
            avg_stats_volume: data.avg_sell_stats.volume,
            top_days_on_market: data.top_sell_stats.days_on_market,
            avg_days_on_market: data.avg_sell_stats.days_on_market
        };
        if (AgentAce.smallScreen) {
            AgentAce.agentStatsAnimation(animData);
        }
        else {
            AgentAce.topStatsAnimation(animData);
        }
	},

	/**
	 * Buy stats form animation
	 */
	buyStatsAnimation: function(data)
	{
        var animData = {
            status: data.status,
            top_stats_volume: data.top_buy_stats.volume,
            avg_stats_volume: data.avg_buy_stats.volume,
            top_days_on_market: data.top_buy_stats.days_on_market,
            avg_days_on_market: data.avg_buy_stats.days_on_market
        };
        if (AgentAce.smallScreen) {
            AgentAce.agentStatsAnimation(animData);
        }
        else {
            AgentAce.topStatsAnimation(animData);
        }
	},

    /**
     * Generic stats animation function
     */
    topStatsAnimation: function(data)
    {
        // Cache the stats data
        AgentAce.statsData = data;

        // Set the labels to zero
        $('#topstats #topagentlabel2').text(0);
        $('#topstats #avgagentlabel2').text(0);

        // Reset the width of the bar graph
        $('#topstats #topagent2').css({width: '0%'});
        $('#topstats #avgagent2').css({width: '0%'});

        // Hide the pie chart containers
        $('#topstats #topagentpie').fadeOut(ConfigOptions.fadeOutTime);
        $('#topstats #avgagentpie').fadeOut(ConfigOptions.fadeOutTime);
        $('#topstats #topweekslabel2').text('0');
        $('#topstats #avgweekslabel2').text('0');

        // Hide the submit buttons
        $('#topstatsform :submit').hide();

        // Only animate if AJAX call reports success
        if(data.status == 'success')
        {
            // Set the labels text
            var top_weeks = Math.round(data.top_days_on_market / 7);
            var avg_weeks = Math.round(data.avg_days_on_market / 7);

            // maximum bar width
            var max_bar_width = 69;

            // get volumes
            var top_vol = data.top_stats_volume;
            var avg_vol = data.avg_stats_volume;

            // calculate bar width as a ratio
            var top_bar_pct = 1.0;
            var avg_bar_pct = avg_vol / top_vol;

            // animate the bars and labels
            $('#topstats #topagent2').animate({
                    width: (max_bar_width * top_bar_pct) + '%'
                },
                {
                    duration: 1500 * top_bar_pct,
                    easing: 'linear',
                    step: function(now, fx){
                        $('#topstats #topagentlabel2').text(Math.round(top_vol * (now / (max_bar_width * top_bar_pct))));
                    },
                    complete: function(){
                        $('#topstats #topagentlabel2').text(top_vol);

                        $('#topstats #topagentpie').fadeIn(ConfigOptions.fadeInTime);
                        $('#topstats #avgagentpie').fadeIn(ConfigOptions.fadeInTime);
                        $('#topstats #topweekslabel2').text(top_weeks);
                        $('#topstats #avgweekslabel2').text(avg_weeks);

                        // Draw pie charts
                        AgentAce.drawPieCharts(
                            [top_weeks, 52 - top_weeks],
                            [avg_weeks, 52 - avg_weeks],
                            $('#topstats #topagentpie'),
                            $('#topstats #avgagentpie')
                        );

                        $('#topstatsform :submit').fadeIn(ConfigOptions.fadeInTime);
                    }
                });

            $('#topstats #avgagent2').animate({
                    width: (max_bar_width * avg_bar_pct) + '%'
                },
                {
                    duration: 1500 * avg_bar_pct,
                    easing: 'linear',
                    step: function(now, fx){
                        $('#topstats #avgagentlabel2').text(Math.round(avg_vol * (now / (max_bar_width * avg_bar_pct))));
                    },
                    complete: function(){
                        $('#topstats #avgagentlabel2').text(avg_vol);
                    }
                });
        }
    },

    /**
     * Generic stats animation function
     */
    agentStatsAnimation: function(data)
    {
        // Cache the stats data
        AgentAce.statsData = data;

        // Set the labels to zero
        $('#agentstats #topagentlabel').text(0);
        $('#agentstats #avgagentlabel').text(0);

        // Reset the width of the bar graph
        $('#agentstats #topagent').css({
            width: '0%'
        });
        $('#agentstats #avgagent').css({
            width: '0%'
        });

        // Hide the pie chart containers
        $('#agentstats #topagentpie').hide();
        $('#agentstats #avgagentpie').hide();
        $('#agentstats #topweekslabel').text('0');
        $('#agentstats #avgweekslabel').text('0');

        // Hide the submit buttons
        $('#statsform :submit').hide();
        $('#statsform2 :submit').hide();
        $('#contactinfo :submit').hide();

        // Only animate if AJAX call reports success
        if(data.status == 'success')
        {
            // Set the labels text
            var top_weeks = Math.round(data.top_days_on_market / 7);
            var avg_weeks = Math.round(data.avg_days_on_market / 7);

            // maximum bar width
            var max_bar_width = 69;

            // get volumes
            var top_vol = data.top_stats_volume;
            var avg_vol = data.avg_stats_volume;

            // calculate bar width as a ratio
            var top_bar_pct = 1.0;
            var avg_bar_pct = avg_vol / top_vol;

            // animate the bars and labels
            $('#agentstats #topagent').animate({
                    width: (max_bar_width * top_bar_pct) + '%'
                },
                {
                    duration: 1500 * top_bar_pct,
                    easing: 'linear',
                    step: function(now, fx){
                        $('#agentstats #topagentlabel').text(Math.round(top_vol * (now / (max_bar_width * top_bar_pct))));
                    },
                    complete: function(){
                        $('#agentstats #topagentlabel').text(top_vol);

                        $('#agentstats #topagentpie').fadeIn(ConfigOptions.fadeInTime);
                        $('#agentstats #avgagentpie').fadeIn(ConfigOptions.fadeInTime);
                        $('#agentstats #topweekslabel').text(top_weeks);
                        $('#agentstats #avgweekslabel').text(avg_weeks);

                        // Draw pie charts
                        AgentAce.drawPieCharts(
                            [top_weeks, 52 - top_weeks],
                            [avg_weeks, 52 - avg_weeks],
                            $('#agentstats #topagentpie2'),
                            $('#agentstats #avgagentpie2')
                        );

                        $('#statsform :submit').fadeIn(ConfigOptions.fadeInTime);

                        if (AgentAce.smallScreen) {
                            $('#statsform2 :submit').fadeIn(ConfigOptions.fadeInTime);
                        }
                        $('#contactinfo :submit').fadeIn(ConfigOptions.fadeInTime);
                    }
                });

            $('#agentstats #avgagent').animate({
                    width: (max_bar_width * avg_bar_pct) + '%'
                },
                {
                    duration: 1500 * avg_bar_pct,
                    easing: 'linear',
                    step: function(now, fx){
                        $('#agentstats #avgagentlabel').text(Math.round(avg_vol * (now / (max_bar_width * avg_bar_pct))));
                    },
                    complete: function(){
                        $('#agentstats #avgagentlabel').text(avg_vol);
                    }
                });
        }
    },

    /**
     * Copy stats data into slide2 (no animation)
     */
    copyStats: function()
    {
        var data = AgentAce.statsData;

        var max_bar_width = 69;

        var top_vol = data.top_stats_volume;
        var avg_vol = data.avg_stats_volume;

        var top_bar_pct = 1.0;
        var avg_bar_pct = avg_vol / top_vol;

        var top_weeks = Math.round(data.top_days_on_market / 7);
        var avg_weeks = Math.round(data.avg_days_on_market / 7);

        // Set the graph labels
        $('#agentstats #topagentlabel').text(top_vol);
        $('#agentstats #avgagentlabel').text(avg_vol);

        // Set the graphs
        $('#agentstats #topagent').css({
            width: (max_bar_width * top_bar_pct) + '%'
        });
        $('#agentstats #avgagent').css({
            width: (max_bar_width * avg_bar_pct) + '%'
        });

        // Set the charts labels
        $('#agentstats #topweekslabel').text(top_weeks);
        $('#agentstats #avgweekslabel').text(avg_weeks);

        // Draw the pie charts
        AgentAce.drawPieCharts(
            [top_weeks, 52 - top_weeks],
            [avg_weeks, 52 - avg_weeks],
            $('#agentstats #topagentpie2'),
            $('#agentstats #avgagentpie2')
        );

        // Show the buttons
        $('#statsform :submit').show();
        if (AgentAce.smallScreen) {
            $('#statsform2 :submit').show();
        }
        else {
            $('#statsform2 :submit').hide();
        }
    },

	/**
	 ********************************************************************************************
	 * UTILITY FUNCTIONS
	 ********************************************************************************************
	 */

	/**
	 * AgentAce tracking function
	 */
	track: function(ev)
	{
		var img = $("<img />").attr({
			src: 'http://agentace.com/trk.gif?event='+ ev + '&session_id=' + sessionID  + '&rand=' + (new Date).getTime(),
			height: '1',
			width: '1',
			style: 'border-style:none;',
			alt: ''
		});
	},

	/**
	 * Google conversion tracking
	 */
	trackGoogleConversion: function()
	{
                var img = $("<img />").attr({
                        src: 'http://www.googleadservices.com/pagead/conversion/1014723314/?label=28svCJbH8QIQ8uXt4wM&amp;guid=ON&amp;script=0',
                        height: '1',
                        width: '1',
                        style: 'border-style:none;',
                        alt: ''
		});
	},

	/**
	* Bing/Yahoo conversion tracking
	*/
	trackBingConversion: function() {
		var iframe = document.createElement('iframe');
		iframe.style.width = '0px';
		iframe.style.height = '0px';
		document.body.appendChild(iframe);
		iframe.src = "http://agentace.com/bing.html";
        },

    /**
     * Draw pie charts
     */
    drawPieCharts: function(data1, data2, el1, el2)
    {
        // Define data series for the pie charts
        var data1 = [
            { label: 'None', data: data1[0], color: '#EF4A34' },
            { label: 'None', data: data1[1], color: '#FFF' }
        ];
        var data2 = [
            { label: 'None', data: data2[0], color: '#BBB' },
            { label: 'None', data: data2[1], color: '#FFF' }
        ];

        el1.css({ display: 'block', width: '64px', height: '64px' });
        el2.css({ display: 'block', width: '64px', height: '64px' });

        // Define options for the pie charts
        var pieOptions = {
            show: true,
            radius: 20,
            startAngle: 3 / 2,
            stroke: {
                color: '#EFE8E4',
                width: 0
            },
            showLabel: false,
            label: {
                show: false
            }
        };
        var legendOptions = {
            show: false
        };

        // Draw pie charts
        $.plot(el1, data1, {
            series: {
                pie: pieOptions
            },
            legend: legendOptions
        });
        $.plot(el2, data2, {
            series: {
                pie: pieOptions
            },
            legend: legendOptions
        });
    },

	/**
	 * Dynamic content using AJAX, also performs animation
	 */
	dynamicContentLoad: function(url, onComplete, onFadeInComplete)
	{
        if (url != AgentAce.currentUrl)
        {
            // Select the content container
            var $mainContent = null;
            if (AgentAce.smallScreen) {
                // Select the form container in single-column layout
                $mainContent = $('#main-content #form-container:eq(0)');
            }
            else {
                // Select the left column in multi-column layout
                $mainContent = $('#main-content #form-container:eq(0) .leftcol');
            }

            // Perform the animation / ajax
            $mainContent.fadeOut(ConfigOptions.fadeOutTime, function() {
                $mainContent.hide().load(url, function() {

                    // Fade in the content
                    $mainContent.fadeIn(ConfigOptions.fadeInTime, function() {
                        // Execute the onFadeInComplete function
                        if(onFadeInComplete !== undefined) onFadeInComplete();
                    });

                    // Apply uniform to the new content
                    if (AgentAce.smallScreen) {
                        $('#main-content #form-container:eq(0) select').uniform();
                    }
                    else {
                        $('#main-content #form-container:eq(0) .leftcol select').uniform();
                    }

                    // Apply Modernizr to the new content
                    if(!Modernizr.input.placeholder) {
                        $("input[placeholder]").placeholder({
                            placeholderTextColour : "#999"
                        });
                    }

                    // Disable tabbing
                    AgentAce.disableTabIndexes();

                    // Cache the url to prevent duplicate content loading
                    AgentAce.currentUrl = url;

                    // Execute the onComplete function
                    if(onComplete !== undefined) onComplete();
                });
            });
        }
	},

	/**
	 * Sets the styling on the navigation list elements
	 * above the form.
	 * stage - (integer) valid range 1..3
	 */
	setProgressBar: function(stage)
	{
		// find all nav elements and reset styling
		$nav1 = $('#progress1').removeClass('active').removeClass('stage2');
		$nav2 = $('#progress2').removeClass('active').removeClass('stage2');
		$nav3 = $('#progress3').removeClass('active').removeClass('stage2');

		// selectively apply styling
		switch(stage)
		{
			case 1:
				$nav1.addClass('active');
				break;
			case 2:
				$nav1.addClass('stage2');
				$nav2.addClass('active');
				break;
			case 3:
				$nav2.addClass('stage2');
				$nav3.addClass('active');
				break;
		}
	},

    /**
     * Disables tab indexes
     */
    disableTabIndexes: function()
    {
        // Buy / Sell form
        $('#address').attr('tabindex', -1);
        $('#property_type').attr('tabindex', -1);
        $('#price_range').attr('tabindex', -1);
        $('#buyform :submit').attr('tabindex', -1);
        $('#sellform :submit').attr('tabindex', -1);

        // Top Stats form
        $('#topstatsform :submit').attr('tabindex', -1);

        // Stats form
        $('#statsform :submit').attr('tabindex', -1);
        $('#statsform2 :submit').attr('tabindex', -1);

        // Contact form
        $('#full_name_contact').attr('tabindex', -1);
        $('#email_contact').attr('tabindex', -1);
        $('#phone_contact').attr('tabindex', -1);
        $('#best_time').attr('tabindex', -1);
        $('#agree').attr('tabindex', -1);
        $('#contactinfo :submit').attr('tabindex', -1);
        $('#contactinfo2 :submit').attr('tabindex', -1);

        // Success form
        $('#result :submit').attr('tabindex', -1);
    },

	/**
	 * Enable autocomplete
	 */
	ajaxAutocomplete: function()
	{
		$("#address").autocomplete({
			autoFill : true,
			source: function(req, add){
				$.ajax({
					url 		: ConfigOptions.autoCompleteUrl + '?metro=1&value=' + $('#address').val() + '&session_id=' + sessionID,
					dataType	: 'jsonp',
					success 	: function (data, textStatus, jqXHR) {
						var suggestions = [];
						if(data.status == 'success')
						{
							$.each(data.values, function(index, value) {
								suggestions.push(value);
							});
							add(suggestions);
						}
					}
				});
			}
		});
		$('#address').click(function() {
			$("#address").autocomplete('close');
		});
	},

	/**
	 * Toggle buy / sell form layout
	 */
	toggleBuySell: function()
	{
        // Buy button
		$('.buylabel').click( function(e) {
            // Fix for IE
            $('#buy').prop('checked', true);

            // Switch to first slide
            if (AgentAce.sliderObj.currentSlide != 0) {
                AgentAce.sliderObj.flexAnimate(0);
                AgentAce.setProgressBar(1);
            }

            // Serialize the form data
            var formDataArray = $("#sellform").serializeArray();
            $.each(formDataArray, function(){
                if (this.name == 'address' && this.value == $('#address').attr('placeholder'))
                    this.value = '';
            });

            // Reset the stats to defaults
            AgentAce.resetFormStats();

             // Fade out the time div of the widget
            $('.time').hide();

            //Change the switch
            $('.buysell').addClass('buy');
            $('.stats').addClass('buy');
            $('.bs span').replaceWith( "<span>Bought</span>" );
            $('.selllabel').removeClass('checked');
            $('.buylabel').addClass('checked');

            // Load the buy form
			AgentAce.dynamicContentLoad(AgentAce.formUrls.buyHome, function() {
				AgentAce.buyFormHandler();

                // Copy the form data into the buy form
                $.each(formDataArray, function(){
                    if (this.name == 'address' && this.value != '')
                        $('#address').val(this.value);
                    if (this.name == 'property_type')
                        $('#property_type').val(this.value);
                    if (this.name == 'price_range')
                        $('#price_range').val(this.value);
                });

                // Update uniform
                $.uniform.update('select');
			});
		});

        // Sell button
		$('.selllabel').click( function(e) {
            // Fix for IE
            $('#sell').prop('checked', true);

            // Switch to first slide
            if (AgentAce.sliderObj.currentSlide != 0) {
                AgentAce.sliderObj.flexAnimate(0);
                AgentAce.setProgressBar(1);
            }

            // Serialize the form data
            var formDataArray = $("#buyform").serializeArray();
            $.each(formDataArray, function(){
                if (this.name == 'address' && this.value == $('#address').attr('placeholder'))
                    this.value = '';
            });

            // Reset the stats to defaults
            AgentAce.resetFormStats();

            //Change the switch back
            $('.buysell').removeClass('buy');
            $('.stats').removeClass('buy');
            $('.bs span').replaceWith( "<span>Sold</span>" );
            $('.selllabel').addClass('checked');
            $('.buylabel').removeClass('checked');

            // Fade in the time div of the widget
            $('.time').fadeIn(ConfigOptions.fadeInTime);

            // Load the sell form
			AgentAce.dynamicContentLoad(AgentAce.formUrls.sellHome, function() {
				AgentAce.sellFormHandler();

                // Copy the form data into the sell form
                $.each(formDataArray, function(){
                    if (this.name == 'address' && this.value != '')
                        $('#address').val(this.value);
                    if (this.name == 'property_type')
                        $('#property_type').val(this.value);
                    if (this.name == 'price_range')
                        $('#price_range').val(this.value);
                });

                // Update uniform
                $.uniform.update('select');
			});
		});
	},

    /**
     * Reset buy / sell form to defaults
     */
    resetFormBuySell: function()
    {
        // Reset the buy / sell form
        $('#address').val('');
        $('#property_type').val($('#property_type').prop('defaultSelected'));
        $('#price_range').val($('#price_range').prop('defaultSelected'));

        // Update uniform
        $.uniform.update('select');
    },

    /**
     * Reset contact form to defaults
     */
    resetFormContact: function()
    {
        // Reset the contact form
        $('#full_name_contact').val('');
        $('#email_contact').val('');
        $('#phone_contact').val('');
        $('#best_time').val($('#best_time').prop('defaultSelected'));
        $('#agree').removeAttr('checked');

        // Update uniform
        $.uniform.update('select');
    },

    /**
     * Reset stats form to defaults
     */
    resetFormStats: function()
    {
        // Reset the wide screen stats form
        if (!AgentAce.smallScreen) {
            $('#topstats #topagentlabel2').text('0');
            $('#topstats #avgagentlabel2').text('0');
            $('#topstats #topagent2').css({ width: '0%' });
            $('#topstats #avgagent2').css({ width: '0%' });
            $('#topstats #topweekslabel2').text('0');
            $('#topstats #avgweekslabel2').text('0');
            $('#topstatsform :submit').hide();
            if($('.buysell :checked').val() == 'sell')
            {
                AgentAce.drawPieCharts(
                    [5, 95],
                    [5, 95],
                    $('#topstats #topagentpie'),
                    $('#topstats #avgagentpie')
                );
            }
        }

        // Reset the regular stats form
        $('#agentstats #topagentlabel').text('0');
        $('#agentstats #avgagentlabel').text('0');
        $('#agentstats #topagent').css({ width: '0%' });
        $('#agentstats #avgagent').css({ width: '0%' });
        $('#agentstats #topweekslabel').text('0');
        $('#agentstats #avgweekslabel').text('0');
        $('#statsform :submit').hide();
        $('#statsform2 :submit').hide();
        //if($('.buysell :checked').val() == 'sell')
        //{
        //    AgentAce.drawPieCharts(
        //        [5, 95],
        //        [5, 95],
        //        $('#agentstats #topagentpie2'),
        //        $('#agentstats #avgagentpie2')
        //    );
        //}

        // Update uniform
        $.uniform.update('select');
    },

    /**
     * Reset form to defaults
     */
    resetForm: function()
    {
        AgentAce.resetFormBuySell();
        AgentAce.resetFormContact();
        AgentAce.resetFormStats();
    },

    /**
     * Handle form errors
     * @param data
     */
    handleResponseError: function(data)
    {
        var formUrl = AgentAce.formUrls.noResult;
        if(data.status == 'invalid address'){
        	formUrl = AgentAce.formUrls.invalid;
        }
        else if(data.status == 'out of area'){
        	formUrl = AgentAce.formUrls.outOfRange;
        }
        else if(data.status == 'no matches'){
        	formUrl = AgentAce.formUrls.noResult;
        }
        AgentAce.dynamicContentLoad(formUrl, function(){
            // do nothing
        });
    },

	/**
	 ********************************************************************************************
	 * FORM HANDLERS
	 ********************************************************************************************
	 */

	/**
	 * Sell form handler
	 */
	sellFormHandler: function()
	{
		// Address field autocomplete function
		AgentAce.ajaxAutocomplete();

		// Sell form validation
		AgentAce.sellFormValidation(function(){
			$("#address").autocomplete('close');

			var formDataArray = $("#sellform").serializeArray();
            formDataArray[formDataArray.length] = { name:'listing_type', value:$('.buysell :checked').val() };
			formDataArray[formDataArray.length] = { name:'session_id', value:sessionID };

			$.ajax({
				url 		: ConfigOptions.agentStatsUrl,
				dataType	: 'jsonp',
				data		: $.param(formDataArray),
				success 	: function(data, textStatus, jqXHR) {
                    if (data.status == 'success'){
                        // Replace some html
                        $('.formstart').removeClass('pointer');
                        $('.formstart span').replaceWith( "<span>Your current search:</span>" );
                        $('#sellform :submit').val('Search again ›').addClass('beta');

                        AgentAce.formParameters = formDataArray;
                        AgentAce.sellStatsAnimation(data);
                        AgentAce.setProgressBar(2);

                        if (AgentAce.smallScreen) {
                            AgentAce.sliderObj.flexAnimate(1);
                        }
                    } else {
                        AgentAce.handleResponseError(data);
                    }
				}
			});
		});
	},

    /**
     * Buy form handler
     */
    buyFormHandler: function()
    {
        // Address field autocomplete function
        AgentAce.ajaxAutocomplete();

        // Sell form validation
        AgentAce.buyFormValidation(function(){
            $("#address").autocomplete('close');

            var formDataArray = $("#buyform").serializeArray();
            formDataArray[formDataArray.length] = { name:'listing_type', value:$('.buysell :checked').val() };
            formDataArray[formDataArray.length] = { name:'session_id', value:sessionID };

            $.ajax({
                url 		: ConfigOptions.agentStatsUrl,
                dataType	: 'jsonp',
                data		: $.param(formDataArray),
                success 	: function(data, textStatus, jqXHR) {
                    if (data.status == 'success'){
                        // Replace some html
                        $('.formstart').removeClass('pointer');
                        $('.formstart span').replaceWith( "<span>Your current search:</span>" );
                        $('#buyform :submit').val('Search again ›').addClass('beta');

                        AgentAce.formParameters = formDataArray;
                        AgentAce.buyStatsAnimation(data);
                        AgentAce.setProgressBar(2);

                        if (AgentAce.smallScreen) {
                            AgentAce.sliderObj.flexAnimate(1);
                        }
                    } else {
                        AgentAce.handleResponseError(data);
                    }
                }
            });
        });
    },

    /**
     * Top stats form handler (multiple column view only)
     */
    topStatsFormHandler: function()
    {
        // get the top agent form submit handler
        $('#topstatsform').submit(function(e) {
            AgentAce.sliderObj.flexAnimate(1);
            AgentAce.setProgressBar(2);
            AgentAce.copyStats();
            e.preventDefault();
		AgentAce.track('get_click');
        });

        // Hide the submit button
        $('#topstatsform :submit').hide();
    },

    /**
     * Stats form handler
     */
    statsFormHandler: function()
    {
        // start over form submit handler
        $('#statsform').submit(function(e) {
            AgentAce.sliderObj.flexAnimate(0);
            // for mobile / small screens
            if(AgentAce.smallScreen) {
                AgentAce.setProgressBar(1);
            }
            e.preventDefault();
        });

        // for mobile / small screens
        if(AgentAce.smallScreen) {
            // get top agent submit handler
            $('#statsform2').submit(function(e) {
                AgentAce.sliderObj.flexAnimate(2);
                AgentAce.setProgressBar(3);
                e.preventDefault();
            });
        }
        else {
            $('#statsform2 :submit').hide();
        }
    },

	/**
	 * Contact form handler
	 */
	contactFormHandler: function()
	{
		AgentAce.contactFormValidation(function(){
			var formDataArray = $("#contactinfo").serializeArray();

            // Fix value from agree checkbox
			$.each(formDataArray, function() {
				if(this.name == 'agree' && this.value == 'on'){
					this.value = 1;
				}
			});

            // Selectively copy form data
			$.each(AgentAce.formParameters, function() {
				if( this.name == 'metro' || this.name == 'address' ||
                    this.name == 'price_range' || this.name == 'property_type')
				{
					formDataArray[formDataArray.length] = this;
				}
			});

            // Add the listing type
            formDataArray[formDataArray.length] = { name:'listing_type', value:$('.buysell :checked').val() };

            // Add the session id
			formDataArray[formDataArray.length] = { name:'session_id', value:sessionID };

            // Fire and forget AJAX call
			$.ajax({
				url			: ConfigOptions.userContactUrl,
				dataType	: 'jsonp',
				data		: $.param(formDataArray)
			});

                        AgentAce.trackGoogleConversion();
                        AgentAce.trackBingConversion();

            AgentAce.setProgressBar(3);

            if(AgentAce.smallScreen) {
                AgentAce.sliderObj.flexAnimate(3);
            }
            else {
                AgentAce.sliderObj.flexAnimate(2);
            }
		});

        // for mobile / small screens
        if(AgentAce.smallScreen) {
            // get top agent submit handler
            $('#contactinfo2').submit(function(e) {
                AgentAce.sliderObj.flexAnimate(1);
                AgentAce.setProgressBar(2);
                e.preventDefault();
            });
        }
        else {
            $('#contactinfo2 :submit').hide();
        }
	},

	/**
	 * Result form handler
	 */
	resultFormHandler: function()
	{
		// start over form submit handler
		$('#result').submit(function(e) {
            AgentAce.sliderObj.flexAnimate(0);
            AgentAce.setProgressBar(1);
            AgentAce.resetForm();
			e.preventDefault();
		});
	},

    /**
     * General contact form handler
     */
    generalContactFormHandler: function()
    {
        AgentAce.generalContactFormValidation(function(){
            var formDataArray = $('#general-contact').serializeArray();
            formDataArray[formDataArray.length] = { name:'session_id', value:sessionID };
            $.ajax({
                url			: ConfigOptions.userEnquiryUrl,
                dataType	: 'jsonp',
                data		: $.param(formDataArray)
            });
            $('#general-contact-container').fadeOut(ConfigOptions.fadeOutTime, function() {
                $(this).html('<p>Your message has been sent.</p>')
                    .fadeIn(ConfigOptions.fadeInTime);
            });
        });
    },

	/**
	 ********************************************************************************************
	 * WIDGET
	 ********************************************************************************************
	 */

	/**
	 * Widget init function
	 */
	initWidget: function()
	{
        // Initialize members
        AgentAce.currentUrl = AgentAce.formUrls.sellHome;
        AgentAce.smallScreen = (screen.width > 760) ? false : true;

        // Uncomment the following line to debug small screen browsers
        //AgentAce.smallScreen = true;

        // Custom validator rule for placeholder text
        $.validator.addMethod('notPlaceholder', function(val, el) {
            return this.optional(el) || ( val !== $(el).attr('placeholder') );
        }, $.validator.messages.required);

        // Custom validator rule for regular expressions
        $.validator.addMethod('regex', function(val, el, exp) {
            var regEx = new RegExp(exp);
            return this.optional(el) || regEx.test(val);
        }, $.validator.messages.required);

        // Load content based on screen size
        var contentUrl = (AgentAce.smallScreen) ?
            AgentAce.contentUrls.smallScreen : AgentAce.contentUrls.largeScreen;

        // Load and animate the content
        var mainContent = $('#main-container');
        mainContent.fadeOut(ConfigOptions.fadeOutTime, function() {
            mainContent.hide().load(contentUrl, function() {

                // Fade in the content
                mainContent.fadeIn(ConfigOptions.fadeInTime, function() {
                    // Some stuff is only for big screens
                    if (!AgentAce.smallScreen) {
                        // Draw initial pie charts
                        AgentAce.drawPieCharts(
                            [5, 95],
                            [5, 95],
                            $('#topstats #topagentpie'),
                            $('#topstats #avgagentpie')
                        );
                    }
                });

                // Apply uniform to the new content
                $('#main-container select').uniform();

                // Apply Modernizr to the new content
                if(!Modernizr.input.placeholder) {
                    $("input[placeholder]").placeholder({
                        placeholderTextColour : "#999"
                    });
                }

                // Some stuff is only for big screens
                if (!AgentAce.smallScreen) {
                    // Handle the top stats form
                    AgentAce.topStatsFormHandler();
                }

                // Buy / sell form toggle
                AgentAce.toggleBuySell();

                // Handle general contact form
                AgentAce.generalContactFormHandler();

                // Handle the sell form
                AgentAce.sellFormHandler();

                // Handle the stats form
                AgentAce.statsFormHandler();

                // Handle the contact form
                AgentAce.contactFormHandler();

                // Handle the result form
                AgentAce.resultFormHandler();

                // Set the progress bar
                AgentAce.setProgressBar(1);

                // Disable the tab indexes
                AgentAce.disableTabIndexes();

                // Initialize flexslider
                $('.flexslider').flexslider({
                    animation: "slide",
										keyboardNav: false,
                    controlsContainer: ".flex-container",
                    animationDuration: 300,
                    slideshow: false,
                    directionNav: false,
                    controlNav: false,
                    start: function(slider){
                        AgentAce.sliderObj = slider;
                    }
                });
            });
        });
	}
};

$(document).ready(function() {

	//Hide expanded how it works process
	$('.show').hide();
    $('.expand').click(function() {
        $('.show').slideDown(300);
        $('.expand').hide();
        return false;
    });

	// Hide the curtain, show the widget and set a cookie on clicking the start link
/*	$('.start').click(function() {
		$('#curtain').slideUp(350);
		$('#main').delay(600).fadeTo(450, 1, function() {});
		$.cookie('curtain', 'dismiss', { expires: 1 });
		AgentAce.track('start_click');
	});


	//Check for cookies and do stuff
	var curtain = $.cookie('curtain');
	if (curtain == null) {
		$('#curtain').delay(600).fadeIn(450);
	} else {
		$('#main').fadeTo(450, 1, function() {});
	};
	
	*/
	//added the widget fade in independent of the curtain
	$('#main').fadeTo(450, 1, function() {});
	// Initialize the widget
	AgentAce.initWidget();

	// Initialize fancybox with screen-specific options
    if(screen.width > 600) {
        $("a.ffaq").fancybox({
            opacity			: true,
            scrolling 		: 'no',
            centerOnScroll	: true,
            overlayColor 	: '#000000',
            overlayOpacity  : '0.9',
            padding			: 20,
            margin			: 0,
            type            : 'inline',
            autoDimensions  : false,
            width           : '600'
        });
    } else {
        $("a.ffaq").fancybox({
            opacity			: true,
            scrolling 		: 'no',
            centerOnScroll	: true,
            overlayColor 	: '#000000',
            overlayOpacity  : '0.9',
            padding			: 20,
            margin			: 0,
            type            : 'inline',
            autoDimensions  : true
        });
    }

	//placeholder attribute support for older browsers
	if(!Modernizr.input.placeholder) {
		$("input[placeholder]").placeholder({
			placeholderTextColour : "#999"
		});
	}

	// Create the dropdown base
	$("<select />").appendTo("nav");

	// Create default option "Go to..."
	$("<option />", {
		"selected" : "selected",
		"value" : "",
		"text" : "Navigate..."
	}).appendTo("nav select");

	// Populate dropdown with menu items
	$("nav a").each(function() {
		var el = $(this);
		$("<option />", {
			"value" : el.attr("href"),
			"text" : el.text()
		}).appendTo("nav select");
	});

	// To make dropdown actually work
	$("nav select").change(function() {
		window.location = $(this).find("option:selected").val();
	});

    // Fancy forms
    $('select').uniform();

    // Smooth scrolling
    $('.home .onep a, .ttop').smoothScroll();

    // Nav highlighting
    $('.home .onep a').each(function(index){
        $(this).click(function(){
            $('#menu-main li').removeClass('current');
            $(this).parent().addClass('current');
        });
    });

    // Fix nav highlight
    $('.home .onep a').each(function(index){
        if(window.location.hash == $(this).attr('href'))
        {
            $('#menu-main li').removeClass('current');
            $(this).trigger('click');
        }
    });

});

