/// <reference path="~/scripts/jquery-1.4.2.js" />

/**
 * Mutes firebug console code and errors on browsers where firebug is not installed
 */
if (!window.console || !console.firebug) {
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", 
	"groupCollapsed", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
    window.console = {};
    for (var i = 0; i < names.length; ++i) {
        window.console[names[i]] = function() {};
	}
}

var map;

function getRandomInt(min,max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

/*	DOM-READY FUNCTION
-------------------------------------------------------------- */
$(function() {

    // Dynamic Tabs
    $('#helperTabs a').click(function() {
        var theTab = $(this).attr('id');
        $(this).parent().addClass('activeTab').siblings().removeClass('activeTab');
        $('.' + theTab).show().siblings().hide();
        document.location.hash = "_" + theTab;

        if (theTab == 'services') {
            if (typeof(map) !== 'undefined') {
                map.checkResize();
                map.zoomToMarkers(20);
            }
        }
        if (typeof(pageTracker) != 'undefined')
            pageTracker._trackEvent('helperLandingMarch2010', 'Click', 'Tab: ' + theTab);
        return false;
    });

    // Get the current hash of the page
    var currentHash = window.location.hash.substr(1);
    if (currentHash == "_services") {
        $('#services').click();
    } else if (currentHash == "_customer-reviews") {
        $('#customer-reviews').click();
    } else {
        $('.services, .customer-reviews').hide();
        //$('.services, .customer-reviews').addClass('contentHidden');
    }

    // HoverClass these objects
    $('#helperTabs li').hoverClass();

    // Table stripes
    $('.modColRight .mod table').each(function() {
        $(this).find('tr:odd').addClass('odd');
    })

	// Cache the h1 content
	var helperName = $('#header h1').text();

    // Helper names: Widow prevention, Fancy Ampersands, and long helper name class change.
    $('#header h1').each(function() {
        $(this).html($(this).text().replace(/ (\S+)$/, '&nbsp;' + '$1')).html($(this).html().replace('&amp;', '<span class="amp">&amp;</span>'));
        //console.log($(this).text().length)
        if ($(this).text().length >= 60) { $(this).addClass('hugeHelperName'); }
    });

    // Hover on star reviews
    var reviewsTab = $('#customer-reviews').parent();
    $('.hahRating').hover(function() {
        $(this).addClass('hover');
        reviewsTab.addClass('hover');
    }, function() {
        $(this).removeClass('hover');
        reviewsTab.removeClass('hover');
    })

    // Alternate on the comments on the mover landing page
    $('.reviewBlockPreview:odd span').addClass('even');

    // Add 'last' class to last items
    $('.modColRight .mod:last-child, #footer li:last-child').addClass('last');

    // 2 column list. Because CSS sucks that bad.
    $('.serviceAreas ul').after('<ul></ul>').next('ul').append($('.serviceAreas ul:eq(0) li:gt(' + Math.floor($('.serviceAreas li').size() / 2) + ')'));

    // Review blocks layout. Count reviews, and put 1/2 of them in the right hand column.
    $('.customer-reviews .modColRight').append($('.customer-reviews .modColLeft .hreview:gt(' + Math.floor($('.customer-reviews .modColLeft .hreview').size() / 2) + ')'));
    // This PNG replacement needs to happen AFTER the content gets moved. (2 lines above)
    if ($.browser.className == 'msie6') { DD_belatedPNG.fix('.hreview .rating'); }

    // Customer reviews link
    $('.allReviewsLink').click(function() {
        $('#customer-reviews').click();
        if (typeof(pageTracker) != 'undefined')
            pageTracker._trackEvent('helperLandingMarch2010', 'Click', 'Read all our customer reviews');
    })

    // Learn More Modals
    $('#modalGuarantee, #modalPayment, #modalSecurity, #modalReviews').dialog({
        bgiframe: true,
        modal: true,
        maxHeight: 500,
        width: 600,
        //position: 'center',
        autoOpen: false
    });

    // Modal Window Launchers
    $('.listCheck .learnMore').click(function() {
        $('#modalGuarantee').dialog('open');
        if (typeof(pageTracker) != 'undefined')
            pageTracker._trackEvent('helperLandingMarch2010', 'Click', 'Learn More Bug: modalGuarantee');
        return false;
    });
    $('.listDollar .learnMore').click(function() {
        $('#modalPayment').dialog('open');
        if (typeof(pageTracker) != 'undefined')
            pageTracker._trackEvent('helperLandingMarch2010', 'Click', 'Learn More Bug: modalPayment');
        return false;
    });
    $('.listLock .learnMore').click(function() {
        $('#modalSecurity').dialog('open');
        if (typeof(pageTracker) != 'undefined')
            pageTracker._trackEvent('helperLandingMarch2010', 'Click', 'Learn More Bug: modalSecurity');
        return false;
    });
    $('.listReviews .learnMore').click(function() {
        $('#modalReviews').dialog('open');
        if (typeof(pageTracker) != 'undefined')
            pageTracker._trackEvent('helperLandingMarch2010', 'Click', 'Learn More Bug: modalReviews');
        return false;
    });

    // Cache some selectors
    var bookingFields = $('#modBookOnline input[type="text"]');
    var dateField = $('#modBookOnline .labelWrapper:first input[type="text"]');
    var zipField = $('#modBookOnline .labelWrapper:last input[type="text"]')

    // Handle page load inputs from browser cache
    bookingFields.each(function() {
        if ($(this).val() != "") {
            $(this).next('span').hide();
        }
    });

    dateField.focus(function() {
        if ($(this).val() == "") {
            $(this).next('span').hide();
        }
    }).blur(function() {
        if (dateField.val() == "") {
            dateField.next('span').show().css('color', '#666666');
        }
    }).siblings('span').click(function() {
        dateField.focus();
    });

    zipField.focus(function() {
        if ($(this).val() == "") {
            $(this).next('span').css('color', '#999999');
        }
    }).keyup(function(e) {
        var tthis = $(this)
        // Enter Key
        if (e.which == 13) {
            BookUsOnlineSubmit();
        }
        if (tthis.val() != "") {
            tthis.next('span').hide();
        }
        if (tthis.val() == "") {
            tthis.next('span').show();
        }
    }).blur(function() {
        if (zipField.val() == "") {
            zipField.next('span').show().css('color', '#666666');
        }
    }).siblings('span').click(function() {
        zipField.focus();
    });


    // Hold values for call-to-action fields
    dateField.datepicker({
        beforeShow: function() {
            $(this).next('span').hide();
        },
        onClose: function() {
            if (zipField.val() == '') {
                zipField.focus();
            }
            $(this).siblings('span').hide();
        }
    });

    // CLick the calendar icon on the date text input.
    $('.calendarBug').click(function() {
        dateField.focus();
        return false;
    })

    // Clicking the service area link in the call to action calls the associated tab.
    $('#serviceAreaLnk').click(function() {
        $('#services').click();
        return false;
    });

    $('.onlineCTA').click(function() {
        if (typeof(pageTracker) != 'undefined')
            pageTracker._trackEvent('helperLandingMarch2010', 'Click', 'CTA');
        BookUsOnlineSubmit();
        return false;
    });

    // Adjust CTA if no truck is offered
    if ($('#modBookOnline .colRight input:first-child').length == 0) {
        $('.onlineCTA').css('marginTop', '35px');
    }

    // Create alert dialogue for validation
    $('body').append('<div id="alertDialogue" title="Alert"><p class="error"></p></div>');
    $('#alertDialogue').hide().dialog({
        bgiframe: true,
        modal: true,
        //maxHeight: 500,
        //width: 600,
        //position: 'center',
        autoOpen: false
    });

    // Random pictures for Services pages
	if ( ($('#header').hasClass('moverWithTruck')) || ($('#header').hasClass('moverNoTruck')) ) {
		$('.services .borderContent img').attr('src', '/static/img/content/helper/moverpic' + getRandomInt(0,3) + '.jpg');
	}
	if ( $('#header').hasClass('cleaningHeader') ) {
		$('.services .borderContent img').attr('src', '/static/img/content/helper/cleaningpic' + getRandomInt(0,3) + '.jpg');
	}
	if ( $('#header').hasClass('lawnHeader') ) {
		$('.services .borderContent img').attr('src', '/static/img/content/helper/lawnpic' + getRandomInt(0,2) + '.jpg');
	}
	if ( $('#header').hasClass('dayLaborHeader') ) {
		$('.services .borderContent img').attr('src', '/static/img/content/helper/daylaborpic' + getRandomInt(0,3) + '.jpg');
	}
    

    // Toggle Helper Response
    $('.helperResponseToggle a').click(function() {
        $(this).parent().next('div').animate({ opacity: 'toggle', height: 'toggle' });
        return false;
    }).toggle(function() {
        $(this).text("Hide Our Response:")
    }, function() {
        $(this).text("View Our Response:")
    }
	);
	
	InitializeGoogleMap();

});

function InitializeGoogleMap() {
    if (workerLocationsJsonObj === '') {
        return;
    }
    
    map = new GMap2(document.getElementById('GoogleMap'));

    // Setup Google Map
            
    var customUI = map.getDefaultUI();
    customUI.controls.menumaptypecontrol = false;
    customUI.controls.maptypecontrol = false;
    customUI.controls.smallzoomcontrol3d = true;
    customUI.controls.largemapcontrol3d = false;
    map.setUI(customUI);
           
    var setCenter = false;
    for (var key in workerLocationsJsonObj) {
        var curObj = workerLocationsJsonObj[key];
        var mapPoint = new GLatLng(curObj.Lat, curObj.Long);        
        if (!setCenter) {
            // need to at least center the map once, otherwise google freaks out.
            map.setCenter(mapPoint, 7);	
            setCenter = true;
        }        
        
        var theMarker = CreateMarker(map, mapPoint, curObj.MarkerName);
                
        map.addOverlay(theMarker);  
                     
        drawCircle(map, mapPoint, curObj.RadiusMiles);
    }    	
    
    map.zoomToMarkers(20);
}

function CreateMarker(mapObj, mapPoint, markerTooltip) {
    var newMarker = new PdMarker(mapPoint);
        
    GEvent.addListener(newMarker, 'click', function() {
        var pt = newMarker.getPoint();
        mapObj.setCenter(new GLatLng(pt.lat(), pt.lng()), 7);
    });        
    
    newMarker.setTooltip(markerTooltip);   
    
    return newMarker; 
}

/*	WINDOW LOADED FUNCTION
-------------------------------------------------------------- */
// $(window).load(function () {
// 	
// 	// Page loaded stuff here
// 
// });

function BookUsOnlineSubmit() {
    var whereObj = $('#where');
    var whenObj = $('#when');
    
    var whereVal = whereObj.val();
    var whenVal = whenObj.val();

	var alertDialogue = $('#alertDialogue')
	var alertDialogueMessage = $('#alertDialogue .error')
           
    // validate
    // dumb validation, like did they enter anything?

	if (whenVal == whenObj.attr('originalvalue') || whenVal == '') {
		alertDialogueMessage.text('Please provide your date in order to proceed.');
		alertDialogue.dialog('open');
		if (typeof(pageTracker) != 'undefined')
		    pageTracker._trackEvent('helperLandingMarch2010', 'Error', 'Please provide your date in order to proceed');
        return false;    
    }
	
    if (whereVal == whereObj.attr('originalvalue') || whereVal == '') {
		alertDialogueMessage.text('Please provide your zip code in order to proceed.');
		alertDialogue.dialog('open');
		if (typeof(pageTracker) != 'undefined')
		    pageTracker._trackEvent('helperLandingMarch2010', 'Error', 'Please provide your zip code in order to proceed');
        whereObj.focus();
        return false;    
    }
    
    //      check the actual values
    var zipRegex = /^[0-9]{5}$/;
    if (!whereVal.match(zipRegex)) {
		alertDialogueMessage.text('Please enter a five-digit ZIP CODE in order to proceed.');
		alertDialogue.dialog('open');
		$('#where').val('').next('span').show();
		if (typeof(pageTracker) != 'undefined')
		    pageTracker._trackEvent('helperLandingMarch2010', 'Error', 'Please enter a five-digit ZIP CODE in order to proceed');
        return false;
    }   
    
    var dateRegex = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
    if (!whenVal.match(dateRegex)) {
		alertDialogueMessage.text('Please provide date in mm/dd/yyyy format in order to proceed.');
		alertDialogue.dialog('open');
		if (typeof(pageTracker) != 'undefined')
    		pageTracker._trackEvent('helperLandingMarch2010', 'Error', 'Please provide date in mm/dd/yyyy format in order to proceed');
        return false;    	
    }
    
    // is date in the past?
    var desiredDate = dateParse(whenVal);
    var currentDate = new Date();
	
    if (desiredDate < currentDate) {
		alertDialogueMessage.text('Date cannot be in the past.');
		alertDialogue.dialog('open');
		if (typeof(pageTracker) != 'undefined')
		    pageTracker._trackEvent('helperLandingMarch2010', 'Error', 'Date cannot be in the past');
        return false;
    }
    
    // execute
    var zcbzip = whereObj.val();
    var zcbdate = whenObj.val();
    var zcbcategoryid = $('#helpsearchtype').val();    
    var baseUrl = $('#helpsearchbaseurl').val();
    
    if ($('#optionMoversOnly').length == 1) {
        zcbcategoryid = $('input[@name="serviceOptions"]:checked').val();
    }

    var zcbmyregexp = /\//g;
    var zcburl = baseUrl + '?ZipCode=' + encodeURIComponent(zcbzip) + '&Date=' + encodeURIComponent(zcbdate.toString().replace(zcbmyregexp,'-')) + '&CategoryID=' + encodeURIComponent(zcbcategoryid);

    if ($('#helpsearchwid').length == 1) {
        zcburl += '&HelperID=' + encodeURIComponent($('#helpsearchwid').val());
    }

    window.location = zcburl;
}

// Parse the date and make the minutes 23:59:59
function dateParse(s) {
	var dateNew = new Date();
	var dateParts = s.split('/');
	var dateAdjusted = (dateParts[0])+'/'+(dateParts[1])+'/'+(dateParts[2])+' 23:59:59';
	//console.log('dateAdjusted = '+dateAdjusted)
	dateNew.setTime(Date.parse(dateAdjusted))
	//console.log('dateNew = '+dateNew)
    return dateNew;
}

/* GOOGLE MAP FUNCTIONS */

var EARTH_RADIUS = 6378.137; //in kilometres
var MILE_IN_KILOMETERS = 1.609344;

function getDestLatLng(latLng, bearing, distance) {
    var lat1 = latLng.latRadians();
    var lng1 = latLng.lngRadians();
    var brng = bearing*Math.PI/180; 
    var dDivR = distance/EARTH_RADIUS;
    var lat2 = Math.asin( Math.sin(lat1)*Math.cos(dDivR) + Math.cos(lat1)*Math.sin(dDivR)*Math.cos(brng) );
    var lng2 = lng1 + Math.atan2(Math.sin(brng)*Math.sin(dDivR)*Math.cos(lat1), Math.cos(dDivR)-Math.sin(lat1)*Math.sin(lat2));
    return new GLatLng(lat2/ Math.PI * 180, lng2/ Math.PI * 180);
}

function drawCircle(map, centrePt, rangeValueMiles) {
    // convert to kilometers first
    var rangeValueKilometers = rangeValueMiles * MILE_IN_KILOMETERS;
    var boundaries = getBoundaries(centrePt, rangeValueKilometers);
    var circle = new GGroundOverlay('/images/green_circle.png', boundaries);
    map.addOverlay(circle);
}

function getBoundaries(centrePt, radius) {
    var hypotenuse = Math.sqrt(2 * radius * radius);
    var sw = getDestLatLng(centrePt, 225, hypotenuse);
    var ne = getDestLatLng(centrePt, 45, hypotenuse);
    return new GLatLngBounds(sw, ne);
}