﻿/*
*   global $j, Page_Validators, console
*
*   Main library for myFiat area
*   @updated 10/03/10:  Andrea Ottolina |   First revision
*/

/*  
*   Input Class
*/
var Input = function ($ref) {
	var _$ref = $ref,
		_netId = $ref.attr('id'),
		_origId = _netId.split('_').pop(),
	// Alternatively: var id = $ref.attr('name').split('$').pop();
	_validators = [];
	for (var i = 0; i < Page_Validators.length; i++) {
		if (Page_Validators[i].controltovalidate === _netId) {
			_validators.push(Page_Validators[i]);
		}
	}
	this.get$ref = function () {
		return _$ref;
	};
	this.getNetId = function () {
		return _netId;
	};
	this.getOrigId = function () {
		return _origId;
	};
	this.getValidators = function () {
		return _validators;
	};
	this.getIsValid = function () {
		var isValid = true;
		for (var i = 0; i < _validators.length; i++) {
			ValidatorValidate(_validators[i]);
			if (!_validators[i].isvalid) {
				isValid = false;
				break;
			}
		}
		return isValid;
	};
};

/*  
*   User Control Class
*/
var UserControl = function (id) {
	var _userControlID = id,
		_$ref = $j('#' + _userControlID),
		_$inputs = _$ref.find(':input'),
		_refInputs = {};
	for (var i = 0; i < _$inputs.length; i++) {
		var tempInput = new Input(_$inputs.eq(i));
		_refInputs[tempInput.getOrigId()] = tempInput;
	}
	this.get$ref = function () {
		return _$ref;
	};
	this.get$Input = function (origId) {
		if (_refInputs[origId]) {
		    return _refInputs[origId].get$ref();
		} else {
            if (window.console) console.log('called "get$ref()" but missing inputField: ' + origId);
        }
	};
	this.getInputValidators = function (origId) {
		if (_refInputs[origId]) {
		    return _refInputs[origId].getValidators();
		} else {
            if (window.console) console.log('called "getValidators()" but missing inputField: ' + origId);
        }
	};
	this.getInputIsValid = function (origId) {
		if (_refInputs[origId]) {
    		return _refInputs[origId].getIsValid();
		} else {
            if (window.console) console.log('called "getIsValid()" but missing inputField: ' + origId);
        }
	};
};

/*  
*   Main NameSpace Creation
*/
if (!myFiat) {
	var myFiat = {};
}

/*  
*   Functions
*/
myFiat.personalDetails = {
	userControl: null,
	init: function (options) {
		var self = this;
		var defaults = {
			userControl: 'personalDetailsUserControl'
		}
		var options = $j.extend(true, {}, defaults, options);
		if (!self.userControl) {
            try {
			    self.userControl = new UserControl(options.userControl);
			}
			catch(err) {
			    if (window.console) console.log(err);
			}
		};
	}
};
myFiat.accountDetails = {
	userControl: null,
	init: function (options) {
		var self = this;
		var defaults = {
			userControl: 'accountDetailsUserControl',
			checkUserNameAvail: {
				active: true,
				checkField: 'userNameCreateTextBox',
				buttonTrigger: 'userNameAvailabilityCheckButton',
				comment: 'span.comment'
			},
			useMyEmailCheck: {
				active: true,
				checkBox: 'useMyEmailCheckBox',
				userNameField: 'userNameCreateTextBox',
				emailOverrideField: undefined //if set, it override the standard check for "personal details" fields.
			},
			passwordStrengh: {
				active: true,
				checkField: 'passwordCreateTextBox',
				comment: 'span.comment'
			}
		}
		var options = $j.extend(true, {}, defaults, options);
		if (!self.userControl) {
			try {
			    self.userControl = new UserControl(options.userControl);
			    if (options.checkUserNameAvail.active) checkUserNameAvail();
			    if (options.useMyEmailCheck.active) useMyEmailCheck();
			    if (options.passwordStrengh.active) passwordStrengh();
			}
			catch(err) {
			    if (window.console) console.log(err);
			}
		}

		function checkUserNameAvail() {
			var MINLENGTH = 6,
				$checkField = self.userControl.get$Input(options.checkUserNameAvail.checkField),
				$buttonTrigger = self.userControl.get$ref().find('#' + options.checkUserNameAvail.buttonTrigger).hide(),
				$comment = $checkField.nextAll(options.checkUserNameAvail.comment),
				updateStatus = function () {
				    var returnValue = false;
				    if ($checkField.val().length >= MINLENGTH) {
					    $buttonTrigger.fadeIn('fast');
					    $comment.html('');
					    returnValue = true;
				    } else {
					    $buttonTrigger.hide();
				    }
				    return returnValue;
			    },
				bindEvents = function () {
				    $checkField.bind('keyup change', function () {
					    updateStatus();
				    });
				    $buttonTrigger.bind('click', function (evt) {
					    evt.preventDefault();
					    if (updateStatus()) {
						    $comment.html('Searching...');
						    $buttonTrigger.hide();
						    $j.ajax({
							    type: "POST",
							    url: '/webservices/LoyaltyScheme/UserRegistrationService.asmx/IsUserNameAvailable',
							    data: "{'userName':'" + $checkField.val() + "'}",
							    contentType: "application/json; charset=utf-8",
							    dataType: "json",
							    success: function (msg) {
								    if (msg.d.IsAvailable) {
									    $comment.html('<span class="isOK">Available</span>');
								    } else {
									    $comment.html('<span class="isNotOK">Not Available</span><br />We suggest: ');
									    for (var i = 0; i < msg.d.SuggestedNames.length; i++) {
										    var name = $j('<a href="#"><span class="isOK">' + msg.d.SuggestedNames[i] + '</span></a>').bind('click', function (e) {
											    e.preventDefault();
											    $checkField.val($j(this).text());
											    $comment.empty();
										    });
										    $comment.append(name);
										    if (i < msg.d.SuggestedNames.length - 1) $comment.append(', ');
									    }
								    }
							    }
						    });
					    }
				    });
			    };
			updateStatus();
			bindEvents();
		};

		function useMyEmailCheck() {
			var $checkBox = self.userControl.get$Input(options.useMyEmailCheck.checkBox),
				$userNameField = self.userControl.get$Input(options.useMyEmailCheck.userNameField),
				$emailOverrideField = self.userControl.get$Input(options.useMyEmailCheck.emailOverrideField),
				updateStatus = function (emailOverride) {
				    var emailUserName = '',
				        isChecked = $checkBox.is(':checked'),
				        shouldBeChecked = false;
				        
                    if (isChecked) {
				        if (emailOverride) {
				            emailUserName = $emailOverrideField.val();
				            shouldBeChecked = true;
				        } else if (myFiat.personalDetails.userControl.getInputIsValid('emailTextBox') && myFiat.personalDetails.userControl.getInputIsValid('confirmEmailTextBox')) {
					        emailUserName = myFiat.personalDetails.userControl.get$Input('emailTextBox').val();
				            shouldBeChecked = true;
				        }
				    }
				    $userNameField.val(emailUserName);
				    $userNameField.trigger('keyup');
				    shouldBeChecked ? $checkBox.attr('checked', true) : $checkBox.removeAttr('checked');
				    // the line below interfere with .NET validation - TODO: reimplement
				    // shouldBeChecked ? $userNameField.attr('disabled', true) : $userNameField.removeAttr('disabled');
			        shouldBeChecked ? $userNameField.attr('readonly', 'readonly') : $userNameField.removeAttr('readonly');
			    },
				bindEvents = function (emailOverride) {
				    $checkBox.bind('click', function (e) {
				        /* 
				        * be aware: clicking on a checkbox changes its status before and then calls the function
					    * in order to trigger the click from script you should manually set the status and then
					    * trigger the event without the browser default behaviour:
						* $checkBox[0].checked = !$checkBox[0].checked;
						* $checkBox.triggerHandler('click');
                        */
					    updateStatus(emailOverride);
				    });
				    if (!emailOverride) {
				        myFiat.personalDetails.userControl.get$Input('emailTextBox').bind('change', function () {
					        updateStatus(emailOverride);
				        });
				        myFiat.personalDetails.userControl.get$Input('confirmEmailTextBox').bind('change', function () {
					        updateStatus(emailOverride);
				        });
				    }
			    };
			if ($emailOverrideField) {
                bindEvents(true);
			} else {
			    myFiat.personalDetails.init();
			    if (myFiat.personalDetails.userControl.get$Input('emailTextBox') && myFiat.personalDetails.userControl.get$Input('confirmEmailTextBox')) {
				    bindEvents(false);
			    }
			}
		};

		function passwordStrengh() {
			var MINLENGTH = 6,
				$checkField = self.userControl.get$Input(options.passwordStrengh.checkField),
				$comment = $checkField.nextAll(options.passwordStrengh.comment),
				strengthMex = [
				    'Unsecure',
				    'Weak',
				    'Medium',
				    'Strong',
				    'Very Strong'
				    ],
				origMex = $comment.html();
			updateStatus = function () {
				var psw = $checkField.val(),
					score = 0;
				if (psw.length >= MINLENGTH) score = 1;
				if (psw.length >= MINLENGTH + 2) score = 2;
				if ((psw.match(/[a-z]/)) && (psw.match(/[A-Z]/))) score++;
				if (psw.match(/\d+/)) score++;
				if (psw.match(/.[!,@,#,$,%,^,&,*,?,_,~,-,(,)]/)) score++;
				if (score >= strengthMex.length) score = strengthMex.length-1;
				if (psw.length > 0) {
					$comment.html('<span class="strength' + score + '">' + strengthMex[score] + ' password</span>');
				} else {
					$comment.html(origMex);
				}
			},
			bindEvents = function () {
				$checkField.bind('keyup change', function () {
					updateStatus();
				});
			};
			updateStatus();
			bindEvents();
		};
	}
};
myFiat.contactPreferences = {
	userControl: null,
	init: function (options) {
		var self = this;
		var defaults = {
			userControl: 'contactPreferencesUserControl',
			preferencesPanel: {
				active: true,
				offersAndServicesCheckBox: 'offersAndServicesCheckBox',
				contactOptionCheckBoxes: '.optionsField input',
				panelShowHide: '.panelShowHide'
			}
		}
		var options = $j.extend(true, {}, defaults, options);
	    if (!self.userControl) {
	        try {
			    self.userControl = new UserControl(options.userControl);
			    if (options.preferencesPanel.active) preferencesPanel();
			}
			catch(err) {
			    if (window.console) console.log(err);
			}
		}
		function preferencesPanel() {
			var $offersAndServicesCheckBox = self.userControl.get$Input(options.preferencesPanel.offersAndServicesCheckBox),
				$contactOptionCheckBoxes = self.userControl.get$ref().find(options.preferencesPanel.contactOptionCheckBoxes).attr('disabled', true),
				$panelShowHide = self.userControl.get$ref().find(options.preferencesPanel.panelShowHide).hide(),
				updateStatus = function () {
				    if ($offersAndServicesCheckBox.is(':checked')) {
					    $contactOptionCheckBoxes.removeAttr('disabled');
				    } else {
					    $contactOptionCheckBoxes.attr('disabled', true).removeAttr('checked');
					    $panelShowHide.hide();
				    }
				    var panels = {};
				    $contactOptionCheckBoxes.each(function () {
					    var $checkBox = $j(this);
					    var refs = $checkBox.attr('rel').split('-');
					    for (var i = 0; i < refs.length; i++) {
						    if ($checkBox.is(':checked') && $offersAndServicesCheckBox.is(':checked')) {
							    panels[refs[i]] = true;
						    } else if (panels[refs[i]] !== true) {
							    panels[refs[i]] = false;
						    }
					    }
				    });
				    for (var item in panels) {
					    var $item = $panelShowHide.filter('#' + item);
					    (panels[item]) ? $item.show() : $item.hide();
				    }
			    },
				bindEvents = function () {
				$offersAndServicesCheckBox.bind('click', function () {
					updateStatus();
				});
				$contactOptionCheckBoxes.bind('click', function () {
					updateStatus();
				});
			};
			updateStatus();
			bindEvents();
		};
	}
};

// Dealer search
myFiat.dealerSearch = {
    userControl: null,
    init: function(options) {
        var self = this;
        var defaults = {
            userControl: 'dealerLocatorUserControl',
            findDealer: {
                active: true,
                checkField: 'postCodeTextBox',
                buttonTrigger: 'findDealerLinkButton',
                resultPanel: 'dealerLocatorResults',
                resultPanelContainer: 'dealerLocatorResultsContainer',
                dealerDetails: 'dealerDetails',
                postcode: ''
            }
        }
        var options = $j.extend(true, {}, defaults, options);
        if (!self.userControl) {
            try {
                self.userControl = new UserControl(options.userControl);
                if (options.findDealer.active) findDealer(options.findDealer.postcode);
            }
            catch (err) {
                if (window.console) console.log(err);
            }
        }
        function findDealer(withPostcode) {
            var $postCode = self.userControl.get$Input(options.findDealer.checkField),
				$buttonTrigger = self.userControl.get$ref().find('#' + options.findDealer.buttonTrigger),
				$resultPanel = $j('#' + options.findDealer.resultPanel),
				$resultPanelContainer = $j('#' + options.findDealer.resultPanelContainer),
				$dealerDetails = $j('#' + options.findDealer.dealerDetails).clone().remove(),
				doSearch = function() {
				    var minLat = 49,
					    maxLat = 61,
					    minLon = -8,
					    maxLon = 2,
					    searchLocation,
					    searchValue = $postCode.val(),
					    map = new VEMap('mapPane');
				    map.LoadMap();
				    // code to add a space into the postcode if there isn't one.
				    if (searchValue.match("([Gg][Ii][Rr] 0[Aa][Aa]|[A-Pa-pR-Ur-uWwYyZz]([0-9]{1,2}|([A-Ha-hK-Yk-y][0-9]|[A-Ha-hK-Yk-y][0-9]([0-9]|[AaBbEeHhMmNnPpRrV-Yv-y]))|[0-9][A-Ha-hJjKkS-Us-uWw]) *[0-9][AaBbD-Hd-hJjLlNnP-Up-uW-Zw-z]{2})$")) {
				        searchValue = searchValue.substr(0, searchValue.length - 3) + " " + searchValue.substr(searchValue.length - 3, 3);
				    }
				    map.Find(null, // what
				        searchValue + ", United Kingdom", // where
				        null, // VEFindType (always VEFindType.Business, relates to what search)
				        null, // VEShapeLayer
				        null, // start index for results (0 by default)
				        null, // max number of results (default = 10, range 0 - 20)
				        false, // show results (default is true)
				        null, // create pushpin for what results
				        false, // use default disambiguation (default is true)
				        null, // set best map view (default is true)
				        onFoundResults);

				    function onFoundResults(shapeLayer, findResults, e, moreResults, errorMsg) {
				        var entryFound = false,
						    pos = 0;

				        function CosineLawDistance(point1Latitude, point1Longitude, point2Latitude, point2Longitude) {
				            var R = 6371; // earth's mean radius in km
				            var d = Math.acos(Math.sin(DegreesToRadians(point1Latitude)) * Math.sin(DegreesToRadians(point2Latitude)) +
                            Math.cos(DegreesToRadians(point1Latitude)) * Math.cos(DegreesToRadians(point2Latitude)) * Math.cos(DegreesToRadians(point2Longitude) - DegreesToRadians(point1Longitude))) * R;
				            return d;
				        }

				        function DegreesToRadians(degrees) { return degrees * Math.PI / 180; }

				        if (e == null || e.length == 0 || e[0].Name.toLowerCase() == 'united kingdom') {
				            alert("No results. Please try a different search or check the spelling.");
				            return;
				        }
				        for (var i = 0; i < e.length; i++) {
				            if (e[i].Name.substr(0, searchValue.length + 1).toLowerCase().replace(" ", "") == searchValue.toLowerCase().replace(" ", "") + ",") {
				                entryFound = true;
				                pos = i;
				                break;
				            }
				        }
				        if (e.length == 1 || entryFound) {
				            if (e[pos].LatLong.Latitude > minLat && e[pos].LatLong.Latitude < maxLat && e[pos].LatLong.Longitude > minLon && e[pos].LatLong.Longitude < maxLon) {
				                var dealerList = dealer,
								    dealersToDisplay = 6,
								    searchLatitude = e[pos].LatLong.Latitude,
								    searchLongitude = e[pos].LatLong.Longitude,
								    nearestDealers = new Array(dealersToDisplay),
								    foundDealerCount = 0;
				                if (searchLocation == null) {
				                    searchLocation = new VELatLong(searchLatitude, searchLongitude);
				                }
				                for (var i = 0; i < dealerList.length; i++) {
				                    if (foundDealerCount < dealersToDisplay) foundDealerCount++;
				                    var dealerDistance = CosineLawDistance(searchLatitude, searchLongitude, dealerList[i].Latitude, dealerList[i].Longitude);
				                    for (var j = 0; j < nearestDealers.length; j++) {
				                        var addDealer = false;
				                        addDealer = nearestDealers[j] == null;
				                        if (!addDealer && dealerDistance < nearestDealers[j].Distance) {
				                            addDealer = true;
				                            for (var k = nearestDealers.length - 1; k > j; k--) {
				                                nearestDealers[k] = nearestDealers[k - 1];
				                            }
				                        }
				                        if (addDealer) {
				                            dealerList[i]['Distance'] = dealerDistance;
				                            nearestDealers[j] = dealerList[i];
				                            break;
				                        }
				                    }
				                }
				                dealersFound = nearestDealers;
				                if (foundDealerCount > 0) {
				                    for (var i = 0; i < foundDealerCount; i++) {
				                        dealersFound[i].DealerName = dealersFound[i].DealerName.toTitleCase();
				                        dealersFound[i].SiteName = dealersFound[i].SiteName.toTitleCase();
				                        dealersFound[i].Address1 = dealersFound[i].Address1.toTitleCase();
				                        dealersFound[i].Address2 = dealersFound[i].Address2.toTitleCase();
				                        dealersFound[i].Town = dealersFound[i].Town.toTitleCase();
				                        dealersFound[i].sAddress = dealersFound[i].Address1;
				                        dealersFound[i].sAddress += (dealersFound[i].sAddress != "" && dealersFound[i].Address2 != "" ? ", " : "") + dealersFound[i].Address2;
				                    }
				                    // Truncate array (if necessary).
				                    dealersFound.length = foundDealerCount;
				                    $resultPanel.hide();
				                    $resultPanelContainer.empty();
				                    for (var i = 0; i < foundDealerCount; i++) {
				                        var $newDetails = $dealerDetails.clone(),
								            currentDealer = dealersFound[i];
				                        $newDetails.find('.fn').html(currentDealer.SiteName);
				                        $newDetails.find('.distance').html(currentDealer.Distance.toFixed(2) + 'Miles');
				                        $newDetails.find('.street-address').html(currentDealer.sAddress);
				                        $newDetails.find('.locality').html(currentDealer.Town);
				                        $newDetails.find('.postal-code').html(currentDealer.ZipCode);
				                        $newDetails.find('.phone .value').html(currentDealer.Telephone);
				                        $newDetails.find('.fax .value').html(currentDealer.Fax);
				                        
				                        if (Page.isDealerASalesProvider(currentDealer.Services)) {
				                            if (currentDealer.SalesRating <= 0) {
				                                $newDetails.find('.CsiRating span').addClass('ratingNoStar');
				                                $newDetails.find('.bPop').html('This dealer doesn\'t yet have a star rating, as less than 15 customers have rated it.');
				                                $newDetails.find('.CsiRating span').html('Not yet rated');
				                            } else {
				                                $newDetails.find('.CsiRating span').addClass('starRating' + currentDealer.SalesRating);
				                                $newDetails.find('.bPop').html('These ratings show how satisfied people were with their experience of buying a vehicle or having a vehicle serviced at this dealer. The scores are generated by our customer satisfaction survey and to be rated, each dealer must have had at least 15 interviews completed in the last 3-month period. The stars reflect an average score out of 10:<br />&bull; 5 stars – average score more than 9.26<br />&bull; 4 stars – between 9.0 and 9.25<br />&bull; 3 stars - between 8.5 and 8.99<br />&bull; 2 stars - between 8.0 and 8.49<br />&bull; 1 star - below 7.99');
				                                $newDetails.find('.CsiRating span').html('Customer rating (Sales): ' + currentDealer.SalesRating + ' star(s)');
				                            }
				                        } else {
				                            $newDetails.find('.CsiRating span').addClass('starRatingNA');
				                            $newDetails.find('.CsiRating span').html('Sales rating not applicable');
				                        }

				                        if (Page.isDealerAServiceProvider(currentDealer.Services)) {
				                            if (currentDealer.ServiceRating <= 0) {
				                                $newDetails.find('.SsiRating span').addClass('ratingNoStar');
				                                $newDetails.find('.bPop').html('This dealer doesn\'t yet have a star rating, as less than 15 customers have rated it.');
				                                $newDetails.find('.SsiRating span').html('Not yet rated');
				                            } else {
				                                $newDetails.find('.SsiRating span').addClass('starRating' + currentDealer.ServiceRating);
				                                $newDetails.find('.bPop').html('These ratings show how satisfied people were with their experience of buying a vehicle or having a vehicle serviced at this dealer. The scores are generated by our customer satisfaction survey and to be rated, each dealer must have had at least 15 interviews completed in the last 3-month period. The stars reflect an average score out of 10:<br/>&bull; 5 stars – average score more than 9.26<br />&bull; 4 stars – between 9.0 and 9.25<br />&bull; 3 stars - between 8.5 and 8.99<br />&bull; 2 stars - between 8.0 and 8.49<br />&bull; 1 star - below 7.99');
				                                $newDetails.find('.SsiRating span').html('Customer rating (Sales): ' + currentDealer.ServiceRating + ' star(s)');
				                            }
				                        } else {
				                            $newDetails.find('.SsiRating span').addClass('starRatingNA');
				                            $newDetails.find('.SsiRating span').html('Service rating not applicable');
				                        }

				                        if (currentDealer.Services.length > 0) {
				                            var $services = $newDetails.find('.services'),
										        $list = $j('<ul>').appendTo($services);
				                            for (var j = 0; j < currentDealer.Services.length; j++) {
				                                $list.append('<li>' + currentDealer.Services[j].Name + '</li>');
				                            }
				                        }
				                        var postUrl = location.pathname.toString().toLowerCase().replace('default.aspx', '') + 'default.aspx' + location.search.toString();
				                        $newDetails.find('.buttonDealerDetails').addClass('buttonSmallColor').attr('target', '_blank').attr('href', '/dealerlocator/DealerInformation.aspx?isSigningUpForLoyalty=true&id=' + currentDealer.DealerId + '&siteid=' + currentDealer.SiteId);
				                        $newDetails.find('.buttonAddDealer').addClass('buttonCta')
								                                            .wrap('<form action="' + postUrl + '" method="post" />')
								                                            .before('<input name="dealerCode" type="hidden" value="' + currentDealer.DealerId + '" />')
								                                            .before('<input name="siteCode" type="hidden" value="' + currentDealer.SiteId + '" />')
								                                            .bind('click', { currentDealer: currentDealer }, function(e) {
								                                                e.preventDefault();
								                                                $j(e.target).closest('form').submit();
								                                            });
				                        $resultPanelContainer.append($newDetails);
				                        if (((i + 1) % 3) === 0 && i > 0) {
				                            $newDetails.after('<div class="clear">');
				                        }
				                    }
				                    self.userControl.get$ref().parent().addClass('noBorder');
				                    $resultPanel.fadeIn();
				                    Cufon.refresh();
				                    myFiat.balloonPopup.refresh();
				                } else {
				                    window.alert("No dealers found matching specified criteria");
				                }
				            }
				        }
				    };
				},
				bindEvents = function() {
				    $buttonTrigger.bind('click', function(e) {
				        e.preventDefault();
				        if (self.userControl.getInputIsValid(options.findDealer.checkField)) doSearch();
				    });
				    if (withPostcode != '') {
				        $postCode.val(withPostcode);
				        $buttonTrigger.trigger('click');
				    }
				};
            bindEvents();
        };
    }
};

// bubblebox
myFiat.balloonPopup = {
	initiated: false,
	opts: {
		container: '#mainContent',
		animate: true
	},
	init: function () {
		var self = this;
		if (!self.initiated) {
			self.initiated = true;
			var $bPop = $j('span.bPop:not(:empty,.ready)', self.opts.container).show().addClass('ready');
			for (var i = 0; i < $bPop.length; i++) {
				var $current = $bPop.eq(i);
				var content = $current.html();
				var $bPopLink = $j('<a href="#" class="bPopLink">more info</a>').hover(function () {
					$j(this).next('.popupWindow').stop(true, true).show();
				}, function () {
					$j(this).next('.popupWindow').stop(true, true).hide();
				});
				$current.html('<span class="popupWindow"><span class="popupHeader fixPNG"></span><span class="popupContent fixPNG">' + content + '</span><span class="popupFooter fixPNG"></span><span class="popupChevron fixPNG"></span></span>').prepend($bPopLink);
			}
		}
	},
	refresh: function () {
	    var self = this;
	    if (self.initiated) self.initiated = false;
	    self.init();
	}
};

// lightbox
myFiat.lightBox = {
    initiated: false,
    ea: [],
    current: -1,
    opts: {
        animate: false,
        container: '#mainContent',
        parent: '#mainContent',
        modal: true
    },
    widths: {
        standard: 669,
        narrow: 460
    },
    init: function() {    
        var self = this;
        if (!self.initiated) {
            self.initiated = true;
            self.$parent = $j(self.opts.parent);
            self.$container = $j(self.opts.container);
            self.$lightBoxBg = $j('<div id="lightBoxBg">').hide().css({
                opacity: '0.6'
            });
            self.$marker = $j('<input type="hidden" id="lbMarker" />');
            self.$lightBoxContent = $j('<div id="lightBoxContent" class="fixPNG" />');
            self.$lightBoxWindow = $j('<div id="lightBoxWindow" />').append(self.$lightBoxContent).append('<div id="lightBoxFooter" class="fixPNG" />').prepend('<div id="lightBoxHeader" class="fixPNG" />').hide();
            self.$lightBoxCloseButton = $j('<a class="buttonSmall"><span>Close</span></a>').prependTo(self.$lightBoxWindow).wrap('<div id="lightBoxClose">');
            self.$lightBoxCloseButton.bind('click', function() {
                self.close();
            });
            self.$container.append(self.$lightBoxBg);
            self.$parent.append(self.$lightBoxWindow);
            self.add($j('a.lbLink', self.opts.container));
        }
    },
    add: function($items) {
        var self = this;
        $items.each(function() {
            var $caller = $j(this);
            var isStatic = ($caller.attr('href').match('#')) ? true : false;
            var target = $caller.attr('href');
            self.pushItem($caller, target, isStatic);
        });
    },
    pushItem: function($caller, target, isStatic) {
        var self = this;
        var eaLength = self.ea.push({
            target: target,
            isStatic: isStatic,
            $content: (isStatic) ? $j(target).hide() : null,
            $caller: $caller
        });
        $caller.bind('click', function(e) {
            e.preventDefault();
            self.current = eaLength - 1;
            self.getContent();
        });
        return eaLength - 1;
    },
    getContent: function() {   
        var self = this;
        var obj = self.ea[self.current];
        //console.log(self)
        
        if (obj.isStatic) {
            obj.$content.after(self.$marker);
            self.open();
        } else {
            $j.get(obj.target, function(data) {
                var cleanedData = data.replace(/\r?\n/ig, "").replace(/<script(.|\s)*?\/script>/gi, "").match(/<body(.|\s)*?\/body>/gi)[0],
                        content = $j(cleanedData).find('div').filter('#column1').children().get(0);
                obj.$content = $j(content);
                self.open();
            });
        }    
    },
    open: function() {        
        var self = this;
        var obj = self.ea[self.current];
        var gutter = 50; /*Updated to move up the box for remove card holder box*/
        var windowScrollTop = $j(window).scrollTop();
        var windowHeight = $j(window).height();
        var callerTop = obj.$caller.position().top;
        var containerTop = self.$container.offset().top;
        var containerWidth = self.$container.outerWidth();
        var containerHeight = self.$container.outerHeight();
        var lbTopPos, lbHeight, lbContentScrollable;
       
        if(obj.isStatic) {
            lbTopPos = gutter + containerTop;
            lbHeight = 'auto';
            lbContentScrollable = false;

        } else {
            var wTot = windowHeight + windowScrollTop;
            var cTot = containerHeight + containerTop;
            if (containerTop < windowScrollTop) {
                lbTopPos = windowScrollTop - containerTop + gutter;
                if (wTot < cTot) {
                    lbHeight = windowHeight - 2 * gutter;
                } else {
                    lbHeight = containerHeight + containerTop - windowScrollTop - 2 * gutter;
                }
            } else {
                lbTopPos = gutter;
                if (wTot < cTot) {
                    lbHeight = windowHeight + windowScrollTop - containerTop - 2 * gutter;
                } else {
                    lbHeight = containerHeight - 2 * gutter;
                }
            }
            lbContentScrollable = true;
        }

        self.hideSelects();
        self.$lightBoxBg.css({
            width: containerWidth,
            height: containerHeight
        }).show();

        self.$lightBoxWindow.css({
            left: self.$container.css('padding-left'),
            top: lbTopPos,
            height: lbHeight
        }).show();
       
        if (obj.isStatic || true) { //always happens               	   
            self.$lightBoxContent.html(obj.$content.show());
            if (lbContentScrollable) {
                var $scrollable = self.$lightBoxContent.find('#scrollable');
                var $scrollHeight = jQuery('#scrollable').height();                
                if ($scrollHeight > '250') {
                    $scrollable.css({
                        'overflow-y': 'scroll',
                        'height': '360px' /*lbHeight - ($scrollable.position().top + self.$lightBoxContent.position().top + (self.$lightBoxContent.outerHeight() - self.$lightBoxContent.innerHeight()) + 10)*/
                    });
                } else {
                    //console.log('hi')
                    $scrollable.css({ height: $scrollHeight, 'overflow' : 'hidden' });
                }

            }
            var $closeButton = self.$lightBoxContent.find('.lbClose');
            $closeButton.bind('click', function() {
                self.close();
            });
            Cufon.refresh();
        }
    },
    close: function() {
        var self = this;
        var obj = self.ea[self.current];
        self.showSelects();
        self.$lightBoxWindow.hide();
        self.$lightBoxBg.hide();
        if (obj.isStatic) {
            self.$marker.after(obj.$content.hide());
        }
        self.$lightBoxContent.empty();
    },
    openById: function(ref) {
        var self = this;
        self.init();
        for (var i = 0; i < self.ea.length; i++) {
            if (self.ea[i].target === ref) {
                self.current = i;
                self.getContent();
                break;
            } else {
                // Add here a method to dinamically add items to the array of lightBoxes.
            }
        }
    },
    hideSelects: function() {
        $j('#mainContent').addClass('hideSelects');
    },
    showSelects: function() {
        $j('#mainContent').removeClass('hideSelects');
    }
};

// TableRows ShowHide
myFiat.tableRowsShowHide = {
    initiated: false,
    opts: {
		container: '#mainContent',
		table: 'table.showHide',
		trigger: 'a.toggle'
	},
    init: function () {
		var self = this;
		if (!self.initiated) {
			self.initiated = true;
			var $table = $j(self.opts.table, self.opts.container);
			var $buttons = $j(self.opts.trigger, self.opts.table);
			for (var i = 0; i < $buttons.length; i++ ){
			    var $button = $buttons.eq(i);
			    $button.data('$panel',$j($button.attr('href')).hide());
			    $button.click( function (e) {
			        var $panel = $j(this).data('$panel');
			        if ($panel.is(':visible')) {
                        //$j(this).find('span').text('View');
                        $panel.hide();
                    } else {
                        //$j(this).find('span').text('Hide');
                        $panel.show();
                    }
                    e.preventDefault();
			    });
			}
        }
    }
};

// Hint inside input[text]
myFiat.inputTextHint = {
    initiated: false,
    init: function (options) {
   		var self = this;
		var defaults = {
		        container: '#mainContent',
		        inputs: 'input[title]',
		        trigger: ''
		    };
		var options = $j.extend(true, {}, defaults, options);
		if (!self.initiated) {
			self.initiated = true;
			var $inputs = $j(options.inputs, options.container);
			var $trigger = $j('#' + options.trigger);
			if ( $trigger.length > 0 ) {
			    $inputs.blur( function (e) {
			        $this = $j(e.target);
			        if ( $this.val() === '' || $this.val() === $this.attr('title') ) {
                        $this.addClass('blurred').val($this.attr('title'));
                        $form = $j(this.form);
                        $form.submit( function () {
                            alert('ciao');
                        });
			        }
			    }).focus( function (e) {
			        $this = $j(e.target);
			        empty($this);
			    }).blur();
			    
			    $trigger.click( function () {
			        empty($inputs);
			    });
			};
			function empty($inputs) {
			    $inputs.each( function() {
                    $this = $j(this);
			        if ( $this.val() === $this.attr('title') ) {
                        $this.removeClass('blurred').val('');
			        }
			    });
			};
		}
    }
};
myFiat.personalDetails = {
	userControl: null,
	init: function (options) {
		var self = this;
		var defaults = {
			userControl: 'personalDetailsUserControl'
		}
		var options = $j.extend(true, {}, defaults, options);
		if (!self.userControl) {
            try {
			    self.userControl = new UserControl(options.userControl);
			}
			catch(err) {
			    if (window.console) console.log(err);
			}
		};
	}
};
Page = {
    isDealerAServiceProvider: function(services) {
        var isMemberOfTaxonomy = false;
        services.each(function(service) {
            if (service.ID == "partsAndServicing") {
                isMemberOfTaxonomy = true;
            }
        });
        return isMemberOfTaxonomy;
    },

    isDealerASalesProvider: function(services) {
        var isMemberOfTaxonomy = false;
        services.each(function(service) {
        if (service.ID == "newCarSales") {
                isMemberOfTaxonomy = true;
            }
        });
        return isMemberOfTaxonomy;
    }
};
//Utility function
String.prototype.toTitleCase = function() {
    var returnValue = this.toLowerCase();
    var splitString = returnValue.split(' ');
    for (var i = 0; i < splitString.length; i++)
        splitString[i] = splitString[i].substring(0, 1).toUpperCase() + splitString[i].substring(1).toLowerCase();
    
    returnValue = splitString.join(' ');
    
    return returnValue;
}

function ShowHideItem(itemId, show) {
    if (show) {
        $j('#' + itemId).show();
    } else {
        $j('#' + itemId).hide();
    }
}

//CardHolders title text box hide/show
$j(function () {
    $j("div.titleField select").change(function() {
        //hide the title other text box if the option value != Other 
        $j("input.titleNoLabel").hide();
        if ($j(this).val() == "Other") {
            $j("input.titleNoLabel").show();
        }
    });
});

