﻿$(document).ready(function() {
    setupCustomGaTracking();
    prepareFormElements();
    initSelectAll();
    initSearchResultsView();
    $(".alertFrequency").change(function(e) {
        e.preventDefault();
        var element = $(this);

        var searchId = element[0].id;
        var searchvalue = element[0].options[element[0].selectedIndex].value;

        if (getUpdateAlertFrequencyLink != null && getUpdateAlertFrequencyLink.length > 0 && searchId && searchvalue) {
            var postLink = getUpdateAlertFrequencyLink + "?id=" + searchId + "&value=" + searchvalue;
            $.getJSON(postLink, function(data) {
                if (data != '') {
                    // Display a message
                    element.fadeOut(1000, function() {
                        element.parent().append("<strong class='addedtext'> Saved </strong>");
                    });

                    setTimeout(function() {
                        $("strong.addedtext").remove();
                        element.fadeIn(1000);
                    }, 2000);
                    //TODO: Remove checkbox selections
                }
                else {
                    //TODO: handle failures
                }
            });
        }
    });

    $(".get-seller-phone-number").click(getSellerPhoneNumber);
    $("ul li a#all-watchlist-items").click(saveSelectedToWatchlist);
    $("ul li a#remove-watchlist-items").click(removeSelectedFromWatchlist);
    $("a.watchlist").click(saveToWatchlist);
    $("ul li a#save-to-favourites").click(saveToFavourites);
    //setIntervalSelectors();

    // Basic Search Calls   
    var searchTarget = $('#searchTarget');

    searchTarget.change(function() {
        searchTargetPageContextSelect($(this).val());
    });
    searchTargetPageContextSelect(searchTarget.attr('title'));
    $(".hero #compare-now").click(compareSelected);
    $("#email-alerts").submit(initEmailAlerts);
    $("#mc-embedded-subscribe-form").submit(subscribeToNewsletter);
    $('.newsletter-subscribe-button').nyroModal({
        type: 'iframe',
        width: 330,
        minWidth: 330,
        height: 315,
        minHeight: 315,
        windowResize: false,
        closeButton: null,
        zIndexStart: 1000
    });

    $("#feedback-button").nyroModal({
        type: 'form',
        width: 716,
        minWidth: 716,
        height: 1030,
        minHeight: 1030,
        windowResize: true,
        closeButton: null,
        zIndexStart: 1000
    });

    $('div.overlay').click(function() { window.location = $(this).prev('a').attr('href'); });

    $('#basic-search').submit(function() {
        if ($('#searchTarget').val() == "Yellow") {
            var keywords = $(this).find('#keywords').val();
            return validateKeywords(keywords);
        }
    });

    $('#yellow-search').submit(function() {
        var keywords = $(this).find('#keywords').val();
        return validateKeywords(keywords);
     });
});

function validateKeywords(keywords) {
    keywords = $.trim(keywords);
    if (keywords == "") {
        alert("Please enter keywords for searching Yellow Pages!");
        return false;
    }
    return true;
}
      
 
function initEmailAlerts(event) {
    event.preventDefault();
    var jQueryValidateResult = $(this).validate().form();
    if (jQueryValidateResult && searchAlertUrl != null && searchAlertUrl.length > 0) {
        saveAlerts(searchAlertUrl);    
    }
}

function saveAlerts(actionUrl) {
    var f = $("#email-alerts");
    var serializedForm = f.serialize();
    var options = {
        type: "POST",
        url: actionUrl,
        data: serializedForm,
        //contentType: "application/json;charset=utf-8",
        dataType: "json",
        async: false,
        success: function(msg) { },
        error: function(msg) { }
    };
    
    var returnText = $.ajax(options).responseText;
    if (returnText.indexOf('success') >= 0) {
        //show succes message
        var element = $("#search-alerts-controls");
        var parent = element.parent();
        element.remove();
        parent.append($("<div class='success-message'></div>").append("Alert Saved"));
    }
    else if (returnText.indexOf('failed') >= 0) {
        // some error message
    }
    else {
        // strange things happened - maybe wrong action Url
    }
}

/* Basic Search Fucntions */
var searchTargetPageContextSelect = function(siteArea) {
    if(siteArea == null || siteArea == '') return;
        
    //Special Case checks
    if (siteArea.toLowerCase() == "news" || siteArea.toLowerCase() == "reviews" || siteArea.toLowerCase() == "video") { siteArea = "Car Talk & Videos"; }
    if (siteArea.toLowerCase() == "car comparison") { siteArea = "New Cars"; }
    $('#searchTarget').val(siteArea)
    $('#basic-search').attr("action", $('#searchTarget :selected').attr('title'));
}

function setIntervalSelectors() {
	// listings
	$("#listing-search-form-price-lower-bound").change(minSelectorHandler);
	$("#listing-search-form-price-upper-bound").change(maxSelectorHandler);

	$("#listing-search-form-year-lower-bound").change(minSelectorHandler);
	$("#listing-search-form-year-upper-bound").change(maxSelectorHandler);

	$("#listing-search-form-odometer-lower-bound").change(minSelectorHandler);
	$("#listing-search-form-odometer-upper-bound").change(maxSelectorHandler);

	//specifications
	$("#specification-search-form-price-lower-bound").change(minSelectorHandler);
	$("#specification-search-form-price-upper-bound").change(maxSelectorHandler);
}

function saveToFavourites(event) {
    event.preventDefault();
    var element = document.getElementById("save-to-favourites");
    if (saveToFavouritesUrl != null && saveToFavouritesUrl.length > 0) {
        var options = {
            type: "POST",
            url: saveToFavouritesUrl,
            dataType: "json",
            async: false,
            success: function(msg) { },
            error: function(msg) { }
        };
        var returnText = $.ajax(options).responseText;

        var msgs = returnText.replace(/\"/g, '').split(",");

        if (msgs[0] == 'succes') {
            element.href = msgs[1];
            element.innerHTML = "Saved to Favourites";
            $("#save-to-favourites").unbind("click");
        }
        else if (msgs[0] == "failed") {
            /// redirect to login page
            window.location = msgs[1];
            $("#save-to-favourites").unbind("click");
        }
        else {
            //TODO: handle failures
        }
    }
}

function saveSelectedToWatchlist(event) {
	event.preventDefault();
	var element = $(this);
	var itemsList = '';
	var separator = '';
	$(".list-item").each(function() {
		var input = $(this).find("input");
		if (input != null && input.is(':checked')) {
			itemsList = itemsList + separator + input.attr("id").replace("result-", "");
			separator = ',';
		}
	});

	saveItemsToWatchlist(itemsList, function() {
		/// show message
		var btn = document.getElementById("all-watchlist-items");
		var txt = btn.innerHTML;
		btn.innerHTML = "Saved to Watchlist";
		setTimeout(function() {
			btn.innerHTML = txt;
		}, 2000);
	});
}

function removeSelectedFromWatchlist(event) {
    event.preventDefault();

    var items = '';
    var separator = '';
    $(".list-item").each(function() {
        var input = $(this).find("input");
        if (input != null && input.is(':checked')) {
            items = items + separator + input.attr("id").replace("result-", "");
            separator = ',';
        }
    });
    if (items != '' && removeItemsFromWatchlistUrl != null && removeItemsFromWatchlistUrl.length > 0) {
        var postLink = removeItemsFromWatchlistUrl.replace("IDS", items);
        var options = {
            type: "POST",
            url: postLink,
            dataType: "json",
            async: false,
            success: function(msg) { },
            error: function(msg) { }
        };
        var returnText = $.ajax(options).responseText;
        var msg = returnText.replace(/\"/g, '');
        if (msg == 'succes') {
            window.location.reload(true);
        }
    }
    
}
 
function compareSelected(event) {
	var element = $(this);
	$(".list-item").each(function() {
		processSelectedComparisonInputs($(this).find("input"));

	});
	$(".compare-column input").each(function() {
		processSelectedComparisonInputs($(this));
	});
}

function processSelectedComparisonInputs(input) {
	if (input != null && input.is(':checked')) {
		var vehicleId = input.attr("id").replace("result-", "");
		if (vehicleId != null && vehicleId != '') {
			if (!compareItemInCookie(vehicleId)) {
				storeCompareItem(vehicleId);
			}
		}
	}
}

function saveItemsToWatchlist(items, additionalMessageFunction) {
    if (items != '' && saveItemsToWatchlistUrl != null && saveItemsToWatchlistUrl.length > 0) {
        var postLink = saveItemsToWatchlistUrl.replace("IDS", items) + "&originalUrl=" + window.location;
        var options = {
            type: "POST",
            url: postLink,
            dataType: "json",
            async: false,
            success: function(msg) { },
            error: function(msg) { }
        };
        var returnText = $.ajax(options).responseText;

        var msgs = returnText.replace(/\"/g, '').split(",");
        if (msgs[0] == 'succes') {
            /// set the buttons for saved items
            var ids = items.split(',');
            for (var k = 0; k < ids.length; k++) {
                var btn = document.getElementById("btn-" + ids[k]);
                if (btn) {
                    btn.href = msgs[1];
                    btn.innerHTML = "Saved to Watchlist";
                }
            }

            additionalMessageFunction();
        }
        else if (msgs[0] == "failed") {
            /// redirect to login page
            window.location = msgs[1];
        }
        else {
            //TODO: handle failures
        }
    }
}

function saveToWatchlist(event) {
	event.preventDefault();
	var element = $(this);
	var id = element.attr("id").replace("btn-", "");

	saveItemsToWatchlist(id, function() { });
	element.unbind("click");
	trackGaEvent('Watchlist', 'Clicks');
}

function getSellerPhoneNumber(event) {
	event.preventDefault();
	var element = $(this);
	var parameters = element[0].title.split(',');

	if (getPhoneNumberLink != null && getPhoneNumberLink.length > 0 && parameters.length == 2) {
		var link = getPhoneNumberLink.replace("NAME", parameters[0]).replace("LOCATION", parameters[1]);
		$.getJSON(link, function(data) {
			if (data != '') {
				// replace the 'get phone number' link with the phone number
				// retrieved
				var parent = element.parent();
				element.remove();
				parent.append($("<div class='dealer-num'></div>").append("Phone " + data));
			}
			else {
				//TODO: handle failures
			}
		});
	}
}

// this method is called when we change the sort order or the page size
function refreshView() {
	var sortOrder = $("#sort-order");
	var sortType = sortOrder[0].options[sortOrder[0].selectedIndex].value;
	var currentLocation = window.location.href;
	var sortIndex = currentLocation.indexOf("sort=");
	if (sortIndex > -1) {
		var urlTail = currentLocation.substr(sortIndex + 5, currentLocation.length - 1);
		var oldsort = "";

		if (urlTail.indexOf('&') > 0) {
			oldsort = currentLocation.substring(sortIndex + 5, currentLocation.indexOf('&'));
		}
		else {
			oldsort = currentLocation.substring(sortIndex + 5);
		}

		newLocation = currentLocation.replace(oldsort, sortType);
	}
	else
		newLocation = currentLocation + (currentLocation.indexOf('?') > 1 ? '&' : '?') + "sort=" + sortType;

	window.location = newLocation; //'/Search/RefreshView/' + sortType + '/' + sizeType + '?' + currentSelection;
};

// set up event handlers for changing sort and page size
$(function() {
	$("#sort-order").change(function() { refreshView() });
});

// Prepares all form elements with their common behaviours.
var prepareFormElements = function() {
	var textBoxes = $('.context-form').find('textarea, input[type=text]');

	for (var i = 0; i < textBoxes.length; i++) {
		var input = $(textBoxes[i]);
		input.addClass('empty');
		if (input.attr('title') != '') {
			input.val(input.attr('title')).focus(focusFormElements).blur(blurFormElements);
		}
	}
}

// Sets the post-blur state on form elements (when a user clicks or tabs out of a control).
var blurFormElements = function() {
	var theInput = $(this);
	if (theInput.val() == '') {
		theInput.addClass('empty').val(theInput.attr('title'));
	}
}

// Sets the post-blur state on form elements (when a user clicks or tabs into a control).
var focusFormElements = function() {
	var theInput = $(this);
	if (theInput.val() == theInput.attr('title')) {
		theInput.val('').removeClass('empty');
	}
}

// Name for session cookie that stores compare items
var COMPARE_COOKIE_NAME = "compareItems";
var options = { path: '/' }

// Cookie Compare Item Related Functions:
function storeCompareItem(itemid) {
	if (!$.cookie) return;

	// hard-coded for now
	var typeid = 1;

	var cookieParts = getCompareItemPartsForType(typeid);
	if (cookieParts[1].indexOf(itemid) > -1) return;
	if (cookieParts[1].length > 0) cookieParts[1] += "," + itemid;
	else cookieParts[1] = itemid;
	$.cookie(COMPARE_COOKIE_NAME, cookieParts.join(':'), options);
}

/// Returns a string array representing compare items stored in the cookie for a particular typeid
/// The first part of the array is the vehicle type id of the compare items, the second is the
/// the comma seperated list of items.
function getCompareItemPartsForType(typeid) {
	var currentCookieParts = getCompareItemParts();
	var cookiePartsForType = null;

	// check if the current cookie compare items are for the right type
	if (currentCookieParts && currentCookieParts.length == 2 && currentCookieParts[0] == typeid) {
		cookiePartsForType = currentCookieParts;
	}
	else {
		cookiePartsForType = new Array(typeid, '');
	}

	return cookiePartsForType;
}


/// Returns a string array representing compare items stored in the cookie
function getCompareItemParts() {
	var parts = null;
	var currentCookieVal = $.cookie(COMPARE_COOKIE_NAME);

	if (currentCookieVal != null && currentCookieVal.length > 0) {
		parts = currentCookieVal.split(':');
	}

	return parts;
}

function setCompareCookie(value) {
	if (!$.cookie) return;
	var typeId = 1;
	var cookieParts = getCompareItemPartsForType(typeId);
	if (cookieParts == null || cookieParts.length != 2) return;
	cookieParts[1] = value;
	$.cookie(COMPARE_COOKIE_NAME, cookieParts.join(':'), options);
}

function storeCompareItem(itemId) {
	if (!compareItemInCookie(itemId)) {
		// hard coded for now
		var typeId = 1;
		var cookieParts = getCompareItemPartsForType(typeId);
		if (cookieParts[1].length > 0) cookieParts[1] += "," + itemId;
		else cookieParts[1] = itemId;
		$.cookie(COMPARE_COOKIE_NAME, cookieParts.join(':'), options);
	}
}

// Checks if the specified vehicleId is already in the comparison list cookie
function compareItemInCookie(vehicleId) {
	var itemInCookie = false;
	var typeId = 1;
	if (!$.cookie) return;

	var cookieParts = getCompareItemPartsForType(typeId);
	var compareListVehicleIds = cookieParts[1].split(',');
	var i = 0;
	for (i = 0; i < compareListVehicleIds.length; i++) {
		var existingId = compareListVehicleIds[i];
		if (vehicleId == existingId) {
			itemInCookie = true;
			break;
		}
	}
	return itemInCookie;
}

/// Returns a string array representing compare items stored in the cookie for a particular typeid
/// The first part of the array is the vehicle type id of the compare items, the second is the
/// the comma seperated list of items.
function getCompareItemPartsForType(typeId) {
	var currentCookieParts = getCompareItemParts();
	var cookiePartsForType = null;

	// check if the current cookie compare items are for the right type
	if (currentCookieParts && currentCookieParts.length == 2 && currentCookieParts[0] == typeId) {
		cookiePartsForType = currentCookieParts;
	}
	else {
		cookiePartsForType = new Array(typeId, '');
	}

	return cookiePartsForType;
}

function removeCompareItem(id) {
	if (!$.cookie) return;

	var compareItems = getCompareItemParts();

	if (compareItems == null || compareItems.length != 2) return;
	if (compareItems[1].length == 0 || compareItems[1].indexOf(id) < 0) return;
	//compareItems[1] = compareItems[1].replace("," + id, "").replace(id + ",", "").replace(id, "");

	var newCookieValue = '';
	var existingCompareItems = compareItems[1].split(',');
	var i = 0;
	for (i = 0; i < existingCompareItems.length; i++) {
		if (existingCompareItems[i] != id) {
			newCookieValue += existingCompareItems[i] + ",";
		}
	}

	if (newCookieValue.length > 0) {
		newCookieValue = newCookieValue.substring(0, newCookieValue.length - 1);
	}

	compareItems[1] = newCookieValue;

	$.cookie(COMPARE_COOKIE_NAME, compareItems.join(':'), options);
}

//Function that deletes the compare cookie to clear the compare list items
function removeAllVehicles() {
	$("#remove-all").click(function(event) {
		event.preventDefault();
		$.cookie(COMPARE_COOKIE_NAME, null);
	});
}

function updateCompareItem(oldId, newId) {
	if (!$.cookie) return;

	var compareItems = getCompareItemParts();
	if (compareItems == null || compareItems.length != 2) return;
	if (compareItems[1].length == 0 || compareItems[1].indexOf(oldId) < 0) return;

	compareItems[1] = compareItems[1].replace(oldId, newId);
	$.cookie(COMPARE_COOKIE_NAME, compareItems.join(':'), options);
}

function getCompareItems() {
	if (!$.cookie) return;
	return $.cookie(COMPARE_COOKIE_NAME);
}

var initSelectAll = function() {
	$("input#select-all").click(function() {
		($("input#select-all").is(":checked")) ? ToggleSelect(true) : ToggleSelect(false);
	});
}

var ToggleSelect = function(checked) {
	$(".list-item").each(function() {
		var input = $(this).find("input");
		if (input != null) {
			input.attr("checked", checked);
		}
	});
}


function minSelectorHandler() {
	var minSelId = $(this).attr('id');
	var maxSelId = minSelId.replace("lower", "upper");
	var minSelector = document.getElementById(minSelId);
	var maxSelector = document.getElementById(maxSelId);
	var selectedMinValue = minSelector.options[minSelector.selectedIndex].value;
	var selectedMaxValue = maxSelector.options[maxSelector.selectedIndex].value;
	if (selectedMinValue != '' && selectedMaxValue != '') {
		min = parseFloat(selectedMinValue);
		max = parseFloat(selectedMaxValue);
		if (min > max) {
			for (k = 0; k < maxSelector.length; k++) {
				if (maxSelector.options[k].value > min) {
					maxSelector.selectedIndex = k;
					break;
				}
			}
		}
	}
}
function maxSelectorHandler() {
	var maxSelId = $(this).attr('id');
	var minSelId = maxSelId.replace("upper", "lower");
	var minSelector = document.getElementById(minSelId);
	var maxSelector = document.getElementById(maxSelId);
	var selectedMinValue = minSelector.options[minSelector.selectedIndex].value;
	var selectedMaxValue = maxSelector.options[maxSelector.selectedIndex].value;
	if (selectedMinValue != '' && selectedMaxValue != '') {
		min = parseFloat(selectedMinValue);
		max = parseFloat(selectedMaxValue);
		if (min > max) {
			for (k = 0; k < minSelector.length; k++) {
				if (max < minSelector.options[k].value && k > 0) {
					minSelector.selectedIndex = k - 1;
					break;
				}
			}
		}
	}
}


// --------------------------------------------- //
// SEARCH RESULTS VIEW - SWITCH LIST/GALLERY     //
//                     - SWITCH PAGE SIZE        //
// --------------------------------------------- //

var SEARCH_VIEW_COOKIE_NAME = "searchView";
var PAGE_SIZE_COOKIE_NAME = "selectedPageSize";
var searchViewOptions = { path: '/', expires: new Date(2050, 1, 1) };

function initSearchResultsView() {
	$("#list-view, #gallery-view").click(function(event) {
		event.preventDefault();
		if (!$(this).hasClass("selected")) switchView($(this).attr("id"));
	});
	$('#page-size').change(function() {
		$.cookie(PAGE_SIZE_COOKIE_NAME, $(this).val(), searchViewOptions);
		location.reload(true);
	});
}

function switchView(type) {
	$.cookie(SEARCH_VIEW_COOKIE_NAME, type, searchViewOptions);

	$('#list-results').toggleClass('gallery-view');
	$('#list-results').toggleClass('list-view');
	$('#list-view').toggleClass('selected');
	$('#gallery-view').toggleClass('selected');
}

// function that takes an absolute url string and breaks it into segments
//-------------------------USAGE-----------------------------------------
//  var myURL = parseURL('http://localhost:8080/tds/home?id=255&m=hello#top');
//  myURL.hash;     // = 'top'
//  myURL.host;     // = 'localhost'
//  myURL.query;    // = '?id=255&m=hello'
//  myURL.params;   // = Object = { id: 255, m: hello }
//  myURL.port;     // = '8080'
//  myURL.protocol; // = 'http'
//  myURL.source;   // = 'http://localhost:8080/tds/home?id=255&m=hello#top'
//
//-----------------------------------------------------------------------
var parseUrl = function(url) {
	var a = document.createElement('a');
	a.href = url;
	return {
		source: url,
		protocol: a.protocol.replace(':', ''),
		host: a.hostname,
		port: a.port,
		query: a.search,
		params: (function() {
			var ret = {},
                    seg = a.search.replace(/^\?/, '').split('&'),
                    len = seg.length, i = 0, s;
			for (; i < len; i++) {
				if (!seg[i]) { continue; }
				s = seg[i].split('=');
				ret[s[0]] = s[1];
			}
			return ret;
		})(),
		hash: a.hash.replace('#', ''),
		relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [, ''])[1]
	};
}

/* --------------------------------------------------------- */
/* NEWSLETTER SUBSCRIPTION FORM SUBMISSION                   */
/* --------------------------------------------------------- */

function subscribeToNewsletter(event) {
    event.preventDefault();
    if (!$(this).validate().form()) {
        return;
    }
        
    var f = $(this);
    var action = f.attr("action");
    var serializedForm = f.serialize();

    var options = {
        type: "POST",
        url: action,
        data: serializedForm,
        //contentType: "application/json;charset=utf-8",
        dataType: "json",
        async: false,
        success: function(msg) { },
        error: function(msg) { }
    };

    var returnText = $.ajax(options).responseText.replace(/"/gi, '').replace(/'/gi, '');
    $("#newsletter-subscription-successful").html(returnText);
    $("#newsletter-subscription-successful-wrapper").show();
    f.slideUp();

    trackGaEvent('Newsletter', 'Sign Ups');
}

// --------------------------------------------- //
// SETTING UP THE FEEDBACK FORM                  //
// --------------------------------------------- //

function FeedbackForm() {
	var feedbackForm = $('<div></div>')
		.attr('id', 'show-feedback');
	
	var feedbackLink = $('<a></a>')
		.attr('href', '/feedback')
		.attr('title', 'Send Feedback')
		.html('Send Feedback')
		.click(function(event, callback) {

	});
	
	$('body').append(feedbackForm.append(feedbackLink));
}

// --------------------------------------------- //
// GA TRACKING                                   //
// --------------------------------------------- //

var gaFormEventSettings = {
    "register-member": {
        "category": "New Account",
        "action": "Sign Ups",
        "validate": true
    },
    "email-a-friend-button": {
        "category": "Email to a Friend",
        "action": "Clicks"
    },
    "aa-insurance-get-quote": {
        "category": "AA Insurance - Get Quote",
        "action": "Clicks"
    }
}

function setupCustomGaTracking() {
    $('.track-ga-event').each(function(event) {
        if ($(this).is('form')) {
            $(this).submit(function(event) {
                handleGaEvent($(this));
            });
        }
        else if ($(this).is('a')) {
            $(this).click(function(event) {
                handleGaEvent($(this));
            });
        }
    });
}

function handleGaEvent(element) {
    var settings = gaFormEventSettings[element.attr('id')];
    if (settings != undefined) {
        if (settings["validate"] != undefined && settings["validate"] === true && $(this).validate().form() !== true) {
            return;
        }
        trackGaEvent(settings['category'], settings['action']);
    }
}

function trackGaEvent(category, action) {
    try {
        //alert('track ga event: ' + category + ' ' + action);
        pageTracker._trackEvent(category, action);
    }
    catch (err) { }
}

function trackGaPageview(url) {
    try {
        //alert('track ga page view: ' + url);
        pageTracker._trackPageview(url);
    }
    catch (err) { }
}