/* Minification failed. Returning unminified contents.
(19,1): run-time error CSS1019: Unexpected token, found '('
(19,2): run-time error CSS1019: Unexpected token, found 'function('
(19,12): run-time error CSS1031: Expected selector, found ')'
(19,12): run-time error CSS1025: Expected comma or open brace, found ')'
(19,2891): run-time error CSS1019: Unexpected token, found ')'
(19,2892): run-time error CSS1019: Unexpected token, found '('
(19,2899): run-time error CSS1031: Expected selector, found ')'
(19,2899): run-time error CSS1025: Expected comma or open brace, found ')'
(26,1): run-time error CSS1019: Unexpected token, found '('
(26,2): run-time error CSS1019: Unexpected token, found 'function('
(26,11): run-time error CSS1019: Unexpected token, found '$'
(26,12): run-time error CSS1019: Unexpected token, found ')'
(26,14): run-time error CSS1019: Unexpected token, found '{'
(27,2): run-time error CSS1019: Unexpected token, found '"use strict"'
(29,15): run-time error CSS1031: Expected selector, found '='
(29,15): run-time error CSS1025: Expected comma or open brace, found '='
(98,17): run-time error CSS1031: Expected selector, found '='
(98,17): run-time error CSS1025: Expected comma or open brace, found '='
(131,11): run-time error CSS1031: Expected selector, found '='
(131,11): run-time error CSS1025: Expected comma or open brace, found '='
(372,14): run-time error CSS1031: Expected selector, found '='
(372,14): run-time error CSS1025: Expected comma or open brace, found '='
(400,2): run-time error CSS1019: Unexpected token, found '$'
(400,12): run-time error CSS1031: Expected selector, found '='
(400,12): run-time error CSS1025: Expected comma or open brace, found '='
(413,1): run-time error CSS1019: Unexpected token, found '}'
(413,2): run-time error CSS1019: Unexpected token, found ')'
(413,3): run-time error CSS1019: Unexpected token, found '('
(413,10): run-time error CSS1031: Expected selector, found ')'
(413,10): run-time error CSS1025: Expected comma or open brace, found ')'
(414,21): run-time error CSS1031: Expected selector, found '='
(414,21): run-time error CSS1025: Expected comma or open brace, found '='
(509,26): run-time error CSS1031: Expected selector, found '='
(509,26): run-time error CSS1025: Expected comma or open brace, found '='
(662,2): run-time error CSS1019: Unexpected token, found '('
(662,3): run-time error CSS1019: Unexpected token, found 'function('
(662,12): run-time error CSS1019: Unexpected token, found '$'
(662,13): run-time error CSS1019: Unexpected token, found ')'
(662,15): run-time error CSS1019: Unexpected token, found '{'
(663,3): run-time error CSS1019: Unexpected token, found '$'
(663,10): run-time error CSS1030: Expected identifier, found '":"'
(663,10): run-time error CSS1033: Expected closing bracket, found '":"'
(663,13): run-time error CSS1031: Expected selector, found ']'
(663,13): run-time error CSS1025: Expected comma or open brace, found ']'
(677,1): run-time error CSS1019: Unexpected token, found '}'
(677,2): run-time error CSS1019: Unexpected token, found ')'
(677,3): run-time error CSS1019: Unexpected token, found '('
(677,10): run-time error CSS1031: Expected selector, found ')'
(677,10): run-time error CSS1025: Expected comma or open brace, found ')'
(680,1): run-time error CSS1019: Unexpected token, found '$'
(680,17): run-time error CSS1031: Expected selector, found '='
(680,17): run-time error CSS1025: Expected comma or open brace, found '='
(698,1): run-time error CSS1019: Unexpected token, found '$'
(698,18): run-time error CSS1031: Expected selector, found '='
(698,18): run-time error CSS1025: Expected comma or open brace, found '='
(717,1): run-time error CSS1019: Unexpected token, found '$'
(717,22): run-time error CSS1031: Expected selector, found '='
(717,22): run-time error CSS1025: Expected comma or open brace, found '='
(735,1): run-time error CSS1019: Unexpected token, found '!'
(735,2): run-time error CSS1019: Unexpected token, found 'function('
(735,12): run-time error CSS1031: Expected selector, found ')'
(735,12): run-time error CSS1025: Expected comma or open brace, found ')'
(735,147): run-time error CSS1019: Unexpected token, found '('
(735,148): run-time error CSS1019: Unexpected token, found 'function('
(735,158): run-time error CSS1031: Expected selector, found ')'
(735,158): run-time error CSS1025: Expected comma or open brace, found ')'
(735,20102): run-time error CSS1019: Unexpected token, found ')'
(738,10): run-time error CSS1031: Expected selector, found 'statusChangeCallback('
(738,10): run-time error CSS1025: Expected comma or open brace, found 'statusChangeCallback('
(762,10): run-time error CSS1031: Expected selector, found 'checkLoginState('
(762,10): run-time error CSS1025: Expected comma or open brace, found 'checkLoginState('
(768,20): run-time error CSS1031: Expected selector, found '='
(768,20): run-time error CSS1025: Expected comma or open brace, found '='
(797,1): run-time error CSS1019: Unexpected token, found '('
(797,11): run-time error CSS1031: Expected selector, found '('
(797,11): run-time error CSS1025: Expected comma or open brace, found '('
(803,2): run-time error CSS1019: Unexpected token, found '('
(803,13): run-time error CSS1031: Expected selector, found ''script''
(805,12): run-time error CSS1031: Expected selector, found '='
(805,12): run-time error CSS1025: Expected comma or open brace, found '='
(806,10): run-time error CSS1031: Expected selector, found 'register_prospect_after_facebook_login('
(806,10): run-time error CSS1025: Expected comma or open brace, found 'register_prospect_after_facebook_login('
(839,10): run-time error CSS1031: Expected selector, found 'RedirectToRegistration('
(839,10): run-time error CSS1025: Expected comma or open brace, found 'RedirectToRegistration('
(844,10): run-time error CSS1031: Expected selector, found 'fbAuth_RequireEmailPermission('
(844,10): run-time error CSS1025: Expected comma or open brace, found 'fbAuth_RequireEmailPermission('
(850,23): run-time error CSS1031: Expected selector, found ';'
(850,23): run-time error CSS1025: Expected comma or open brace, found ';'
(852,10): run-time error CSS1031: Expected selector, found 'fbAuth_EmailRequiresManualInput('
(852,10): run-time error CSS1025: Expected comma or open brace, found 'fbAuth_EmailRequiresManualInput('
(862,10): run-time error CSS1031: Expected selector, found 'fbAuth_Continue('
(862,10): run-time error CSS1025: Expected comma or open brace, found 'fbAuth_Continue('
(887,10): run-time error CSS1031: Expected selector, found 'PostMessage('
(887,10): run-time error CSS1025: Expected comma or open brace, found 'PostMessage('
(913,10): run-time error CSS1031: Expected selector, found 'RegisterProspect('
(913,10): run-time error CSS1025: Expected comma or open brace, found 'RegisterProspect('
(949,10): run-time error CSS1031: Expected selector, found 'sign_up_with_facebook('
(949,10): run-time error CSS1025: Expected comma or open brace, found 'sign_up_with_facebook('
(961,10): run-time error CSS1031: Expected selector, found 'ProcessProspectRegistrationForSignInWithFacebook('
(961,10): run-time error CSS1025: Expected comma or open brace, found 'ProcessProspectRegistrationForSignInWithFacebook('
(1000,10): run-time error CSS1031: Expected selector, found 'ProcessProspectRegistrationForSignUpWithFacebook('
(1000,10): run-time error CSS1025: Expected comma or open brace, found 'ProcessProspectRegistrationForSignUpWithFacebook('
(1044,10): run-time error CSS1031: Expected selector, found 'signOut('
(1044,10): run-time error CSS1025: Expected comma or open brace, found 'signOut('
(1050,10): run-time error CSS1031: Expected selector, found 'IsAgent('
(1050,10): run-time error CSS1025: Expected comma or open brace, found 'IsAgent('
(1071,10): run-time error CSS1031: Expected selector, found 'IsProspect('
(1071,10): run-time error CSS1025: Expected comma or open brace, found 'IsProspect('
(1093,10): run-time error CSS1031: Expected selector, found 'IsUnregisteredAgent('
(1093,10): run-time error CSS1025: Expected comma or open brace, found 'IsUnregisteredAgent('
(1115,10): run-time error CSS1031: Expected selector, found 'googleAuthSuccess('
(1115,10): run-time error CSS1025: Expected comma or open brace, found 'googleAuthSuccess('
(1141,10): run-time error CSS1031: Expected selector, found 'googleAuthError('
(1141,10): run-time error CSS1025: Expected comma or open brace, found 'googleAuthError('
(1146,10): run-time error CSS1031: Expected selector, found 'loadProfile('
(1146,10): run-time error CSS1025: Expected comma or open brace, found 'loadProfile('
(1151,10): run-time error CSS1031: Expected selector, found 'loadProfileCallback('
(1151,10): run-time error CSS1025: Expected comma or open brace, found 'loadProfileCallback('
(1168,10): run-time error CSS1031: Expected selector, found 'RegisterProspectForSocialMedia('
(1168,10): run-time error CSS1025: Expected comma or open brace, found 'RegisterProspectForSocialMedia('
(1204,10): run-time error CSS1031: Expected selector, found 'sign_up_with_google_plus('
(1204,10): run-time error CSS1025: Expected comma or open brace, found 'sign_up_with_google_plus('
(1221,10): run-time error CSS1031: Expected selector, found 'sign_up_with_google_plus_load_profile('
(1221,10): run-time error CSS1025: Expected comma or open brace, found 'sign_up_with_google_plus_load_profile('
(1226,10): run-time error CSS1031: Expected selector, found 'sign_up_with_google_plus_load_profile_callback('
(1226,10): run-time error CSS1025: Expected comma or open brace, found 'sign_up_with_google_plus_load_profile_callback('
(1243,10): run-time error CSS1031: Expected selector, found 'ProcessProspectRegistrationForSignUpWithGooglePlus('
(1243,10): run-time error CSS1025: Expected comma or open brace, found 'ProcessProspectRegistrationForSignUpWithGooglePlus('
(1285,10): run-time error CSS1031: Expected selector, found 'ProcessRegistrationForSignInWithSocialMedia('
(1285,10): run-time error CSS1025: Expected comma or open brace, found 'ProcessRegistrationForSignInWithSocialMedia('
(1333,15): run-time error CSS1031: Expected selector, found '='
(1333,15): run-time error CSS1025: Expected comma or open brace, found '='
(1334,17): run-time error CSS1031: Expected selector, found '='
(1334,17): run-time error CSS1025: Expected comma or open brace, found '='
(1336,10): run-time error CSS1031: Expected selector, found 'microsoftGraphAuthenticationHandler('
(1336,10): run-time error CSS1025: Expected comma or open brace, found 'microsoftGraphAuthenticationHandler('
(1348,10): run-time error CSS1031: Expected selector, found 'acquireTokenPopupAndCallMSGraph('
(1348,10): run-time error CSS1025: Expected comma or open brace, found 'acquireTokenPopupAndCallMSGraph('
(1366,10): run-time error CSS1031: Expected selector, found 'graphAPICallback('
(1366,10): run-time error CSS1025: Expected comma or open brace, found 'graphAPICallback('
(1388,10): run-time error CSS1031: Expected selector, found 'acquireTokenRedirectCallBack('
(1388,10): run-time error CSS1025: Expected comma or open brace, found 'acquireTokenRedirectCallBack('
(1396,10): run-time error CSS1031: Expected selector, found 'callMSGraph('
(1396,10): run-time error CSS1025: Expected comma or open brace, found 'callMSGraph('
(1422,10): run-time error CSS1031: Expected selector, found 'ProcessRegistrationForSignInWithGraph('
(1422,10): run-time error CSS1025: Expected comma or open brace, found 'ProcessRegistrationForSignInWithGraph('
(1463,10): run-time error CSS1031: Expected selector, found 'RegisterProspectForGraph('
(1463,10): run-time error CSS1025: Expected comma or open brace, found 'RegisterProspectForGraph('
(1492,10): run-time error CSS1031: Expected selector, found 'storeDeviceToken('
(1492,10): run-time error CSS1025: Expected comma or open brace, found 'storeDeviceToken('
(1509,16): run-time error CSS1031: Expected selector, found '='
(1509,16): run-time error CSS1025: Expected comma or open brace, found '='
(1519,1): run-time error CSS1019: Unexpected token, found '$'
(1519,2): run-time error CSS1019: Unexpected token, found '('
(1519,9): run-time error CSS1031: Expected selector, found ')'
(1519,9): run-time error CSS1025: Expected comma or open brace, found ')'
(1522,2): run-time error CSS1019: Unexpected token, found ')'
(1524,1): run-time error CSS1019: Unexpected token, found '$'
(1524,29): run-time error CSS1031: Expected selector, found '='
(1524,29): run-time error CSS1025: Expected comma or open brace, found '='
(1529,1): run-time error CSS1019: Unexpected token, found '$'
(1529,33): run-time error CSS1031: Expected selector, found '='
(1529,33): run-time error CSS1025: Expected comma or open brace, found '='
(1533,22): run-time error CSS1031: Expected selector, found ';'
(1533,22): run-time error CSS1025: Expected comma or open brace, found ';'
(1534,22): run-time error CSS1031: Expected selector, found ';'
(1534,22): run-time error CSS1025: Expected comma or open brace, found ';'
(1535,12): run-time error CSS1031: Expected selector, found '='
(1535,12): run-time error CSS1025: Expected comma or open brace, found '='
(1536,18): run-time error CSS1031: Expected selector, found '='
(1536,18): run-time error CSS1025: Expected comma or open brace, found '='
(1537,18): run-time error CSS1031: Expected selector, found '='
(1537,18): run-time error CSS1025: Expected comma or open brace, found '='
(1538,26): run-time error CSS1031: Expected selector, found ';'
(1538,26): run-time error CSS1025: Expected comma or open brace, found ';'
(1539,21): run-time error CSS1031: Expected selector, found '='
(1539,21): run-time error CSS1025: Expected comma or open brace, found '='
(1540,18): run-time error CSS1031: Expected selector, found ';'
(1540,18): run-time error CSS1025: Expected comma or open brace, found ';'
(1542,10): run-time error CSS1031: Expected selector, found 'ProjectStats('
(1542,10): run-time error CSS1025: Expected comma or open brace, found 'ProjectStats('
(1844,28): run-time error CSS1031: Expected selector, found '='
(1844,28): run-time error CSS1025: Expected comma or open brace, found '='
(1869,10): run-time error CSS1031: Expected selector, found 'RemoveDupicateItems('
(1869,10): run-time error CSS1025: Expected comma or open brace, found 'RemoveDupicateItems('
(1881,22): run-time error CSS1031: Expected selector, found '='
(1881,22): run-time error CSS1025: Expected comma or open brace, found '='
(1888,10): run-time error CSS1031: Expected selector, found 'InsertToProjectStats('
(1888,10): run-time error CSS1025: Expected comma or open brace, found 'InsertToProjectStats('
(1915,10): run-time error CSS1031: Expected selector, found 'InsertToStats('
(1915,10): run-time error CSS1025: Expected comma or open brace, found 'InsertToStats('
(1944,10): run-time error CSS1031: Expected selector, found 'InsertToGoogleAnalytics('
(1944,10): run-time error CSS1025: Expected comma or open brace, found 'InsertToGoogleAnalytics('
(1962,10): run-time error CSS1031: Expected selector, found 'InsertListToProjectStats('
(1962,10): run-time error CSS1025: Expected comma or open brace, found 'InsertListToProjectStats('
(1985,10): run-time error CSS1031: Expected selector, found 'resizeImg('
(1985,10): run-time error CSS1025: Expected comma or open brace, found 'resizeImg('
(2004,16): run-time error CSS1031: Expected selector, found '='
(2004,16): run-time error CSS1025: Expected comma or open brace, found '='
(2006,4): run-time error CSS1031: Expected selector, found '('
(2006,4): run-time error CSS1025: Expected comma or open brace, found '('
(2022,5): run-time error CSS1062: Expected semicolon or closing curly-brace, found '$'
(2025,19): run-time error CSS1031: Expected selector, found ';'
(2025,19): run-time error CSS1025: Expected comma or open brace, found ';'
(2027,1): run-time error CSS1019: Unexpected token, found '$'
(2027,2): run-time error CSS1019: Unexpected token, found '('
(2027,3): run-time error CSS1019: Unexpected token, found '".fullscreenVidIcon"'
(2027,23): run-time error CSS1019: Unexpected token, found ')'
(2027,25): run-time error CSS1030: Expected identifier, found 'click('
(2027,25): run-time error CSS1019: Unexpected token, found 'click('
(2027,40): run-time error CSS1031: Expected selector, found '('
(2027,40): run-time error CSS1025: Expected comma or open brace, found '('
(2030,2): run-time error CSS1019: Unexpected token, found ')'
(2032,10): run-time error CSS1031: Expected selector, found 'galleryPrev('
(2032,10): run-time error CSS1025: Expected comma or open brace, found 'galleryPrev('
(2081,10): run-time error CSS1031: Expected selector, found 'galleryNext('
(2081,10): run-time error CSS1025: Expected comma or open brace, found 'galleryNext('
(2131,10): run-time error CSS1031: Expected selector, found 'InsertAgentListToProjectStats('
(2131,10): run-time error CSS1025: Expected comma or open brace, found 'InsertAgentListToProjectStats('
(2152,15): run-time error CSS1031: Expected selector, found '='
(2152,15): run-time error CSS1025: Expected comma or open brace, found '='
(2168,17): run-time error CSS1031: Expected selector, found '='
(2168,17): run-time error CSS1025: Expected comma or open brace, found '='
(2169,23): run-time error CSS1031: Expected selector, found '='
(2169,23): run-time error CSS1025: Expected comma or open brace, found '='
(2170,18): run-time error CSS1031: Expected selector, found '='
(2170,18): run-time error CSS1025: Expected comma or open brace, found '='
(2171,17): run-time error CSS1031: Expected selector, found '='
(2171,17): run-time error CSS1025: Expected comma or open brace, found '='
(2172,17): run-time error CSS1031: Expected selector, found '='
(2172,17): run-time error CSS1025: Expected comma or open brace, found '='
(2173,18): run-time error CSS1031: Expected selector, found '='
(2173,18): run-time error CSS1025: Expected comma or open brace, found '='
(2174,25): run-time error CSS1031: Expected selector, found '='
(2174,25): run-time error CSS1025: Expected comma or open brace, found '='
(2175,1): run-time error CSS1019: Unexpected token, found '$'
(2175,2): run-time error CSS1019: Unexpected token, found '('
(2175,9): run-time error CSS1031: Expected selector, found ')'
(2175,9): run-time error CSS1025: Expected comma or open brace, found ')'
(2183,2): run-time error CSS1019: Unexpected token, found ')'
(2185,1): run-time error CSS1019: Unexpected token, found '$'
(2185,2): run-time error CSS1019: Unexpected token, found '('
(2185,11): run-time error CSS1031: Expected selector, found ')'
(2185,11): run-time error CSS1025: Expected comma or open brace, found ')'
(2256,2): run-time error CSS1019: Unexpected token, found ')'
(2258,26): run-time error CSS1031: Expected selector, found '='
(2258,26): run-time error CSS1025: Expected comma or open brace, found '='
(2291,10): run-time error CSS1031: Expected selector, found 'onShareClick('
(2291,10): run-time error CSS1025: Expected comma or open brace, found 'onShareClick('
(2298,10): run-time error CSS1031: Expected selector, found 'OpenLoginBottomLinePage('
(2298,10): run-time error CSS1025: Expected comma or open brace, found 'OpenLoginBottomLinePage('
(2302,10): run-time error CSS1031: Expected selector, found 'CloseFancyAndOpenLogin('
(2302,10): run-time error CSS1025: Expected comma or open brace, found 'CloseFancyAndOpenLogin('
(2311,10): run-time error CSS1031: Expected selector, found 'CloseMagnificBox('
(2311,10): run-time error CSS1025: Expected comma or open brace, found 'CloseMagnificBox('
(2314,10): run-time error CSS1031: Expected selector, found 'OpenThanksForSharingPopup('
(2314,10): run-time error CSS1025: Expected comma or open brace, found 'OpenThanksForSharingPopup('
(2318,10): run-time error CSS1031: Expected selector, found 'OpenOnlyThanksPopup('
(2318,10): run-time error CSS1025: Expected comma or open brace, found 'OpenOnlyThanksPopup('
(2322,10): run-time error CSS1031: Expected selector, found 'OpenLoginPopup('
(2322,10): run-time error CSS1025: Expected comma or open brace, found 'OpenLoginPopup('
(2325,10): run-time error CSS1031: Expected selector, found 'PostFollowMessageOnFaceBook('
(2325,10): run-time error CSS1025: Expected comma or open brace, found 'PostFollowMessageOnFaceBook('
(2349,10): run-time error CSS1031: Expected selector, found 'PostFollowMessageOnTwitter('
(2349,10): run-time error CSS1025: Expected comma or open brace, found 'PostFollowMessageOnTwitter('
(2354,10): run-time error CSS1031: Expected selector, found 'PostFollowMessageOnFaceBook2('
(2354,10): run-time error CSS1025: Expected comma or open brace, found 'PostFollowMessageOnFaceBook2('
(2391,10): run-time error CSS1031: Expected selector, found 'OnlySendEmailAndForProspect('
(2391,10): run-time error CSS1025: Expected comma or open brace, found 'OnlySendEmailAndForProspect('
(2412,10): run-time error CSS1031: Expected selector, found 'GetHasLeadsForProspect('
(2412,10): run-time error CSS1025: Expected comma or open brace, found 'GetHasLeadsForProspect('
(2441,10): run-time error CSS1031: Expected selector, found 'SendEmailAndGetHasLeadsForProspect('
(2441,10): run-time error CSS1025: Expected comma or open brace, found 'SendEmailAndGetHasLeadsForProspect('
(2471,10): run-time error CSS1031: Expected selector, found 'OpenSocialWindow('
(2471,10): run-time error CSS1025: Expected comma or open brace, found 'OpenSocialWindow('
(2523,10): run-time error CSS1031: Expected selector, found 'adjustPlaceholder('
(2523,10): run-time error CSS1025: Expected comma or open brace, found 'adjustPlaceholder('
(2542,1): run-time error CSS1019: Unexpected token, found '$'
(2542,2): run-time error CSS1019: Unexpected token, found '('
(2542,11): run-time error CSS1031: Expected selector, found ')'
(2542,11): run-time error CSS1025: Expected comma or open brace, found ')'
(2562,2): run-time error CSS1019: Unexpected token, found ')'
(2564,10): run-time error CSS1031: Expected selector, found 'validateEmail('
(2564,10): run-time error CSS1025: Expected comma or open brace, found 'validateEmail('
 */
/* NUGET: BEGIN LICENSE TEXT
 *
 * Microsoft grants you the right to use these script files for the sole
 * purpose of either: (i) interacting through your browser with the Microsoft
 * website or online service, subject to the applicable licensing or use
 * terms; or (ii) using the files as included with a Microsoft product subject
 * to that product's license terms. Microsoft reserves all other rights to the
 * files not expressly granted by Microsoft, whether by implication, estoppel
 * or otherwise. Insofar as a script file is dual licensed under GPL,
 * Microsoft neither took the code under GPL nor distributes it thereunder but
 * under the terms set out in this paragraph. All notices and licenses
 * below are for informational purposes only.
 *
 * NUGET: END LICENSE TEXT */
/*
** Unobtrusive Ajax support library for jQuery
** Copyright (C) Microsoft Corporation. All rights reserved.
*/
(function(a){var b="unobtrusiveAjaxClick",d="unobtrusiveAjaxClickTarget",h="unobtrusiveValidation";function c(d,b){var a=window,c=(d||"").split(".");while(a&&c.length)a=a[c.shift()];if(typeof a==="function")return a;b.push(d);return Function.constructor.apply(null,b)}function e(a){return a==="GET"||a==="POST"}function g(b,a){!e(a)&&b.setRequestHeader("X-HTTP-Method-Override",a)}function i(c,b,e){var d;if(e.indexOf("application/x-javascript")!==-1)return;d=(c.getAttribute("data-ajax-mode")||"").toUpperCase();a(c.getAttribute("data-ajax-update")).each(function(f,c){var e;switch(d){case"BEFORE":e=c.firstChild;a("<div />").html(b).contents().each(function(){c.insertBefore(this,e)});break;case"AFTER":a("<div />").html(b).contents().each(function(){c.appendChild(this)});break;case"REPLACE-WITH":a(c).replaceWith(b);break;default:a(c).html(b)}})}function f(b,d){var j,k,f,h;j=b.getAttribute("data-ajax-confirm");if(j&&!window.confirm(j))return;k=a(b.getAttribute("data-ajax-loading"));h=parseInt(b.getAttribute("data-ajax-loading-duration"),10)||0;a.extend(d,{type:b.getAttribute("data-ajax-method")||undefined,url:b.getAttribute("data-ajax-url")||undefined,cache:!!b.getAttribute("data-ajax-cache"),beforeSend:function(d){var a;g(d,f);a=c(b.getAttribute("data-ajax-begin"),["xhr"]).apply(b,arguments);a!==false&&k.show(h);return a},complete:function(){k.hide(h);c(b.getAttribute("data-ajax-complete"),["xhr","status"]).apply(b,arguments)},success:function(a,e,d){i(b,a,d.getResponseHeader("Content-Type")||"text/html");c(b.getAttribute("data-ajax-success"),["data","status","xhr"]).apply(b,arguments)},error:function(){c(b.getAttribute("data-ajax-failure"),["xhr","status","error"]).apply(b,arguments)}});d.data.push({name:"X-Requested-With",value:"XMLHttpRequest"});f=d.type.toUpperCase();if(!e(f)){d.type="POST";d.data.push({name:"X-HTTP-Method-Override",value:f})}a.ajax(d)}function j(c){var b=a(c).data(h);return!b||!b.validate||b.validate()}a(document).on("click","a[data-ajax=true]",function(a){a.preventDefault();f(this,{url:this.href,type:"GET",data:[]})});a(document).on("click","form[data-ajax=true] input[type=image]",function(c){var g=c.target.name,e=a(c.target),f=a(e.parents("form")[0]),d=e.offset();f.data(b,[{name:g+".x",value:Math.round(c.pageX-d.left)},{name:g+".y",value:Math.round(c.pageY-d.top)}]);setTimeout(function(){f.removeData(b)},0)});a(document).on("click","form[data-ajax=true] :submit",function(e){var g=e.currentTarget.name,f=a(e.target),c=a(f.parents("form")[0]);c.data(b,g?[{name:g,value:e.currentTarget.value}]:[]);c.data(d,f);setTimeout(function(){c.removeData(b);c.removeData(d)},0)});a(document).on("submit","form[data-ajax=true]",function(h){var e=a(this).data(b)||[],c=a(this).data(d),g=c&&c.hasClass("cancel");h.preventDefault();if(!g&&!j(this))return;f(this,{url:this.action,type:this.method||"GET",data:e.concat(a(this).serializeArray())})})})(jQuery);
/*! Drum.JS - v0.1dev - 2014-01-09
 * http://mb.aquarius.uberspace.de/drum.js
 *
 * Copyright (c) 2013 Marcel Bretschneider <marcel.bretschneider@gmail.com>;
 * Licensed under the MIT license */

(function($) {
	"use strict";

	var DrumIcon = (function () {
		var svgelem = function (tagName) {
			return document.createElementNS("http://www.w3.org/2000/svg", tagName);
		};
		var svgcanvas = function (width, height) {
			var svg = $(svgelem("svg"));
			$(svg).attr("width", width);
			$(svg).attr("height", height);

			var g = $(svgelem("g"));
			$(svg).append(g);

			return svg;
		};
		var container = function (className) {
			var container = document.createElement("div");
			$(container).attr("class", className);
			var inner = document.createElement("div");
			$(container).append(inner);
			return container;
		};
		var path = function (settings) {
			var p = $(svgelem("path"));
			var styles = {
				"fill" : "none",
				"stroke" : settings.dail_stroke_color,
				"stroke-width" : settings.dail_stroke_width + "px",
				"stroke-linecap" : "butt",
				"stroke-linejoin" : "miter",
				"stroke-opacity": "1"
			};
			var style = "";
			for (var i in styles) {
				$(p).attr(i, styles[i]);
			}
			return p;
		};
		return {
			up : function (settings) {
				var width = settings.dail_w;
				var height = settings.dail_h;

				var svg = svgcanvas(width, height);
				var p = path(settings); 

				$(p).attr("d", "m0," + (height + settings.dail_stroke_width) + "l" + (width/2) + ",-" + height + "l" + (width/2) + "," + height);
				$(svg).find("g").append(p);

				var cont = container("dial up");
				$(cont).find("div").append(svg);
				return cont;
			},
			down : function (settings) {
				var width = settings.dail_w;
				var height = settings.dail_h;

				var svg = svgcanvas(width, height);
				var p = path(settings); 

				$(p).attr("d", "m0,-" + settings.dail_stroke_width + "l" + (width/2) + "," + height + "l" + (width/2) + ",-" + height);
				$(svg).find("g").append(p);

				var cont = container("dial down");
				$(cont).find("div").append(svg);
				return cont;
			}
		};
	})();

	var PanelModel = function (index, data_index, settings) 
	{
		this.index = index;
		this.dataModel = new (function (data, i) {
			this.data = data;
			this.index = i;
			this.getText = function () {
				return this.data[this.index];
			};
		})(settings.data, data_index);

		this.init = function () {
			this.angle = settings.theta * index;
			this.elem = document.createElement('figure');
			$(this.elem).addClass('a' + this.angle*100);
			$(this.elem).css('opacity', '0.5');
			$(this.elem).css(
				settings.transformProp, 
				settings.rotateFn + '(' + -this.angle + 'deg) translateZ(' + settings.radius + 'px)'
			);
			this.setText();
		};
		this.setText = function () {
			$(this.elem).text(this.dataModel.getText());
		};
		this.update = function (data_index) {
			if (this.dataModel.index != data_index) {
				this.dataModel.index = data_index;
				this.setText();
			}
		};
	};

	var Drum = function(element, options, transformProp)
	{
		var HTMLselect = ($(element))[0];
		var obj = this;
		var settings = $.extend({
			panelCount : 16,
			rotateFn : 'rotateX',
			interactive: true,
			dail_w: 20,
			dail_h: 5,
			dail_stroke_color: '#999999',
			dail_stroke_width: 1
		}, options || {});

		settings.transformProp = transformProp;
		settings.rotation = 0;
		settings.distance = 0;
		settings.last_angle = 0;
		settings.theta = 360 / settings.panelCount;

		settings.initselect = HTMLselect.selectedIndex;

		settings.data = [];
		for (var i=0; i<HTMLselect.children.length; i++) {
			settings.data.push($(HTMLselect.children[i]).text());
		}

		$(element).hide();

		var wrapper = document.createElement( "div" );
		$(wrapper).addClass("drum-wrapper");
		
		if (settings.id)
			$(wrapper).attr('id', settings.id);
		else if (HTMLselect.id)
			$(wrapper).attr('id', 'drum_' + HTMLselect.id);
		else if ($(HTMLselect).attr('name'))
			$(wrapper).attr('id', 'drum_' + $(HTMLselect).attr('name'));

		$(HTMLselect).after(wrapper);

		var inner = document.createElement("div");
		$(inner).addClass("inner");
		$(inner).appendTo(wrapper);

		var container = document.createElement( "div" );
		$(container).addClass("container");		
		$(container).appendTo(inner);

		var drum = document.createElement( "div" );
		$(drum).addClass("drum");
		$(drum).appendTo(container);

		if (settings.interactive === true) {
			var dialUp = DrumIcon.up(settings);
			$(wrapper).append(dialUp);

			var dialDown = DrumIcon.down(settings);
			$(wrapper).append(dialDown);

            //Don't Show and Disable the click function for up and down
			//$(wrapper).hover(function () {
			//	$(this).find(".up").show();
			//	$(this).find(".down").show();
			//}, function () {
			//	$(this).find(".up").hide();
			//	$(this).find(".down").hide();
			//});
		}

		settings.radius = 75; //Math.round( ( $(drum).height() / 2 ) / Math.tan( Math.PI / settings.panelCount ) );
		settings.mapping = [];
		var c = 0;
		for (var i=0; i < settings.panelCount; i++) {
			if (settings.data.length == i) break;
			var j = c;
			if (c >= (settings.panelCount / 2)) {
				j = settings.data.length - (settings.panelCount - c);
			}
			c++;

			var panel = new PanelModel(i, j, settings);
			panel.init();
			settings.mapping.push(panel);

			$(drum).append(panel.elem);
		}

		var getNearest = function (deg) {

			deg = deg || settings.rotation;
			var th = (settings.theta / 2);
			var n = 360;
			var angle = ((deg + th) % n + n) % n;
			angle = angle - angle % settings.theta;
			var l = (settings.data.length - 1) * settings.theta;
			if (angle > l) {
				if (deg > 0) return l;
				else return 0;
			}
			return angle;
		};
		var getSelected = function () {
			var nearest = getNearest();
			for (var i in settings.mapping) {
				if (settings.mapping[i].angle == nearest) {
					return settings.mapping[i];
				}
			}
		};
		var update = function (selected) {
			var c, list = [], pc = settings.panelCount, ph = settings.panelCount / 2, l = settings.data.length;
			var i = selected.index; 
			var j = selected.dataModel.index;
			for (var k=j-ph; k<=j+ph-1; k++) {
				c = k;
				if (k < 0) c = l+k;
				if (k > l-1) c = k-l;
				list.push(c);
			}
			var t = list.slice(ph-i); 
			list = t.concat(list.slice(0, pc - t.length));
			for (var i=0; i<settings.mapping.length; i++) {
				settings.mapping[i].update(list[i]);
			}

			
		};
		var transform = function () {
            
		    if (navigator.userAgent.indexOf('MSIE') !== -1
                || navigator.appVersion.indexOf('Trident/') > 0) {
		        $(drum).css(settings.transformProp, 'translateZ(-' + settings.radius + 'px) ' + settings.rotateFn + '(0deg)');
		    }
            else
			$(drum).css(settings.transformProp, 'translateZ(-' + settings.radius + 'px) ' + settings.rotateFn + '(' + settings.rotation + 'deg)');

			var selected = getSelected();
			if (selected) {
				var data = selected.dataModel;
				
				var last_index = HTMLselect.selectedIndex;
				HTMLselect.selectedIndex = data.index;

				if (last_index != data.index && settings.onChange) 
					settings.onChange(HTMLselect);

				$(selected.elem).css("opacity", 1);
				$("figure:not(.a" + (selected.angle*100) + ", .hidden)", drum).css("opacity", "0.5");
				if (selected.angle != settings.last_angle) {
					settings.last_angle = selected.angle;
					update(selected);


					if (navigator.userAgent.indexOf('MSIE') !== -1
                        || navigator.appVersion.indexOf('Trident/') > 0) {
					    $(selected.elem).parent().attr('style', 'transform: translateZ(-75px) rotateX(0deg);')

					    var elementstyle = $(selected.elem).attr('style');    //"opacity: 0.5; transform: rotateX(0deg) translateZ(75px);,"
					    var elementRotateX = elementstyle.substring(elementstyle.indexOf('rotateX(') + 8, elementstyle.indexOf('deg'));
					    elementRotateX *= -1;
					    $(selected.elem).attr('style', 'opacity: 1; transform: rotateX(0deg) translateZ(75px);');

					    $($(selected.elem).parent().find("figure")).each(function (index, value) {
					        //console.log('div' + index + ' :' + $(this).attr('style'));
					        if ($(this).css('opacity') != 1) {
					            // console.log("noral");
					            var otherelementstyle = $(this).attr('style');
					            var otherelementRotateX = otherelementstyle.substring(otherelementstyle.indexOf('rotateX(') + 8, otherelementstyle.indexOf('deg'));
					            var angle = parseFloat(otherelementRotateX) + parseFloat(elementRotateX);
					            // console.log(index + ',style=' + otherelementstyle + ',rotatex=' + otherelementRotateX + ',angle=' + angle);
					            $(this).attr('style', 'opacity: 0.5; transform: rotateX(' + angle + 'deg) translateZ(75px);');
					        }
					    });
					}
				}
			}			
		};
		this.setIndex = function (dataindex) {
			var page = Math.floor(dataindex / settings.panelCount);
			var index = dataindex - (page * settings.panelCount);
			var selected = new PanelModel(index, dataindex, settings);
			update(selected);
			settings.rotation = index * settings.theta;
			transform();
		};

		this.setIndex(settings.initselect);

		this.getIndex = function () {
			return getSelected().dataModel.index;
		};

		if (typeof(Hammer) != "undefined") {
			settings.touch = new Hammer(wrapper, {
				prevent_default: true,
				no_mouseevents: true
			});
			
			settings.touch.on("dragstart", function (e) { 
				settings.distance = 0;
			});

			settings.touch.on("drag", function (e) {
			    var evt = ["up", "down"];
			    if ((navigator.userAgent.indexOf('MSIE') !== -1
                    || navigator.appVersion.indexOf('Trident/') > 0)) {
			        transform();
			        $('.drum').attr("style", "transform: translateZ(-75px) rotateX(0deg);");
			    }
			    else {
			        if (evt.indexOf(e.gesture.direction) >= 0) {
			            e.gesture.deltaY = e.gesture.deltaY < -135 ? -135 : e.gesture.deltaY;//Lower Range: 6 items * 22.5
			            e.gesture.deltaY = e.gesture.deltaY > 135 ? 135 : e.gesture.deltaY;//Upper Range: 6 items * 22.5
			            settings.rotation += Math.round(e.gesture.deltaY - settings.distance) * -1;
			            transform();
			            settings.distance = e.gesture.deltaY;
			        }
			    }
			});

			settings.touch.on("dragend", function (e) {
				settings.rotation = getNearest();
				transform();
			});
		}

		if (settings.interactive) {
			$(dialUp).click(function (e) {
				var deg = settings.rotation + settings.theta + 1;
				settings.rotation = getNearest(deg);
				transform();
			});
			$(dialDown).click(function (e) {
				var deg = settings.rotation - settings.theta - 1;
				settings.rotation = getNearest(deg);
				transform();
			});			
		}
	};

	var methods = {
		getIndex : function () {
			if ($(this).data('drum'))
				return $(this).data('drum').getIndex();
			return false;
		},
		setIndex : function (index) {
			if ($(this).data('drum'))
				$(this).data('drum').setIndex(index);
		},
		init : function (options) {
			var transformProp = false;
			var prefixes = 'transform WebkitTransform MozTransform OTransform msTransform'.split(' ');
			for(var i = 0; i < prefixes.length; i++) {
				if(document.createElement('div').style[prefixes[i]] !== undefined) {
					transformProp = prefixes[i];
				}
			}
			if (transformProp) {
				var element = $(this);
				if (!element.data('drum')) {
					var drum = new Drum(element, options, transformProp);
					element.data('drum', drum);
				}
			}
		}
	};

	$.fn.drum = function(methodOrOptions)
	{
		var _arguments = arguments;
		return this.each(function() {
			if ( methods[methodOrOptions] ) {
				return methods[ methodOrOptions ].apply( this, Array.prototype.slice.call( _arguments, 1 ));
			} else if ( typeof methodOrOptions === 'object' || ! methodOrOptions ) {
				return methods.init.apply( this, _arguments );
			} else {
				$.error( 'Method ' +  methodOrOptions + ' does not exist on jQuery.drum' );
			}
		});
	};
})(jQuery);
var DateDrumHelpers = {
	allMonths: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
	allWeekDays: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
    htmlTemplate: '<div class="date_wrapper outside">' +
                        '<form>' +
                            '<div class="lines"><span id="weekday" class="weekday"></span></div>' +
                            '<select class="date" name="month"></select>' +
                            '<select class="date" name="day"></select>' +
                            '<select class="date" name="year"></select>' +
                            '<select class="date" name="hours"></select>' +
                            '<select class="date" name="minutes"></select>' +
                            '<select class="date" name="time-am-pm"></select>' +
                        '</form>' +
                    '</div>',
    yearRange: 200,//Should be even, half of it before current date and half of it after
    Pad: function (number) {
        if (number < 10) {
            return '0' + number;
        }
        return number;
	},
	PopulateWeekDayOptions: function () {
		var allOptionHtml = "";
		for (var i = 0; i < DateDrumHelpers.allWeekDays.length; i++) {
			allOptionHtml += "<span data-value=" + i + ">" + DateDrumHelpers.allWeekDays[i] + "</span>";
		}
		return allOptionHtml;
	},
    PopulateMonthOptions: function () {
        var allOptionHtml = "";
        for (var i = 0; i < DateDrumHelpers.allMonths.length; i++) {
            allOptionHtml += "<option value=" + i + ">" + DateDrumHelpers.allMonths[i] + "</option>";
        }
        return allOptionHtml;
    },
    PopulateDayOptions: function () {
        var allOptionHtml = "";
        for (var i = 1; i <= 31; i++) {
            allOptionHtml += "<option value=" + i + ">" + i + "</option>";
        }
        return allOptionHtml;
    },
    PopulateYearOptions: function () {
        var dateTime = new Date();
        var allOptionHtml = "";
        var nYear = dateTime.getFullYear() - DateDrumHelpers.yearRange / 2;
        for (var i = 0; i <= DateDrumHelpers.yearRange; i++) {
            allOptionHtml += "<option value=" + i + ">" + nYear + "</option>";
            nYear++;
        }
        return allOptionHtml;
    },
    PopulateHourOptions: function () {
        var allOptionHtml = "";
        for (var i = 0; i < 24; i++) {
            var ampmHour = (i + 1) % 12;
            if (ampmHour === 0) ampmHour = 12;
            var tempOptionHtml = "<option value=" + ampmHour + ">" + ampmHour + "</option>";
            allOptionHtml += tempOptionHtml;
        }
        return allOptionHtml;
    },
    PopulateMinuteOptions: function () {
        var allOptionHtml = "";
        for (var k = 0; k < 2; k++) {
            for (var i = 0; i < 60; i += 5) {
                var tempOptionHtml = "<option value=" + i + ">" + this.Pad(i) + "</option>";
                allOptionHtml += tempOptionHtml;
            }
        }
        return allOptionHtml;
    },
    PopulateAmPmOptions: function () {
        var allOptionHtml = '<option value="0">AM</option><option value="1">PM</option>';
        return allOptionHtml;
    },
    GetIndexForValue: function ($elem, value) {
        var returnValue = "100";
        $elem.find("option").each(function () {
            if ($(this).text().trim() === value)
                returnValue = $(this).val();
        });
        return returnValue;
    },
    AddFiveMinutes: function (dateTimeObj) {
        var floorDivision = Math.floor(dateTimeObj.getMinutes() / 5);
        var ceilDivision = Math.ceil(dateTimeObj.getMinutes() / 5);
        if (floorDivision === ceilDivision)
            return dateTimeObj;

        dateTimeObj.setMinutes(floorDivision * 5 + 5);
        return dateTimeObj;
    }
};

var IphoneDateTimePicker = function ($dateSection, existingDate, onChangeCallBack) {
    $dateSection.html(DateDrumHelpers.htmlTemplate);

	var $day = $dateSection.find("[name='day']");
	var $weekday = $dateSection.find("#weekday");
    var $month = $dateSection.find("[name='month']");
    var $year = $dateSection.find("[name='year']");
    var $hour = $dateSection.find("[name='hours']");
    var $minute = $dateSection.find("[name='minutes']");
    var $amPm = $dateSection.find("[name='time-am-pm']");

    var calledFromUpdate = false;
    var SelectedDateTimeBySelector = function () {
        var dateString = $day.find("option:selected").text().trim() + " " + $month.find("option:selected").text().trim() + " " + $year.find("option:selected").text().trim() + " " + DateDrumHelpers.Pad($hour.find("option:selected").text().trim()) + ":" + $minute.find("option:selected").text().trim() + ":00 " + $amPm.find("option:selected").text().trim();
        return dateString;
    }
    var UpdateDateTimeWithDrum = function (dateTimeObj, OnlyDateMonth) {
        calledFromUpdate = true;
        dateTimeObj = DateDrumHelpers.AddFiveMinutes(dateTimeObj);
        $day.drum('setIndex', dateTimeObj.getDate() - 1);
        $month.drum('setIndex', dateTimeObj.getMonth());
        if (!OnlyDateMonth) {
            var minutesIndex = Math.ceil(dateTimeObj.getMinutes() / 5);
            var currentAmPmValue = dateTimeObj.getHours() < 12 ? 0 : 1;
            var amPmHour = dateTimeObj.getHours() % 12;
            if (amPmHour === 0) amPmHour = 12;
            $year.drum('setIndex', DateDrumHelpers.GetIndexForValue($year, dateTimeObj.getFullYear().toString()));
            $hour.drum('setIndex', amPmHour - 1);
            $minute.drum('setIndex', minutesIndex);
            $amPm.drum('setIndex', currentAmPmValue);
        }
        calledFromUpdate = false;
    };
    var initDate = new Date();
    var getWeekDay = initDate.getDay();
    var parentSelector = $('#startPauseDateTime, .exclusive-agent .startDate, .exclusive-agent .endDate');
    var UpdateDayofWeek = function (getWeekDay, parentSelector) {
		parentSelector.find('#weekday span').hide();
    	parentSelector.find('[data-value="' + getWeekDay + '"]').show();
    };
    try
    {
        Hammer.plugins.fakeMultitouch();
    }
    catch(e)
    {
		console.log();
	}
	$weekday.html(DateDrumHelpers.PopulateWeekDayOptions());
    $day.html(DateDrumHelpers.PopulateDayOptions());
    $month.html(DateDrumHelpers.PopulateMonthOptions());
    $year.html(DateDrumHelpers.PopulateYearOptions());
    $hour.html(DateDrumHelpers.PopulateHourOptions());
    $minute.html(DateDrumHelpers.PopulateMinuteOptions());
    $amPm.html(DateDrumHelpers.PopulateAmPmOptions());

    var isChanged = false;

    $dateSection.find("[name='day'], [name='month'], [name='year'], [name='hours'], [name='minutes'], [name='time-am-pm']").drum({
        onChange: function (ctrl) {
            if (calledFromUpdate === false) {
                isChanged = true;

                if (onChangeCallBack !== 'undefined' && typeof onChangeCallBack === 'function') {
                    onChangeCallBack();
                }

                if ($(ctrl).attr("name") === "year" || $(ctrl).attr("name") === "day" || $(ctrl).attr("name") === "month") {
                    var date = new Date(SelectedDateTimeBySelector());
                    UpdateDateTimeWithDrum(date, false);
                    UpdateDayofWeek(date.getDay(), $(ctrl).parents('.dvDateForm'));
                }
            }
        }
    });

    var dragmouse = 0;
    $dateSection.find("figure")
        .mousedown(function () {
            dragmouse = 0;
        })
    .mousemove(function () {
        dragmouse = 1;
    });
    $dateSection.find("figure").mouseup(function () {
        if (dragmouse) {
            dragmouse = 0;
            return;
        }
        var $currentList = $(this).parents(".drum-wrapper").prev();
        var currentText = $(this).text().trim();
        var currentIndex = DateDrumHelpers.GetIndexForValue($currentList, currentText);

        if ($currentList.attr("name") === "year" || $currentList.attr("name") === "month" || $currentList.attr("name") === "day") {

            var date = new Date(SelectedDateTimeBySelector());
            if ($currentList.attr("name") === "year") {
                date.setFullYear($(this).text().trim());
            }
            else if ($currentList.attr("name") === "month") {
                date.setMonth(currentIndex);
            }
            else if ($currentList.attr("name") === "day") {
                date.setDate(currentIndex);
            }

            UpdateDateTimeWithDrum(date, false);
            UpdateDayofWeek(date.getDay(), $(this).parents('.dvDateForm'));

            if (onChangeCallBack !== 'undefined' && typeof onChangeCallBack === 'function') {
                onChangeCallBack();
            }

            return;
        }

        if ($currentList.attr("name") === "hours") currentIndex--;
        if ($currentList.attr("name") === "minutes") currentIndex /= 5;
        $currentList.drum('setIndex', currentIndex);
    });

    var dateTimeObj = (existingDate === undefined || existingDate === "") ? new Date() : new Date(existingDate);
    UpdateDateTimeWithDrum(dateTimeObj, false);
    UpdateDayofWeek(dateTimeObj.getDay(), $day.parents('.dvDateForm'));

    this.GetSelectedDateTime = function () {
        var dateString = this.GetSelectedDate() + " " + this.GetSelectedMonth() + " " + this.GetSelectedYear() + " " + DateDrumHelpers.Pad(this.GetSelectedHour()) + ":" + this.GetSelectedMin() + ":00 " + this.GetSelectedAmPm();
        return dateString;
    }
    this.GetSelectedDate = function () {
        return $day.find("option:selected").text().trim();
    }
    this.GetSelectedMonth = function () {
        return $month.find("option:selected").text().trim();
    }
    this.GetSelectedYear = function () {
        return $year.find("option:selected").text().trim();
    }
    this.GetSelectedHour = function () {
        return $hour.find("option:selected").text().trim();
    }
    this.GetSelectedMin = function () {
        return $minute.find("option:selected").text().trim();
    }
    this.GetSelectedAmPm = function () {
        return $amPm.find("option:selected").text().trim();
    }

    this.IsDateChange = function () {
        return isChanged;
    }
};
// http://benpickles.github.com/onScreen
;(function($) {
  $.expr[":"].onScreen = function(elem) {
    var $window = $(window)
    var viewport_top = $window.scrollTop()
    var viewport_height = $window.height()
    var viewport_bottom = viewport_top + viewport_height
    var $elem = $(elem)
    var top = $elem.offset().top
    var height = $elem.height()
    var bottom = top + height

    return (top >= viewport_top && top < viewport_bottom) ||
           (bottom > viewport_top && bottom <= viewport_bottom) ||
           (height > viewport_height && top <= viewport_top && bottom >= viewport_bottom)
  }
})(jQuery);

// http://upshots.org/javascript/jquery-test-if-element-is-in-viewport-visible-on-screen
$.fn.isOnScreen = function () {
    var win = $(window);
    var viewport = {
        top: win.scrollTop(),
        left: win.scrollLeft()
    };
    viewport.right = viewport.left + win.width();
    viewport.bottom = viewport.top + win.height();

    var bounds = this.offset();
    if (bounds == null) return false;
    bounds.right = bounds.left + this.outerWidth();
    bounds.bottom = bounds.top + this.outerHeight();

    return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));

};

$.fn.isOnContent = function (contentSelector) {
    var win = $(contentSelector);
    var viewport = win.offset();
    if (viewport == null) return false;
    viewport.right = viewport.left + win.outerWidth();
    viewport.bottom = viewport.top + win.outerHeight();

    viewport.right = viewport.left + win.width();
    viewport.bottom = viewport.top + win.height();

    var bounds = this.offset();
    if (bounds == null) return false;
    bounds.right = bounds.left + this.outerWidth();
    bounds.bottom = bounds.top + this.outerHeight();

    return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));

};

$.fn.isFullyOnScreen = function (contentSelector) {
    if ($(this).length < 1) return false;
    var docViewTop = $(contentSelector).offset().top;
    var docViewBottom = docViewTop + $(contentSelector).height();
    var docViewLeft = $(contentSelector).offset().left;
    var docViewRight = docViewLeft + $(contentSelector).width();

    var elemTop = $(this).offset().top;
    var elemBottom = elemTop + $(this).height();
    var elemLeft = $(this).offset().left;
    var elemRight = elemLeft + $(this).width();

    return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop)) && ((elemRight <= docViewRight) && (elemLeft >= docViewLeft));

};
/*! Magnific Popup - v1.1.0 - 2016-02-20
* http://dimsemenov.com/plugins/magnific-popup/
* Copyright (c) 2016 Dmitry Semenov; */
!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):a("object"==typeof exports?require("jquery"):window.jQuery||window.Zepto)}(function(a){var b,c,d,e,f,g,h="Close",i="BeforeClose",j="AfterClose",k="BeforeAppend",l="MarkupParse",m="Open",n="Change",o="mfp",p="."+o,q="mfp-ready",r="mfp-removing",s="mfp-prevent-close",t=function(){},u=!!window.jQuery,v=a(window),w=function(a,c){b.ev.on(o+a+p,c)},x=function(b,c,d,e){var f=document.createElement("div");return f.className="mfp-"+b,d&&(f.innerHTML=d),e?c&&c.appendChild(f):(f=a(f),c&&f.appendTo(c)),f},y=function(c,d){b.ev.triggerHandler(o+c,d),b.st.callbacks&&(c=c.charAt(0).toLowerCase()+c.slice(1),b.st.callbacks[c]&&b.st.callbacks[c].apply(b,a.isArray(d)?d:[d]))},z=function(c){return c===g&&b.currTemplate.closeBtn||(b.currTemplate.closeBtn=a(b.st.closeMarkup.replace("%title%",b.st.tClose)),g=c),b.currTemplate.closeBtn},A=function(){a.magnificPopup.instance||(b=new t,b.init(),a.magnificPopup.instance=b)},B=function(){var a=document.createElement("p").style,b=["ms","O","Moz","Webkit"];if(void 0!==a.transition)return!0;for(;b.length;)if(b.pop()+"Transition"in a)return!0;return!1};t.prototype={constructor:t,init:function(){var c=navigator.appVersion;b.isLowIE=b.isIE8=document.all&&!document.addEventListener,b.isAndroid=/android/gi.test(c),b.isIOS=/iphone|ipad|ipod/gi.test(c),b.supportsTransition=B(),b.probablyMobile=b.isAndroid||b.isIOS||/(Opera Mini)|Kindle|webOS|BlackBerry|(Opera Mobi)|(Windows Phone)|IEMobile/i.test(navigator.userAgent),d=a(document),b.popupsCache={}},open:function(c){var e;if(c.isObj===!1){b.items=c.items.toArray(),b.index=0;var g,h=c.items;for(e=0;e<h.length;e++)if(g=h[e],g.parsed&&(g=g.el[0]),g===c.el[0]){b.index=e;break}}else b.items=a.isArray(c.items)?c.items:[c.items],b.index=c.index||0;if(b.isOpen)return void b.updateItemHTML();b.types=[],f="",c.mainEl&&c.mainEl.length?b.ev=c.mainEl.eq(0):b.ev=d,c.key?(b.popupsCache[c.key]||(b.popupsCache[c.key]={}),b.currTemplate=b.popupsCache[c.key]):b.currTemplate={},b.st=a.extend(!0,{},a.magnificPopup.defaults,c),b.fixedContentPos="auto"===b.st.fixedContentPos?!b.probablyMobile:b.st.fixedContentPos,b.st.modal&&(b.st.closeOnContentClick=!1,b.st.closeOnBgClick=!1,b.st.showCloseBtn=!1,b.st.enableEscapeKey=!1),b.bgOverlay||(b.bgOverlay=x("bg").on("click"+p,function(){b.close()}),b.wrap=x("wrap").attr("tabindex",-1).on("click"+p,function(a){b._checkIfClose(a.target)&&b.close()}),b.container=x("container",b.wrap)),b.contentContainer=x("content"),b.st.preloader&&(b.preloader=x("preloader",b.container,b.st.tLoading));var i=a.magnificPopup.modules;for(e=0;e<i.length;e++){var j=i[e];j=j.charAt(0).toUpperCase()+j.slice(1),b["init"+j].call(b)}y("BeforeOpen"),b.st.showCloseBtn&&(b.st.closeBtnInside?(w(l,function(a,b,c,d){c.close_replaceWith=z(d.type)}),f+=" mfp-close-btn-in"):b.wrap.append(z())),b.st.alignTop&&(f+=" mfp-align-top"),b.fixedContentPos?b.wrap.css({overflow:b.st.overflowY,overflowX:"hidden",overflowY:b.st.overflowY}):b.wrap.css({top:v.scrollTop(),position:"absolute"}),(b.st.fixedBgPos===!1||"auto"===b.st.fixedBgPos&&!b.fixedContentPos)&&b.bgOverlay.css({height:d.height(),width:d.width(),position:"absolute"}),b.st.enableEscapeKey&&d.on("keyup"+p,function(a){27===a.keyCode&&b.close()}),v.on("resize"+p,function(){b.updateSize()}),b.st.closeOnContentClick||(f+=" mfp-auto-cursor"),f&&b.wrap.addClass(f);var k=b.wH=v.height(),n={};if(b.fixedContentPos&&b._hasScrollBar(k)){var o=b._getScrollbarSize();o&&(n.marginRight=o)}b.fixedContentPos&&(b.isIE7?a("body, html").css("overflow","hidden"):n.overflow="hidden");var r=b.st.mainClass;return b.isIE7&&(r+=" mfp-ie7"),r&&b._addClassToMFP(r),b.updateItemHTML(),y("BuildControls"),a("html").css(n),b.bgOverlay.add(b.wrap).prependTo(b.st.prependTo||a(document.body)),b._lastFocusedEl=document.activeElement,setTimeout(function(){b.content?(b._addClassToMFP(q),b._setFocus()):b.bgOverlay.addClass(q),d.on("focusin"+p,b._onFocusIn)},16),b.isOpen=!0,b.updateSize(k),y(m),c},close:function(){b.isOpen&&(y(i),b.isOpen=!1,b.st.removalDelay&&!b.isLowIE&&b.supportsTransition?(b._addClassToMFP(r),setTimeout(function(){b._close()},b.st.removalDelay)):b._close())},_close:function(){y(h);var c=r+" "+q+" ";if(b.bgOverlay.detach(),b.wrap.detach(),b.container.empty(),b.st.mainClass&&(c+=b.st.mainClass+" "),b._removeClassFromMFP(c),b.fixedContentPos){var e={marginRight:""};b.isIE7?a("body, html").css("overflow",""):e.overflow="",a("html").css(e)}d.off("keyup"+p+" focusin"+p),b.ev.off(p),b.wrap.attr("class","mfp-wrap").removeAttr("style"),b.bgOverlay.attr("class","mfp-bg"),b.container.attr("class","mfp-container"),!b.st.showCloseBtn||b.st.closeBtnInside&&b.currTemplate[b.currItem.type]!==!0||b.currTemplate.closeBtn&&b.currTemplate.closeBtn.detach(),b.st.autoFocusLast&&b._lastFocusedEl&&a(b._lastFocusedEl).focus(),b.currItem=null,b.content=null,b.currTemplate=null,b.prevHeight=0,y(j)},updateSize:function(a){if(b.isIOS){var c=document.documentElement.clientWidth/window.innerWidth,d=window.innerHeight*c;b.wrap.css("height",d),b.wH=d}else b.wH=a||v.height();b.fixedContentPos||b.wrap.css("height",b.wH),y("Resize")},updateItemHTML:function(){var c=b.items[b.index];b.contentContainer.detach(),b.content&&b.content.detach(),c.parsed||(c=b.parseEl(b.index));var d=c.type;if(y("BeforeChange",[b.currItem?b.currItem.type:"",d]),b.currItem=c,!b.currTemplate[d]){var f=b.st[d]?b.st[d].markup:!1;y("FirstMarkupParse",f),f?b.currTemplate[d]=a(f):b.currTemplate[d]=!0}e&&e!==c.type&&b.container.removeClass("mfp-"+e+"-holder");var g=b["get"+d.charAt(0).toUpperCase()+d.slice(1)](c,b.currTemplate[d]);b.appendContent(g,d),c.preloaded=!0,y(n,c),e=c.type,b.container.prepend(b.contentContainer),y("AfterChange")},appendContent:function(a,c){b.content=a,a?b.st.showCloseBtn&&b.st.closeBtnInside&&b.currTemplate[c]===!0?b.content.find(".mfp-close").length||b.content.append(z()):b.content=a:b.content="",y(k),b.container.addClass("mfp-"+c+"-holder"),b.contentContainer.append(b.content)},parseEl:function(c){var d,e=b.items[c];if(e.tagName?e={el:a(e)}:(d=e.type,e={data:e,src:e.src}),e.el){for(var f=b.types,g=0;g<f.length;g++)if(e.el.hasClass("mfp-"+f[g])){d=f[g];break}e.src=e.el.attr("data-mfp-src"),e.src||(e.src=e.el.attr("href"))}return e.type=d||b.st.type||"inline",e.index=c,e.parsed=!0,b.items[c]=e,y("ElementParse",e),b.items[c]},addGroup:function(a,c){var d=function(d){d.mfpEl=this,b._openClick(d,a,c)};c||(c={});var e="click.magnificPopup";c.mainEl=a,c.items?(c.isObj=!0,a.off(e).on(e,d)):(c.isObj=!1,c.delegate?a.off(e).on(e,c.delegate,d):(c.items=a,a.off(e).on(e,d)))},_openClick:function(c,d,e){var f=void 0!==e.midClick?e.midClick:a.magnificPopup.defaults.midClick;if(f||!(2===c.which||c.ctrlKey||c.metaKey||c.altKey||c.shiftKey)){var g=void 0!==e.disableOn?e.disableOn:a.magnificPopup.defaults.disableOn;if(g)if(a.isFunction(g)){if(!g.call(b))return!0}else if(v.width()<g)return!0;c.type&&(c.preventDefault(),b.isOpen&&c.stopPropagation()),e.el=a(c.mfpEl),e.delegate&&(e.items=d.find(e.delegate)),b.open(e)}},updateStatus:function(a,d){if(b.preloader){c!==a&&b.container.removeClass("mfp-s-"+c),d||"loading"!==a||(d=b.st.tLoading);var e={status:a,text:d};y("UpdateStatus",e),a=e.status,d=e.text,b.preloader.html(d),b.preloader.find("a").on("click",function(a){a.stopImmediatePropagation()}),b.container.addClass("mfp-s-"+a),c=a}},_checkIfClose:function(c){if(!a(c).hasClass(s)){var d=b.st.closeOnContentClick,e=b.st.closeOnBgClick;if(d&&e)return!0;if(!b.content||a(c).hasClass("mfp-close")||b.preloader&&c===b.preloader[0])return!0;if(c===b.content[0]||a.contains(b.content[0],c)){if(d)return!0}else if(e&&a.contains(document,c))return!0;return!1}},_addClassToMFP:function(a){b.bgOverlay.addClass(a),b.wrap.addClass(a)},_removeClassFromMFP:function(a){this.bgOverlay.removeClass(a),b.wrap.removeClass(a)},_hasScrollBar:function(a){return(b.isIE7?d.height():document.body.scrollHeight)>(a||v.height())},_setFocus:function(){(b.st.focus?b.content.find(b.st.focus).eq(0):b.wrap).focus()},_onFocusIn:function(c){return c.target===b.wrap[0]||a.contains(b.wrap[0],c.target)?void 0:(b._setFocus(),!1)},_parseMarkup:function(b,c,d){var e;d.data&&(c=a.extend(d.data,c)),y(l,[b,c,d]),a.each(c,function(c,d){if(void 0===d||d===!1)return!0;if(e=c.split("_"),e.length>1){var f=b.find(p+"-"+e[0]);if(f.length>0){var g=e[1];"replaceWith"===g?f[0]!==d[0]&&f.replaceWith(d):"img"===g?f.is("img")?f.attr("src",d):f.replaceWith(a("<img>").attr("src",d).attr("class",f.attr("class"))):f.attr(e[1],d)}}else b.find(p+"-"+c).html(d)})},_getScrollbarSize:function(){if(void 0===b.scrollbarSize){var a=document.createElement("div");a.style.cssText="width: 99px; height: 99px; overflow: scroll; position: absolute; top: -9999px;",document.body.appendChild(a),b.scrollbarSize=a.offsetWidth-a.clientWidth,document.body.removeChild(a)}return b.scrollbarSize}},a.magnificPopup={instance:null,proto:t.prototype,modules:[],open:function(b,c){return A(),b=b?a.extend(!0,{},b):{},b.isObj=!0,b.index=c||0,this.instance.open(b)},close:function(){return a.magnificPopup.instance&&a.magnificPopup.instance.close()},registerModule:function(b,c){c.options&&(a.magnificPopup.defaults[b]=c.options),a.extend(this.proto,c.proto),this.modules.push(b)},defaults:{disableOn:0,key:null,midClick:!1,mainClass:"",preloader:!0,focus:"",closeOnContentClick:!1,closeOnBgClick:!0,closeBtnInside:!0,showCloseBtn:!0,enableEscapeKey:!0,modal:!1,alignTop:!1,removalDelay:0,prependTo:null,fixedContentPos:"auto",fixedBgPos:"auto",overflowY:"auto",closeMarkup:'<button title="%title%" type="button" class="mfp-close">&#215;</button>',tClose:"Close (Esc)",tLoading:"Loading...",autoFocusLast:!0}},a.fn.magnificPopup=function(c){A();var d=a(this);if("string"==typeof c)if("open"===c){var e,f=u?d.data("magnificPopup"):d[0].magnificPopup,g=parseInt(arguments[1],10)||0;f.items?e=f.items[g]:(e=d,f.delegate&&(e=e.find(f.delegate)),e=e.eq(g)),b._openClick({mfpEl:e},d,f)}else b.isOpen&&b[c].apply(b,Array.prototype.slice.call(arguments,1));else c=a.extend(!0,{},c),u?d.data("magnificPopup",c):d[0].magnificPopup=c,b.addGroup(d,c);return d};var C,D,E,F="inline",G=function(){E&&(D.after(E.addClass(C)).detach(),E=null)};a.magnificPopup.registerModule(F,{options:{hiddenClass:"hide",markup:"",tNotFound:"Content not found"},proto:{initInline:function(){b.types.push(F),w(h+"."+F,function(){G()})},getInline:function(c,d){if(G(),c.src){var e=b.st.inline,f=a(c.src);if(f.length){var g=f[0].parentNode;g&&g.tagName&&(D||(C=e.hiddenClass,D=x(C),C="mfp-"+C),E=f.after(D).detach().removeClass(C)),b.updateStatus("ready")}else b.updateStatus("error",e.tNotFound),f=a("<div>");return c.inlineElement=f,f}return b.updateStatus("ready"),b._parseMarkup(d,{},c),d}}});var H,I="ajax",J=function(){H&&a(document.body).removeClass(H)},K=function(){J(),b.req&&b.req.abort()};a.magnificPopup.registerModule(I,{options:{settings:null,cursor:"mfp-ajax-cur",tError:'<a href="%url%">The content</a> could not be loaded.'},proto:{initAjax:function(){b.types.push(I),H=b.st.ajax.cursor,w(h+"."+I,K),w("BeforeChange."+I,K)},getAjax:function(c){H&&a(document.body).addClass(H),b.updateStatus("loading");var d=a.extend({url:c.src,success:function(d,e,f){var g={data:d,xhr:f};y("ParseAjax",g),b.appendContent(a(g.data),I),c.finished=!0,J(),b._setFocus(),setTimeout(function(){b.wrap.addClass(q)},16),b.updateStatus("ready"),y("AjaxContentAdded")},error:function(){J(),c.finished=c.loadError=!0,b.updateStatus("error",b.st.ajax.tError.replace("%url%",c.src))}},b.st.ajax.settings);return b.req=a.ajax(d),""}}});var L,M=function(c){if(c.data&&void 0!==c.data.title)return c.data.title;var d=b.st.image.titleSrc;if(d){if(a.isFunction(d))return d.call(b,c);if(c.el)return c.el.attr(d)||""}return""};a.magnificPopup.registerModule("image",{options:{markup:'<div class="mfp-figure"><div class="mfp-close"></div><figure><div class="mfp-img"></div><figcaption><div class="mfp-bottom-bar"><div class="mfp-title"></div><div class="mfp-counter"></div></div></figcaption></figure></div>',cursor:"mfp-zoom-out-cur",titleSrc:"title",verticalFit:!0,tError:'<a href="%url%">The image</a> could not be loaded.'},proto:{initImage:function(){var c=b.st.image,d=".image";b.types.push("image"),w(m+d,function(){"image"===b.currItem.type&&c.cursor&&a(document.body).addClass(c.cursor)}),w(h+d,function(){c.cursor&&a(document.body).removeClass(c.cursor),v.off("resize"+p)}),w("Resize"+d,b.resizeImage),b.isLowIE&&w("AfterChange",b.resizeImage)},resizeImage:function(){var a=b.currItem;if(a&&a.img&&b.st.image.verticalFit){var c=0;b.isLowIE&&(c=parseInt(a.img.css("padding-top"),10)+parseInt(a.img.css("padding-bottom"),10)),a.img.css("max-height",b.wH-c)}},_onImageHasSize:function(a){a.img&&(a.hasSize=!0,L&&clearInterval(L),a.isCheckingImgSize=!1,y("ImageHasSize",a),a.imgHidden&&(b.content&&b.content.removeClass("mfp-loading"),a.imgHidden=!1))},findImageSize:function(a){var c=0,d=a.img[0],e=function(f){L&&clearInterval(L),L=setInterval(function(){return d.naturalWidth>0?void b._onImageHasSize(a):(c>200&&clearInterval(L),c++,void(3===c?e(10):40===c?e(50):100===c&&e(500)))},f)};e(1)},getImage:function(c,d){var e=0,f=function(){c&&(c.img[0].complete?(c.img.off(".mfploader"),c===b.currItem&&(b._onImageHasSize(c),b.updateStatus("ready")),c.hasSize=!0,c.loaded=!0,y("ImageLoadComplete")):(e++,200>e?setTimeout(f,100):g()))},g=function(){c&&(c.img.off(".mfploader"),c===b.currItem&&(b._onImageHasSize(c),b.updateStatus("error",h.tError.replace("%url%",c.src))),c.hasSize=!0,c.loaded=!0,c.loadError=!0)},h=b.st.image,i=d.find(".mfp-img");if(i.length){var j=document.createElement("img");j.className="mfp-img",c.el&&c.el.find("img").length&&(j.alt=c.el.find("img").attr("alt")),c.img=a(j).on("load.mfploader",f).on("error.mfploader",g),j.src=c.src,i.is("img")&&(c.img=c.img.clone()),j=c.img[0],j.naturalWidth>0?c.hasSize=!0:j.width||(c.hasSize=!1)}return b._parseMarkup(d,{title:M(c),img_replaceWith:c.img},c),b.resizeImage(),c.hasSize?(L&&clearInterval(L),c.loadError?(d.addClass("mfp-loading"),b.updateStatus("error",h.tError.replace("%url%",c.src))):(d.removeClass("mfp-loading"),b.updateStatus("ready")),d):(b.updateStatus("loading"),c.loading=!0,c.hasSize||(c.imgHidden=!0,d.addClass("mfp-loading"),b.findImageSize(c)),d)}}});var N,O=function(){return void 0===N&&(N=void 0!==document.createElement("p").style.MozTransform),N};a.magnificPopup.registerModule("zoom",{options:{enabled:!1,easing:"ease-in-out",duration:300,opener:function(a){return a.is("img")?a:a.find("img")}},proto:{initZoom:function(){var a,c=b.st.zoom,d=".zoom";if(c.enabled&&b.supportsTransition){var e,f,g=c.duration,j=function(a){var b=a.clone().removeAttr("style").removeAttr("class").addClass("mfp-animated-image"),d="all "+c.duration/1e3+"s "+c.easing,e={position:"fixed",zIndex:9999,left:0,top:0,"-webkit-backface-visibility":"hidden"},f="transition";return e["-webkit-"+f]=e["-moz-"+f]=e["-o-"+f]=e[f]=d,b.css(e),b},k=function(){b.content.css("visibility","visible")};w("BuildControls"+d,function(){if(b._allowZoom()){if(clearTimeout(e),b.content.css("visibility","hidden"),a=b._getItemToZoom(),!a)return void k();f=j(a),f.css(b._getOffset()),b.wrap.append(f),e=setTimeout(function(){f.css(b._getOffset(!0)),e=setTimeout(function(){k(),setTimeout(function(){f.remove(),a=f=null,y("ZoomAnimationEnded")},16)},g)},16)}}),w(i+d,function(){if(b._allowZoom()){if(clearTimeout(e),b.st.removalDelay=g,!a){if(a=b._getItemToZoom(),!a)return;f=j(a)}f.css(b._getOffset(!0)),b.wrap.append(f),b.content.css("visibility","hidden"),setTimeout(function(){f.css(b._getOffset())},16)}}),w(h+d,function(){b._allowZoom()&&(k(),f&&f.remove(),a=null)})}},_allowZoom:function(){return"image"===b.currItem.type},_getItemToZoom:function(){return b.currItem.hasSize?b.currItem.img:!1},_getOffset:function(c){var d;d=c?b.currItem.img:b.st.zoom.opener(b.currItem.el||b.currItem);var e=d.offset(),f=parseInt(d.css("padding-top"),10),g=parseInt(d.css("padding-bottom"),10);e.top-=a(window).scrollTop()-f;var h={width:d.width(),height:(u?d.innerHeight():d[0].offsetHeight)-g-f};return O()?h["-moz-transform"]=h.transform="translate("+e.left+"px,"+e.top+"px)":(h.left=e.left,h.top=e.top),h}}});var P="iframe",Q="//about:blank",R=function(a){if(b.currTemplate[P]){var c=b.currTemplate[P].find("iframe");c.length&&(a||(c[0].src=Q),b.isIE8&&c.css("display",a?"block":"none"))}};a.magnificPopup.registerModule(P,{options:{markup:'<div class="mfp-iframe-scaler"><div class="mfp-close"></div><iframe class="mfp-iframe" src="//about:blank" frameborder="0" allowfullscreen></iframe></div>',srcAction:"iframe_src",patterns:{youtube:{index:"youtube.com",id:"v=",src:"//www.youtube.com/embed/%id%?autoplay=1"},vimeo:{index:"vimeo.com/",id:"/",src:"//player.vimeo.com/video/%id%?autoplay=1"},gmaps:{index:"//maps.google.",src:"%id%&output=embed"}}},proto:{initIframe:function(){b.types.push(P),w("BeforeChange",function(a,b,c){b!==c&&(b===P?R():c===P&&R(!0))}),w(h+"."+P,function(){R()})},getIframe:function(c,d){var e=c.src,f=b.st.iframe;a.each(f.patterns,function(){return e.indexOf(this.index)>-1?(this.id&&(e="string"==typeof this.id?e.substr(e.lastIndexOf(this.id)+this.id.length,e.length):this.id.call(this,e)),e=this.src.replace("%id%",e),!1):void 0});var g={};return f.srcAction&&(g[f.srcAction]=e),b._parseMarkup(d,g,c),b.updateStatus("ready"),d}}});var S=function(a){var c=b.items.length;return a>c-1?a-c:0>a?c+a:a},T=function(a,b,c){return a.replace(/%curr%/gi,b+1).replace(/%total%/gi,c)};a.magnificPopup.registerModule("gallery",{options:{enabled:!1,arrowMarkup:'<button title="%title%" type="button" class="mfp-arrow mfp-arrow-%dir%"></button>',preload:[0,2],navigateByImgClick:!0,arrows:!0,tPrev:"Previous (Left arrow key)",tNext:"Next (Right arrow key)",tCounter:"%curr% of %total%"},proto:{initGallery:function(){var c=b.st.gallery,e=".mfp-gallery";return b.direction=!0,c&&c.enabled?(f+=" mfp-gallery",w(m+e,function(){c.navigateByImgClick&&b.wrap.on("click"+e,".mfp-img",function(){return b.items.length>1?(b.next(),!1):void 0}),d.on("keydown"+e,function(a){37===a.keyCode?b.prev():39===a.keyCode&&b.next()})}),w("UpdateStatus"+e,function(a,c){c.text&&(c.text=T(c.text,b.currItem.index,b.items.length))}),w(l+e,function(a,d,e,f){var g=b.items.length;e.counter=g>1?T(c.tCounter,f.index,g):""}),w("BuildControls"+e,function(){if(b.items.length>1&&c.arrows&&!b.arrowLeft){var d=c.arrowMarkup,e=b.arrowLeft=a(d.replace(/%title%/gi,c.tPrev).replace(/%dir%/gi,"left")).addClass(s),f=b.arrowRight=a(d.replace(/%title%/gi,c.tNext).replace(/%dir%/gi,"right")).addClass(s);e.click(function(){b.prev()}),f.click(function(){b.next()}),b.container.append(e.add(f))}}),w(n+e,function(){b._preloadTimeout&&clearTimeout(b._preloadTimeout),b._preloadTimeout=setTimeout(function(){b.preloadNearbyImages(),b._preloadTimeout=null},16)}),void w(h+e,function(){d.off(e),b.wrap.off("click"+e),b.arrowRight=b.arrowLeft=null})):!1},next:function(){b.direction=!0,b.index=S(b.index+1),b.updateItemHTML()},prev:function(){b.direction=!1,b.index=S(b.index-1),b.updateItemHTML()},goTo:function(a){b.direction=a>=b.index,b.index=a,b.updateItemHTML()},preloadNearbyImages:function(){var a,c=b.st.gallery.preload,d=Math.min(c[0],b.items.length),e=Math.min(c[1],b.items.length);for(a=1;a<=(b.direction?e:d);a++)b._preloadItem(b.index+a);for(a=1;a<=(b.direction?d:e);a++)b._preloadItem(b.index-a)},_preloadItem:function(c){if(c=S(c),!b.items[c].preloaded){var d=b.items[c];d.parsed||(d=b.parseEl(c)),y("LazyLoad",d),"image"===d.type&&(d.img=a('<img class="mfp-img" />').on("load.mfploader",function(){d.hasSize=!0}).on("error.mfploader",function(){d.hasSize=!0,d.loadError=!0,y("LazyLoadError",d)}).attr("src",d.src)),d.preloaded=!0}}}});var U="retina";a.magnificPopup.registerModule(U,{options:{replaceSrc:function(a){return a.src.replace(/\.\w+$/,function(a){return"@2x"+a})},ratio:1},proto:{initRetina:function(){if(window.devicePixelRatio>1){var a=b.st.retina,c=a.ratio;c=isNaN(c)?c():c,c>1&&(w("ImageHasSize."+U,function(a,b){b.img.css({"max-width":b.img[0].naturalWidth/c,width:"100%"})}),w("ElementParse."+U,function(b,d){d.src=a.replaceSrc(d,c)}))}}}}),A()});

// This is called with the results from from FB.getLoginStatus().
function statusChangeCallback(response) {
    console.log('statusChangeCallback');
    console.log(response);
    // The response object is returned with a status field that lets the
    // app know the current login status of the person.
    // Full docs on the response object can be found in the documentation
    // for FB.getLoginStatus().
    if (response.status === 'connected') {
        // Logged into your app and Facebook. 
    } else if (response.status === 'not_authorized') {
        // The person is logged into Facebook, but not your app.
        /*document.getElementById('status').innerHTML = 'Please log ' +
          'into this app.';*/
    } else {
        // The person is not logged into Facebook, so we're not sure if
        // they are logged into this app or not.
        /*document.getElementById('status').innerHTML = 'Please log ' +
          'into Facebook.';*/
    }
}

// This function is called when someone finishes with the Login
// Button.  See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
    FB.getLoginStatus(function (response) {
        statusChangeCallback(response);
    });
}

window.fbAsyncInit = function () {
    FB.init({
        appId: FacebookAppId,
        cookie: true,  // enable cookies to allow the server to access 
        // the session
        xfbml: true,  // parse social plugins on this page
        version: 'v2.7', // use graph api version 2.5
        scope: 'public_profile,email'
    });

    // Now that we've initialized the JavaScript SDK, we call 
    // FB.getLoginStatus().  This function gets the state of the
    // person visiting this page and can return one of three states to
    // the callback you provide.  They can be:
    //
    // 1. Logged into your app ('connected')
    // 2. Logged into Facebook, but not your app ('not_authorized')
    // 3. Not logged into Facebook and can't tell if they are logged into
    //    your app or not.
    //
    // These three cases are handled in the callback function.

    FB.getLoginStatus(function (response) {
        statusChangeCallback(response);
    });

};

// Load the SDK asynchronously
(function (d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

let scopes = { scope: 'public_profile,email', return_scopes: true };
function register_prospect_after_facebook_login() {
    FB.login(function (login_response) {
        if (login_response.authResponse) {
			const auth_response = login_response.authResponse;
			const granted_scopes = auth_response.grantedScopes;

			if (!granted_scopes.includes('email')) {
				fbAuth_RequireEmailPermission();
				return;
			}


			FB.api('/me', { fields: 'id,name,email,link' }, function (response) {
				const has_minimum_required_data = response.name && response.id;
				const email_address = response.email;


				if (has_minimum_required_data && email_address) {
					if (IsUnregisteredAgent(email_address) && !IsAgent(email_address) && !IsProspect(email_address)) RedirectToRegistration(email_address, 'unregisteredAgent');
					else ProcessProspectRegistrationForSignInWithFacebook(response);
				} else if (has_minimum_required_data) {
					fbAuth_EmailRequiresManualInput(response);
				} else {
					// This case should not happen.
					console.log(response);
				}
			});
		} else {
			console.log('Facebook Auth', 'User cancelled or did not complete authorization.');
        }
    }, scopes);
}

function RedirectToRegistration(email_address, account_type) {
	window.location.href = `/PublicRegistration?frompage=${account_type}&email=${email_address}`;
}

/** This function handles if the user has not granted CondoNow access to their email address. */
function fbAuth_RequireEmailPermission() {
	scopes = { scope: 'public_profile,email', return_scopes: true, auth_type: "rerequest" };
}

/** This function handles if the user has logged in with a phone number and will be required to manually enter an email address. */

let facebook_auth_data;

function fbAuth_EmailRequiresManualInput(account_data) {
	console.log('Facebook Auth', account_data);
	facebook_auth_data = account_data;
	
	$("#dvLogInWithContainer").hide();
	$('#dvRequiresEmailContainer, #dvFinishSocialMediaContainer').show();
	magnific_helpers.SetContentHight();
}

/** This function handles if the user has logged in with a phone number and will be required to manually enter an email address. */
function fbAuth_Continue(event) {
	const email_address_elem = $('#txtFbEmailAddress');
	const email_address = email_address_elem.val();

	if (Register.ValidationEmpty(email_address_elem)) {
		if (Register.ValidationEmail(email_address_elem)) {
			if (Register.ValidationHTMLTag(email_address_elem)) {
				const response = {
					id: facebook_auth_data.id,
					name: facebook_auth_data.name,
					email: email_address
				};

				if (IsUnregisteredAgent(email_address) && !IsAgent(email_address) && !IsProspect(email_address)) RedirectToRegistration(email_address, 'unregisteredAgent');
				else ProcessProspectRegistrationForSignInWithFacebook(response);
			}
		}
		else {
			//
		}
	} else {
		//
	}
}

function PostMessage(userName, response) {
    //    var opts = {
    //        message: postMessage  ,
    //        name: 'Condonow.com',
    //        link: 'https://condonow.247salescenter.com/10-14-Prince-Arthur'
    //    };
    $.get('/CustomSettings.xml', function (xml) {
        var opts = {};
        var messages = $(xml).find("fbmessage");
        for (var i = 0; i < messages.length; i++) {
            opts[messages[i].getAttribute("key")] = messages[i].getAttribute("value");
        }
        opts["message"] = opts["message"];
        opts["link"] = parent.window.location.href.replace('/Login', '');
        FB.api('/me/feed', 'post', opts, function (response) {
            if (!response || response.error) {
                //alert('Error occured');
            } else {
                //alert('Post ID: ' + response.id);
            }
        });
    });


}

function RegisterProspect(fbData) {
    var url = '/Stateless.asmx/ProcessProspectRegistrationByFacebook';
    var param = JSON.stringify({
        name: fbData.name,
        email: fbData.email,
        phone: '',
        isFBuser: true,
        isinsiderclubmember: false,
        fbProfileId: fbData.id,
        fbProfileUrl: '',
        url: encodeURIComponent(parent.window.location.pathname)
    });

    $.ajax({
        type: "POST",
        url: url,
        data: param,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        cache: false,
        success: function (data) {
            if (data.d.indexOf("newuser") >= 0) {
                // PostMessage(fbData.name, fbData);
            }
            if (data.d.indexOf("true") >= 0) {
                if(typeof parent.fcm_token !== "undefined") {
                    storeDeviceToken();
                } else parent.window.location = parent.window.location;
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log(errorThrown);
        }
    });
}

function sign_up_with_facebook() {
    FB.login(function (response) {
        if (response.authResponse) {
            FB.api('/me', { fields: 'id,name,email,link' }, function (response) {
                ProcessProspectRegistrationForSignUpWithFacebook(response);
            });
        } else {
            console.log('User cancelled login or did not fully authorize.');
        }
    }, { scope: 'public_profile,email', return_scopes: true });
}

function ProcessProspectRegistrationForSignInWithFacebook(fbData) {
    var url = '/Stateless.asmx/ProcessProspectRegistrationForSignUpWithFacebook';
    var param = JSON.stringify({
        name: fbData.name,
        email: fbData.email,
        phone: '',
        isFBuser: true,
        isinsiderclubmember: false,
        fbProfileId: fbData.id,
        fbProfileUrl: '',
        url: encodeURIComponent(parent.window.location.pathname)
    });

    $.ajax({
        type: "POST",
        url: url,
        data: param,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        cache: false,
        success: function (data) {
            if (data.d.indexOf("newuser") >= 0) {
                if (data.d.split('~').length == 2) {
                    $.cookie("FilledProspectID", data.d.split('~')[1]);
                    $.cookie("fromSocialLogin", "true");
                }
                //parent.PublicInviteColleague(fbData.email, true);
                parent.window.location = parent.window.location;
            }
            if (data.d.indexOf("emailexists") >= 0) {
                RegisterProspect(fbData);
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log(errorThrown);
        }
    });
}

function ProcessProspectRegistrationForSignUpWithFacebook(fbData) {
    var url = '/Stateless.asmx/ProcessProspectRegistrationForSignUpWithFacebook';
    var param = JSON.stringify({
        name: fbData.name,
        email: fbData.email,
        phone: '',
        isFBuser: true,
        isinsiderclubmember: false,
        fbProfileId: fbData.id,
        fbProfileUrl: '',
        url: encodeURIComponent(parent.window.location.pathname)
    });

    $.ajax({
        type: "POST",
        url: url,
        data: param,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        cache: false,
        success: function (data) {
            if (data.d.indexOf("newuser") >= 0) {
                //PostMessage(fbData.name, fbData);
            }
            if (data.d.indexOf("emailexists") >= 0) {
                //showing connect account popup
                window.location = "/ConnectAccount.aspx?socialApp=Facebook&email=" + encodeURIComponent(fbData.email);
            }
            if (data.d.indexOf("true") >= 0) {
                if (data.d.split('~').length == 2) {
                    $.cookie("FilledProspectID", data.d.split('~')[1]);
                    $.cookie("fromSocialLogin", "true");
                }
                //parent.PublicInviteColleague(fbData.email, true);
                parent.window.location = parent.window.location;
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log(errorThrown);
        }
    });
}


function signOut() {
    //gapi.auth.signOut();
}

//Google Authentication 
// Google Sign-in (new)
function IsAgent(emailID) {
    var result = false;
    $.ajax({
        type: "POST",
        url: "/Stateless.asmx/IsAgent",
        data: "{ emailID: '" + emailID + "' }",
        contentType: 'application/json; charset=utf-8',
        async: false,
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
        },
        success: function (data) {
            if (data.d) {
                result = true;
            } else {
                result = false;
            }
        }
    });
    return result;
}
function IsProspect(emailID) {
    var result = false;
    $.ajax({
        type: "POST",
        url: "/Stateless.asmx/IsProspect",
        data: "{ emailID: '" + emailID + "' }",
        contentType: 'application/json; charset=utf-8',
        async: false,
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
        },
        success: function (data) {
            if (data.d) {
                result = true;
            } else {
                result = false;
            }
        }
    });
    return result;
}
//check for agents not in condonow
function IsUnregisteredAgent(emailID) {
    var result = false;
    $.ajax({
        type: "POST",
        //url: "/Stateless.asmx/IsUnregisteredAgent",
        url: "/Stateless.asmx/IsUnregisteredAgent",
        data: "{ emailID: '" + emailID + "' }",
        contentType: 'application/json; charset=utf-8',
        async: false,
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
        },
        success: function (data) {
            if (data.d) {
                result = true;
            } else {
                result = false;
            }
        }
    });
    return result;
}
function googleAuthSuccess(googleUser) {
    if (googleAuthTrigger) {
        var profile = googleUser.getBasicProfile();
        var gData = {};
        gData.name = profile.getName();
        gData.email = profile.getEmail();
        gData.id = profile.getId();
        gData.link = '';
        gData.image = profile.getImageUrl();
        var id_token = googleUser.getAuthResponse().id_token;

        if (IsAgent(gData.email)) {
            ProcessRegistrationForSignInWithSocialMedia(gData, '/Stateless.asmx/LoginForAgentWithSocialMedia', true);
        }
        else if (IsProspect(gData.email)) {
            ProcessRegistrationForSignInWithSocialMedia(gData, '/Stateless.asmx/LoginForProspectWithSocialMedia', false);
		}
		else if (IsUnregisteredAgent(gData.email)) {
			window.location.href = "/PublicRegistration?frompage=unregisteredAgent&email=" + gData.email;
		}
        else {
            ProcessRegistrationForSignInWithSocialMedia(gData, '/Stateless.asmx/ProcessProspectRegistrationBySocialMedia', false, 'Google');
        }

    }
}
function googleAuthError() {
    console.log('Error');
    // Handle sign-in errors
}

function loadProfile() {
    var request = gapi.client.plus.people.get({ 'userId': 'me' });
    request.execute(loadProfileCallback);
}

function loadProfileCallback(obj) {
    profile = obj;

    // Filter the emails object to find the user's primary account, which might
    // not always be the first in the array. The filter() method supports IE9+.
    email = obj['emails'].filter(function (v) {
        return v.type === 'account'; // Filter out the primary email
    })[0].value; // get the email from the filtered results, should always be defined.
    var gData = {};
    gData.name = obj.displayName;
    gData.email = email;
    gData.id = obj.id;
    gData.link = obj.url;
    gData.image = obj.image.url;
    ProcessProspectRegistrationForSignInWithGooglePlus(gData, '/Stateless.asmx/ProcessProspectRegistrationForSignUpWithGooglePlus');
}

function RegisterProspectForSocialMedia(gData, url, account_type = 'Google') {
    var profileUrl = typeof gData.link != 'undefined' ? gData.link : "";
    var param = JSON.stringify({
        name: gData.name,
        email: gData.email,
        phone: '',
        isinsiderclubmember: false,
        socialMediaId: gData.id,
        googlePlusProfileUrl: profileUrl,
        socialMediaImageUrl: gData.image,
        url: encodeURIComponent(parent.window.location.pathname),
        accountType: account_type
    });

    $.ajax({
        type: "POST",
        url: url,
        data: param,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        cache: false,
        success: function (data) {
            if (data.d == "true") {
                signOut();
                if(typeof parent.fcm_token !== "undefined") {
                    storeDeviceToken();
                } else parent.window.location = parent.window.location;
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log(errorThrown);
        }
    });
}


function sign_up_with_google_plus(authResult) {
    if (authResult['g-oauth-window'] == undefined)
    { return }
    if (authResult['status']['signed_in']) {
        // Update the app to reflect a signed in user
        // Hide the sign-in button now that the user is authorized, for example:
        gapi.client.load('plus', 'v1', sign_up_with_google_plus_load_profile);
    } else {
        // Update the app to reflect a signed out user
        // Possible error values:
        //   "user_signed_out" - User is signed-out
        //   "access_denied" - User denied access to your app
        //   "immediate_failed" - Could not automatically log in the user
        // console.log('Sign-in state: ' + authResult['error']);
    }
}

function sign_up_with_google_plus_load_profile() {
    var request = gapi.client.plus.people.get({ 'userId': 'me' });
    request.execute(sign_up_with_google_plus_load_profile_callback);
}

function sign_up_with_google_plus_load_profile_callback(obj) {
    profile = obj;

    // Filter the emails object to find the user's primary account, which might
    // not always be the first in the array. The filter() method supports IE9+.
    email = obj['emails'].filter(function (v) {
        return v.type === 'account'; // Filter out the primary email
    })[0].value; // get the email from the filtered results, should always be defined.
    var gData = {};
    gData.name = obj.displayName;
    gData.email = email;
    gData.id = obj.id;
    gData.link = obj.url;
    gData.image = obj.image.url;
    ProcessProspectRegistrationForSignUpWithGooglePlus(gData, '/Stateless.asmx/ProcessProspectRegistrationForSignUpWithGooglePlus');
}

function ProcessProspectRegistrationForSignUpWithGooglePlus(gData, url) {
    var profileUrl = typeof gData.link != 'undefined' ? gData.link : "";
    var param = JSON.stringify({
        name: gData.name,
        email: gData.email,
        phone: '',
        isinsiderclubmember: false,
        googlePlusId: gData.id,
        googlePlusProfileUrl: profileUrl,
        googlePlusImageUrl: gData.image,
        url: encodeURIComponent(parent.window.location.pathname)
    });

    $.ajax({
        type: "POST",
        url: url,
        data: param,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        cache: false,
        success: function (data) {
            if (data.d.indexOf("emailexists") >= 0) {
                //showing connect account popup
                window.location = "/ConnectAccount.aspx?socialApp=Google&email=" + encodeURIComponent(gData.email);
            }
            if (data.d.indexOf("true") >= 0) {
                signOut();
                //parent.window.location = parent.window.location;
                if (data.d.split('~').length == 2) {
                    $.cookie("FilledProspectID", data.d.split('~')[1]);
                    $.cookie("fromSocialLogin", "true");
                }
                //parent.PublicInviteColleague(gData.email, true);
                parent.window.location = parent.window.location;
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log(errorThrown);
        }
    });
}

function ProcessRegistrationForSignInWithSocialMedia(gData, url, isagent, account_type = 'Google') {
    console.log(gData);
    var profileUrl = typeof gData.link != 'undefined' ? gData.link : "";
    var param = JSON.stringify({
        name: gData.name,
        email: gData.email,
        phone: '',
        isinsiderclubmember: false,
        socialMediaId: gData.id,
        googlePlusProfileUrl: profileUrl,
        socialMediaImageUrl: gData.image,
        url: encodeURIComponent(parent.window.location.pathname),
        accountType: account_type
    });
    console.log(param);
    $.ajax({
        type: "POST",
        url: url,
        data: param,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        cache: false,
        success: function (data) {

            if (data.d.indexOf("emailexists") >= 0 && isagent) {
                RegisterProspectForSocialMedia(gData, '/Stateless.asmx/ProcessAgentRegistrationBySocialMedia', account_type);
            }
            else if (data.d.indexOf("emailexists") >= 0) {
                RegisterProspectForSocialMedia(gData, '/Stateless.asmx/ProcessProspectRegistrationBySocialMedia', account_type);
            }
            else if (data.d.indexOf("true") >= 0) {
                signOut();
                if(typeof parent.fcm_token !== "undefined") {
                    storeDeviceToken();
                } else parent.window.location = parent.window.location;
                if (data.d.split('~').length == 2) {
                    $.cookie("FilledProspectID", data.d.split('~')[1]);
                    $.cookie("fromSocialLogin", "true");
                }
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log(errorThrown);
        }
    });
}

//Azure / Microsoft Graph Integration
var aad_token = '';
var aad_idToken = '';

function microsoftGraphAuthenticationHandler() {
    myMSALObj.loginPopup(applicationConfig.graphScopes).then(function (idToken) {
        aad_idToken = idToken;
        //Login Success
        //showWelcomeMessage();
        console.log('Success', idToken, myMSALObj.getUser());
        acquireTokenPopupAndCallMSGraph();
    }, function (error) {
        console.log(error);
    });
}

function acquireTokenPopupAndCallMSGraph() {
    //Call acquireTokenSilent (iframe) to obtain a token for Microsoft Graph
    parent.myMSALObj.acquireTokenSilent(applicationConfig.graphScopes).then(function (accessToken) {
        aad_token = accessToken;
        callMSGraph(applicationConfig.graphEndpoint, accessToken, graphAPICallback);
    }, function (error) {
        console.log(error);
        // Call acquireTokenPopup (popup window) in case of acquireTokenSilent failure due to consent or interaction required ONLY
        if (error.indexOf("consent_required") !== -1 || error.indexOf("interaction_required") !== -1 || error.indexOf("login_required") !== -1) {
            parent.myMSALObj.acquireTokenPopup(applicationConfig.graphScopes).then(function (accessToken) {
                callMSGraph(applicationConfig.graphEndpoint, accessToken, graphAPICallback);
            }, function (error) {
				console.error(error);
				if (error.includes('popup')) alert("Please allow popups to continue signing in to CondoNow with Microsoft.");
            });
        }
    });
}
function graphAPICallback(data) {
    var graphProfile = {};
    console.log(data);
    graphProfile.name = data.responses[1].body.displayName ? data.responses[1].body.displayName : data.responses[0].body.displayName;
    graphProfile.email = data.responses[1].body.userPrincipalName ? data.responses[1].body.userPrincipalName : data.responses[0].body.userPrincipalName;
    graphProfile.link = '';
    graphProfile.id = data.responses[1].body.id ? data.responses[1].body.id : data.responses[0].body.id,
    graphProfile.image = data.responses[0].status != 404 && data.responses[0].headers['Content-Type'] && data.responses[0].headers['Content-Type'].indexOf('image') > -1 ? data.responses[0].body : data.responses[1].status != 404 && data.responses[1].headers['Content-Type'] && data.responses[1].headers['Content-Type'].indexOf('image') > -1 ? data.responses[1].body : '';
    if (IsAgent(graphProfile.email)) {
        ProcessRegistrationForSignInWithSocialMedia(graphProfile, '/Stateless.asmx/LoginForAgentWithSocialMedia', true);
    }
    else if (IsProspect(graphProfile.email)) {
        ProcessRegistrationForSignInWithSocialMedia(graphProfile, '/Stateless.asmx/LoginForProspectWithSocialMedia', false);
    }
    else if (IsUnregisteredAgent(graphProfile.email)) {
        window.location.href = "/PublicRegistration?frompage=unregisteredAgent&email=" + graphProfile.email;
    }
    else {
        ProcessRegistrationForSignInWithSocialMedia(graphProfile, '/Stateless.asmx/ProcessProspectRegistrationBySocialMedia', false, 'MS');
    }
}

function acquireTokenRedirectCallBack(errorDesc, token, error, tokenType) {
    if (tokenType === "access_token") {
        callMSGraph(applicationConfig.graphEndpoint, token, graphAPICallback);
    } else {
        console.log("token type is:" + tokenType);
    }
}

function callMSGraph(theUrl, accessToken, callback) {
    var xmlHttp = new XMLHttpRequest();
    var json = {
        "requests": [
          {
              "id": "1",
              "method": "GET",
              "url": "/me/"
          },
          {
              "id": "2",
              "method": "GET",
              "url": "/me/photo/$value"
          }
        ]
    };
    xmlHttp.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200)
            callback(JSON.parse(this.responseText));
    }
    xmlHttp.open("POST", theUrl, true); // true for asynchronous
    xmlHttp.setRequestHeader('Authorization', 'Bearer ' + accessToken);
    xmlHttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    xmlHttp.send(JSON.stringify(json));
}

function ProcessRegistrationForSignInWithGraph(graphData, url) {
    var param = JSON.stringify({
        name: graphData.name,
        email: graphData.email,
        phone: '',
        isinsiderclubmember: false,
        graphProfileImage: graphData.image,
        url: encodeURIComponent(parent.window.location.pathname)
    });

    $.ajax({
        type: "POST",
        url: url,
        data: param,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        cache: false,
        success: function (data) {
            if (data.d.indexOf("emailexists") >= 0) {
                RegisterProspectForGraph(graphData, '/Stateless.asmx/'); //ProcessProspectRegistrationByGooglePlus

            }
            else {
                RegisterProspectForGraph(graphData, '/Stateless.asmx/'); //ProcessAgentRegistrationByGooglePlus
            }
            if (data.d.indexOf("true") >= 0) {
                if(typeof parent.fcm_token !== "undefined") {
                    storeDeviceToken();
                } else parent.window.location = parent.window.location;
                if (data.d.split('~').length == 2) {
                    $.cookie("FilledProspectID", data.d.split('~')[1]);
                    $.cookie("fromSocialLogin", "true");
                }
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log(errorThrown);
        }
    });
}

function RegisterProspectForGraph(graphData, url) {
    var param = JSON.stringify({
        name: graphData.name,
        email: graphData.email,
        phone: '',
        isinsiderclubmember: false,
        graphProfileImage: graphData.image,
        url: encodeURIComponent(parent.window.location.pathname)
    });

    $.ajax({
        type: "POST",
        url: url,
        data: param,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        cache: false,
        success: function (data) {
            if (data.d == "true") {
                if(typeof parent.fcm_token !== "undefined") {
                    storeDeviceToken();
                } else parent.window.location = parent.window.location;
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log(errorThrown);
        }
    });
}
function storeDeviceToken(){
    $.ajax({
        type: "POST",
        url: "/Stateless.asmx/DeviceStore",
        data: JSON.stringify({ deviceToken: parent.fcm_token}),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        cache: false,
        success: function (data) {
            parent.window.location = parent.window.location;
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log(errorThrown);
            parent.window.location = parent.window.location;
        }
    }); 
}
var actionText = [
    "Clicked on ",
    "Checked on ",
    "Shared on ",
    "",
    "Impression",
    "Hovered on ",
    "Submit "
];

$(window).load(function () {
    if (typeof publicPage == 'undefined')
        document.cookie = 'hasClicked=no;path=/'; 
});

$.fn.insertIntoProjectStats = function (projectId, brokerId, pageUrl, action, actionIndex) {
    actionVal = (action !== '') ? actionText[actionIndex] + action : action;
    InsertToProjectStats(projectId, brokerId, pageUrl, actionVal);
}

$.fn.insertListIntoProjectStats = function (projectIdList, brokerId, pageUrl, action, actionIndex) {
    actionVal = (action !== '') ? actionText[actionIndex] + action : action;
    InsertListToProjectStats(projectIdList, brokerId, pageUrl, actionVal);
}
var realtorImpression;
var adsImpressionTime;
var arrads = new Array();
var arr_projects = new Array();
var arr_realtors = new Array();
var findAnAgentImpression;
var arr_findAnAgent = new Array();
var adsBottomLine;

function ProjectStats() {
    this.bindOnClick = function (projectId, brokerId, details, actionIndex) {
        if (details.length === 0) return;
        $.each(details, function (intIndex, objValue) {
            if (objValue.event === "click") {
                $(objValue.controlId).click(function (event) {
                    if (objValue.hrefVal === 1 && $(this).attr("target") !== "_blank")
                        event.preventDefault();
                    new ProjectStats().recordOnEvent(this, objValue, projectId, brokerId, actionIndex);
                });
            }
            else if (objValue.event === "hover") {
                $(objValue.controlId).on({
                    mouseover: function () {
                        event.preventDefault();
                        new ProjectStats().recordOnEvent(this, objValue, projectId, brokerId, actionIndex);
                    },
                    mouseout: function () {
                        event.preventDefault();
                    }
                });
            }
        });
    }

    this.recordOnEvent = function (obj, objValue, projectId, brokerId, actionIndex) {
        var pageUrl = typeof objValue.pageUrl !== "undefined" ? objValue.pageUrl : '';
        var objLabel;
        if (objValue.label !== '' && objValue.label === "get-data-stats") {
            objLabel = $.trim($(obj).data("stats")) + " popup opened";
            actionIndex = 3;
        }
        else if (objValue.label !== '' && objValue.label === "get-text")
            objLabel = $.trim($(obj).text());
        else objLabel = objValue.label;
        var objPrevLabel = (objValue.prevlabel !== undefined) ? objValue.prevlabel : "";
        var actionVal = (objValue.label !== '') ? actionText[actionIndex] + objPrevLabel + objLabel : objValue.label;
        var hrefVal = (objValue.hrefVal === 1 && $(obj).attr("target") !== "_blank") ? $(obj).attr("href") : undefined;
        InsertToProjectStats(projectId, brokerId, pageUrl, actionVal, hrefVal);
        InsertToGoogleAnalytics({ 'eventName': objValue.event, 'value': objValue.label });
        $.cookie("hasClicked", "yes", { path: '/' });
    }

    this.recordProjectStats = function (projectId, brokerId, pageUrl, action, actionIndex, hrefVal, callback) {
        var localUrl = pageUrl.toLowerCase();
        if (localUrl.indexOf( 'home.aspx') > -1)
            pageUrl = pageUrl.replace(/home.aspx/ig, '');
        else if (localUrl.indexOf('login') > -1)
            pageUrl = pageUrl.replace(/loginPop.aspx/ig, '');
        else if (localUrl.indexOf('create-an-account') > -1)
            pageUrl = pageUrl.replace(/create-an-account/ig, '');
        else if (localUrl.indexOf('publicregistration.aspx') > -1)
            pageUrl = pageUrl.replace(/publicregistration/ig, '');
        else if (localUrl.indexOf('join-the-insiders-club') > -1)
            pageUrl = pageUrl.replace(/join-the-insiders-club/ig, '');

        var actionVal = (action !== '') ? actionText[actionIndex] + action : action;
        InsertToProjectStats(projectId, brokerId, localUrl, actionVal, hrefVal, callback);
        InsertToGoogleAnalytics({ 'eventName': 'click', 'value': action });
    }

    this.recordCompare = function (projectId, brokerId, pageUrl, action, actionIndex, hrefVal, callback) {
        var actionVal = (action !== '') ? actionText[actionIndex] + action : action;
        InsertToProjectStats(projectId, brokerId, pageUrl, actionVal, hrefVal, callback);
        var a = UriParser.getUri(pageUrl);
		if (typeof ga !== 'undefined') {
			ga('send', {
				'hitType': 'pageview',
				'page': a.pathname + a.search,
				'title': document.title
			});
		}

		if (typeof gtag !== 'undefined') {
			gtag('event', {
				'hitType': 'pageview',
				'page': window.location.pathname + '?eventName=' + options.eventName + '&eventValue=' + options.value,
				'title': document.title,
				'send_to': 'G-JWDBW9QXNK'
			});
		}
    }

    this.recordBrowseListProjectStats = function (projectIdList, brokerId, pageUrl) {
        InsertListToProjectStats(projectIdList, brokerId, pageUrl, actionText[4]);
    }

    this.recordStatsOnLoad = function (selector, brokerId, scrollTimer) {
        $(window).load(function () {
            setTimeout(function () {
                var projectIdList = $(selector)
                                        .filter(':onScreen')
                                        .map(function () {
                                            if ($(this).find('img').isOnScreen() && $(this).find('div.projName').isOnScreen())
                                                return this.id;
                                        }).get();

                InsertListToProjectStats(projectIdList, brokerId, $(location).attr("href"), actionText[4]);
            }, 1000 + scrollTimer);
        });
    }

    this.recordStatsOnScroll = function (selector, brokerId, scrollTimer) {
        $(window).scroll(function () {
            clearTimeout($.data(this, "scrollTimer"));
            $.data(this, "scrollTimer", setTimeout(function () {
                var projectIdList = $(selector)
                                        .filter(':onScreen')
                                        .map(function () {
                                            if ($(this).find('img').isOnScreen() && $(this).find('div.projName').isOnScreen())
                                                return this.id;
                                        }).get();

                InsertListToProjectStats(projectIdList, brokerId, $(location).attr("href"), actionText[4]);

            }, scrollTimer));
        });
    }

    this.recordProjectsAfterSearch = function (selector, brokerId, scrollTimer) {
        clearTimeout($.data(this, "scrollTimer"));
        $.data(this, "scrollTimer", setTimeout(function () {
            var projectIdList = $(selector)
                                        .filter(':onScreen')
                                        .map(function () {
                                            if ($(this).find('img').isOnScreen() && $(this).find('div.projName').isOnScreen())
                                                return this.id;
                                        }).get();

            InsertListToProjectStats(projectIdList, brokerId, $(location).attr("href"), actionText[4]);

        }, scrollTimer));
    }

    this.recordNearbyProjectStats = function (projectId, brokerId, pageUrl, action, hrefVal) {
        InsertToProjectStats(projectId, brokerId, pageUrl, action, hrefVal);
    }

    this.recordRealtorImpression = function (selector, brokerId, scrollTimer) {
        if (realtorImpression) {
            clearTimeout(realtorImpression);
        }
        realtorImpression = setTimeout(function () {
            var realtorIdList = $(selector).filter(':onScreen').map(function () {
                return $(this).attr("realtorid");
            });
            if ($(arr_realtors).not(realtorIdList).length == 0 && $(realtorIdList).not(arr_realtors).length == 0) {
                return;
            }
            if (realtorIdList.length === 0) return;
            arr_realtors = realtorIdList;

            for (var i = 0; i < realtorIdList.length; i++) {
                InsertToProjectStats(ProjectID, brokerId, $(location).attr("href"), "Realtor=" + realtorIdList[i] + ", Impression");
            }

        }, scrollTimer);
    }

    this.recordCouponImpression = function () {
        $(window).scroll(function () {
            InsertCouponImpression();
        });
    }

    this.recordAdsImpression = function (first) {

      /*  adsImpressionTime = setInterval(function () {
            var selectorads = $("[id$=divAdvertisement] img");
            var AdsIdList = $(selectorads).filter(':onScreen').map(function () {
                return $(this).attr("adsid");
            }).get();

            var allads = $(selectorads).map(function () {
                return $(this).attr("adsid");
            }).get();
             
            if (allads.length == arrads.length) {
                clearTimeout(adsImpressionTime);
                return;
            }
            for (var ic = 0;ic<AdsIdList.length; ic++) {
                if ($.inArray(AdsIdList[ic], arrads) == -1) {
                    arrads.push(AdsIdList[ic]);

                    var pid = -1;
                    if (typeof ProjectID != 'undefined')
                        pid = ProjectID;

                    var bid = -1;
                    if (typeof brokerId != 'undefined')
                        bid = brokerId;

                    InsertToProjectStats(pid, bid, window.location.href, "Impression on Advertisement - " + AdsIdList[ic]);
                }
            }
        }, 500);*/

        var imgAdvertisements = [].slice.call(document.querySelectorAll(".imgAdvertisement"));

        if ("IntersectionObserver" in window) {
            let AdvertisementsObserver = new IntersectionObserver(function (entries, observer) {
                entries.forEach(function (entry) {
                    if (entry.isIntersecting) {
                        let imgAdver = entry.target;


                        var pid = -1;
                        if (typeof ProjectID != 'undefined')
                            pid = ProjectID;

                        var bid = -1;
                        if (typeof brokerId != 'undefined')
                            bid = brokerId;

                        var InsertProj = true;

                        if ($(imgAdver).hasClass("Refresh"))
                        {
                            if ($(imgAdver).hasClass("Banner"))
                            {
                                if ($(imgAdver).hasClass("FirstLoad"))
                                    $(imgAdver).removeClass("FirstLoad");
                                else {

                                    InsertProj = false;
                                    ReLoadTopAdvertisment(pid, bid);
                                }
                            }
                            else
                            {
                               
                                if ($(imgAdver).hasClass("FirstLoad"))
                                    $(imgAdver).removeClass("FirstLoad");
                                else {

                                    InsertProj = false;
                                    ReLoadAdvertisments(pid, bid, $(imgAdver));
                                }
                                
                            }

                        }
                        if (typeof $(imgAdver).attr("adsid") != "undefined")
                        if (InsertProj && $(imgAdver).attr("adsid") != "" && $(imgAdver).attr("adsid") != "-1")
                            InsertToProjectStats(pid, bid, window.location.href, "Impression on Advertisement - " + $(imgAdver).attr("adsid"));
                       

                    }
                });
            });

            imgAdvertisements.forEach(function (imgAdver) {
                AdvertisementsObserver.observe(imgAdver);
            });
        }
        if (typeof ProjectID != 'undefined') {
            adsBottomLine = setInterval(function () {
                var selectorads = $(".discount-wrapper");
                var AdsIdList = $(selectorads).filter(':onScreen');

                var pid = -1;
                if (typeof ProjectID != 'undefined')
                    pid = ProjectID;

                var bid = -1;
                if (typeof brokerId != 'undefined')
                    bid = brokerId;
                var adslink = $(selectorads).find('a');
                var adstitle = '';
                if (adslink.length > 0) {
                    adstitle = ' - '+ $(adslink).attr('addname');
                }
                //InsertToProjectStats(pid, bid, window.location.href, "Impression on Bottomline ads" + adstitle);
                clearTimeout(adsBottomLine);
            }, 500);
        } 
    }

    this.recordFinAnAgentOnScroll = function (selector, scrollTimer) {

        if (findAnAgentImpression) {
            clearTimeout(findAnAgentImpression);
        }
        findAnAgentImpression = setTimeout(function () {
            var realtorIdList = $(selector).filter(':onScreen').map(function () {
                return $(this).attr("brid");
            }).get();

            
            var _FilteredList = RemoveDupicateItems(arr_findAnAgent, realtorIdList);
            arr_findAnAgent = realtorIdList;
            if (_FilteredList.length === 0) return;

            InsertAgentListToProjectStats(-2, _FilteredList, $(location).attr("href"), "Impression");

        }, scrollTimer);

    }

}

var InsertCouponImpression = function () {
    var $couponCard = $(".coupon .style-card.impression");

    if ($couponCard.length < 1) return;

    var $onScreenCard = $couponCard.filter(':onScreen');

    $.each($onScreenCard, function () {
        var couponTitle = $(this).closest(".coupon").find(".PurchaseInfo").text().trim();
        var amount = $(this).find(".adBoxesAmount").text().trim();
        var description = $(this).find(".adBoxesInfo").text().split("\n");

        var action = "Impression: " + couponTitle + " - " + amount;

        $.each(description, function (index, value) {
            action = action + " " + value.trim();
        });

        new ProjectStats().recordProjectStats(-1, -1, document.location.href, action, 3);

        $(this).removeClass("impression");
    });
}


function RemoveDupicateItems(OldArray, NewArray) {

    var newList = [];

    for (var i = 0; i < NewArray.length; i++) {
        if ($.inArray(NewArray[i], OldArray) == -1) {
            newList.push(NewArray[i]);
        }
    }
    return newList;
}

var ProjectStatsUtil = {
    GetPageUrl: function () {
        if (!window.location.origin) window.location.origin = window.location.protocol + "//" + window.location.host;
        return window.location.origin + document.location.pathname;
    }
}

function InsertToProjectStats(projectId, brokerId, pageUrl, action, hrefVal, callback) {
    if (typeof isStaffUser !== 'undefined' && isStaffUser) return;

 
    projectId = typeof projectId === 'undefined' ? -2 : projectId;
    brokerId = typeof brokerId === 'undefined' ? -2 : brokerId;
    var referrer = document.referrer == undefined ? '' : document.referrer;
    
    var params = JSON.stringify({ 'projectId': projectId, 'brokerId': brokerId, 'pageUrl': encodeURI(pageUrl), 'action': encodeURIComponent(action), 'referrerUrl': encodeURI(referrer), 'pageTitle': $(document).find("title").text() });
    $.ajax({
        type: "POST",
        url: "/WorkflowManagerService.asmx/InsertToProjectStats2",
        data: params,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        beforeSend: function () { },
        complete: function () { },
        success: function (data) {
            if (callback !== undefined)
                callback();
            
        },
        error: function (a, b, c) {
        }
    });
}

function InsertToStats(projectId, brokerId, leadId, pageUrl, action, hrefVal, callback) {
    if (typeof isStaffUser !== 'undefined' && isStaffUser) return;

   
    projectId = typeof projectId === 'undefined' ? -2 : projectId;
    brokerId = typeof brokerId === 'undefined' ? -2 : brokerId;
    var referrer = document.referrer == undefined ? '' : document.referrer;
    var params = JSON.stringify({ 'projectId': projectId, 'brokerId': brokerId, 'leadId': leadId, 'pageUrl': encodeURI(pageUrl), 'action': escape(action),  'referrerUrl': encodeURI(referrer), 'pageTitle': $(document).find("title").text() });
    
    $.ajax({
        type: "POST",
        url: "/WorkflowManagerService.asmx/InsertToProjectStats2",
        data: params,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        beforeSend: function () { },
        complete: function () { },
        success: function (data) {
            if (hrefVal !== undefined && hrefVal.length > 0 && hrefVal !== "javascript:void(0)")
                window.location.href = hrefVal;
            else if (callback !== undefined)
                callback();
            return true;
        },
        error: function (a, b, c) {
        }
    });
}

function InsertToGoogleAnalytics(options) {
    if(typeof ga !== 'undefined') {
        ga('send', {
            'hitType': 'pageview',
            'page': window.location.pathname + '?eventName=' + options.eventName + '&eventValue=' + options.value,
            'title': document.title
        });
    }
    if (typeof gtag !== 'undefined') {
        gtag('event', {
            'hitType': 'pageview',
            'page': window.location.pathname + '?eventName=' + options.eventName + '&eventValue=' + options.value,
			'title': document.title,
			'send_to': 'G-JWDBW9QXNK'
        });
    }
}

function InsertListToProjectStats(projectIdList, brokerId, pageUrl, action) {
    if (typeof isStaffUser !== 'undefined' && isStaffUser) return;

    var _FilteredList = RemoveDupicateItems(arr_projects, projectIdList);
    arr_projects = projectIdList;
    if (_FilteredList.length === 0) return;

    var referrer = document.referrer == undefined ? '' : document.referrer;
    $.ajax({
        type: "POST",
        url: "/WorkflowManagerService.asmx/InsertListToProjectStats",
        data: "{ 'projectIdList': " + JSON.stringify(_FilteredList) + ", 'brokerId': '" + brokerId + "', 'pageUrl': '" + encodeURI(pageUrl) + "', 'action': '" + escape(action) + "', 'referrerUrl': '" + encodeURI(referrer) + "', 'pageTitle': '"+ $(document).find("title").text()+"' }",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        beforeSend: function () { },
        complete: function () { },
        success: function (data) {
        },
        error: function (a, b, c) {
        }
    });
}

function resizeImg(img) {
    var imgwidth = img.naturalWidth;
    var imgheight = img.naturalHeight;
    var popupwidth = $(window).width();
    var popupheight = $(window).height();
    var scale = popupheight / imgheight;
    var scaledwidth = scale * imgwidth;

    if (scaledwidth < popupwidth) {
        img.style["height"] = "100vh";
        img.style["width"] = "auto";
    }
    else if (scaledwidth == popupwidth) { }
    else {
        img.style["width"] = "100vw";
        img.style["height"] = "auto";
    }
}

var lazyImages = [].slice.call(document.querySelectorAll("img[data-src]"));

if ("IntersectionObserver" in window) {
	let lazyImageObserver = new IntersectionObserver(function (entries, observer) {
		entries.forEach(function (entry) {
			if (entry.isIntersecting) {
				let lazyImage = entry.target;
				if(lazyImage.dataset.src) lazyImage.src = lazyImage.dataset.src;
				lazyImageObserver.unobserve(lazyImage);
			}
		});
	});

	lazyImages.forEach(function (lazyImage) {
		lazyImageObserver.observe(lazyImage);
	});
} else {
    // Possibly fall back to a more compatible method here
    $('img:not(([src])[data-src]').attr('src', $(this).attr('data-src'));
}

var currentPreview;

$(".fullscreenVidIcon").click(function () {
    $('#imgFull').attr('style', 'display:none;');
    $(this).attr('style', 'display:none;');
});

function galleryPrev() {
    var previous = currentPreview.previousElementSibling;
    if ($(currentPreview).attr('href') === undefined) {
        if ($(previous).attr('href') === undefined)
        document.getElementById("imgFull").src  = $(currentPreview).prev().find(".thumbnailFrame").children().attr('src');
        currentPreview = currentPreview.previousElementSibling;
    }
    else {
        var videoFrame = $('#videoFrame').length;
        var galleryImage = $('#imgFull').length;
        if (previous.classList.contains("galleryPreviewVideo")) {
            if (videoFrame != null) {
                $('#videoFrame').attr('src', '');
            }

            if (galleryImage != null) {
                $('#imgFull').removeAttr('style');
            }

            var imageURL = $(previous).find('img').attr('src');
            $('#imgFull').attr('src', imageURL);
            var videoURL = $(previous).attr('href');
            $('#fullscreenFloorImage').find('.fullscreenVidIcon').removeAttr('style');
            $('#fullscreenFloorImage').find('.fullscreenVidIcon').attr('href', videoURL);
            currentPreview = currentPreview.previousElementSibling;
        }
        else if (previous.classList.contains("galleryPreviewVR")) {
            if (previous.classList.contains("youtubeLink")) {
                var videoFrame = $('#videoFrame').length;
                var videoURL = $(previous).attr('href');
                $('#imgFull').attr('style', 'display:none;');
                $('#videoFrame').attr('src', videoURL);
                currentPreview = currentPreview.nextElementSibling;
            }
            else {
                var videoFrame = $('#videoFrame').length;
                var galleryImage = $('#imgFull').length;
                var videoURL = $(previous).attr('href');
                if (videoFrame != null) {
                    $('#videoFrame').attr('src', videoURL);
                }

                $('#imgFull').attr('style', 'display:none;');
                currentPreview = currentPreview.nextElementSibling;
            }
        }
    }
}

function galleryNext() {
    var next = currentPreview.nextElementSibling
    if ($(next).attr('href') === undefined) {
        $('#videoFrame').attr('src', '');
        $('#imgFull').removeAttr('style');
        $('#fullscreenFloorImage').find('.fullscreenVidIcon').attr('style', 'display:none;');
        document.getElementById("imgFull").src = $(currentPreview).next().find(".thumbnailFrame").children().attr('src');
        currentPreview = currentPreview.nextElementSibling;
    }
    else {
        var videoFrame = $('#videoFrame').length;
        var galleryImage = $('#imgFull').length;
        if (next.classList.contains("galleryPreviewVideo")) {
            if (videoFrame != null) {
                $('#videoFrame').attr('src', '');
            }

            if (galleryImage != null) {
                $('#imgFull').removeAttr('style');
            }

            var imageURL = $(next).find('img').attr('src');
            $('#imgFull').attr('src', imageURL);
            var videoURL = $(next).attr('href');
            $('#fullscreenFloorImage').find('.fullscreenVidIcon').removeAttr('style');
            $('#fullscreenFloorImage').find('.fullscreenVidIcon').attr('href', videoURL);
            currentPreview = currentPreview.nextElementSibling;
        }
        else if (next.classList.contains("galleryPreviewVR")) {
            if (next.classList.contains("youtubeLink")) {
                var videoFrame = $('#videoFrame').length;
                var videoURL = $(next).attr('href');
                $('#imgFull').attr('style', 'display:none;');
                $('#videoFrame').attr('src', videoURL);
                currentPreview = currentPreview.nextElementSibling;
            }
            else {
                var videoFrame = $('#videoFrame').length;
                var galleryImage = $('#imgFull').length;
                var videoURL = $(next).attr('href');
                if (videoFrame != null) {
                    $('#videoFrame').attr('src', videoURL);
                }

                $('#imgFull').attr('style', 'display:none;');
                currentPreview = currentPreview.nextElementSibling;
            }
        }
    }
}
function InsertAgentListToProjectStats(projectId, brokerIdList, pageUrl, action) {
    if (typeof isStaffUser !== 'undefined' && isStaffUser) return;

    //console.log(brokerIdList);
    var referrer = document.referrer == undefined ? '' : document.referrer;
    $.ajax({
        type: "POST",
        url: "/WorkflowManagerService.asmx/InsertAgentListToProjectStats",
        data: "{'projectId' : '" + projectId + "', 'brokerIdList': " + JSON.stringify(brokerIdList) + ", 'pageUrl': '" + encodeURI(pageUrl) + "', 'action': '" + escape(action) + "', 'referrerUrl': '" + encodeURI(referrer) + "', 'pageTitle':'" + $(document).find("title").text() + "' }",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        beforeSend: function () { },
        complete: function () { },
        success: function (data) {
        },
        error: function (a, b, c) {
        }
    });
}


var UriParser = {
    getUri : function(urlString){
        var parser = document.createElement('a');
        parser.href = urlString;
        //parser.href = "http://example.com:3000/pathname/?search=test#hash";

        parser.protocol; // => "http:"
        parser.hostname; // => "example.com"
        parser.port;     // => "3000"
        parser.pathname; // => "/pathname/"
        parser.search;   // => "?search=test"
        parser.hash;     // => "#hash"
        parser.host;     // => "example.com:3000"
        return parser;
    }
}
var condoplayer = "condoplayer";
var divvideoPlayPause = "#divvideoPlayPause";
var purchaseDate = {};
var closingDate = {};
var isAgentSugg = false;
var isValidAgent = false;
var isValidationSucceed = false;
$(window).load(function () {
    FB.init({
        appId: FacebookAppId,

        status: true,
        cookie: true,
        xfbml: true
    });
});

$(document).ready(function () {
    InsertCouponImpression();
    new ProjectStats().recordCouponImpression();

    if (typeof google != 'undefined')
        var autocomplete = new google.maps.places.Autocomplete((document.getElementById('input_Address')), { types: ['geocode'] });

    $("#lnkLoginPopup").attr('href', $("#lnkPublicResponsiveLogin").attr('href'));

    if (!$(".leftLayer").is(':visible')) {
        condoplayer = "condoplayer2";
        divvideoPlayPause = "#divvideoPlayPause2";
    }

    BottomLine.AdjustRegistrationForm();
    BottomLine.OpenDetailPage();
    BottomLine.InitializeRegistrationEvent();
    BottomLine.OpenVideo();
    BottomLine.BackPage();

    var magnilist = [
                   { id: '#lnkSendRewardEmail', width: 361, height: 550, type: 'iframe', },
                   { id: '#lnkLoginPopup', width: 320, height: 414, type: 'iframe', openCallback: function () { magnific_helpers.SetContentHight(); } },
                   { id: '#lnkThanksForSharingPopup', width: 320, height: 365, type: 'iframe', openCallback: function () { magnific_helpers.SetContentHight(); } },
                   { id: '#lnkOnlyThankYouPopup', width: 320, height: 200, type: 'iframe', openCallback: function () { magnific_helpers.SetContentHight(); } },
                   { id: '#lnkBottomLineUnsubscribe', width: 320, height: 200, type: 'inline' },
                   {
                       id: '#lnkFacebookPopup', width: 395, height: 395, type: 'iframe',
                       changeCallback: function () { console.log("my log"); },
                       closeCallBack: function () { console.log("my close log"); },
                       aftercloseCallBack: function () { console.log("my close log"); }
                   },
                    {
                        id: '#lnkTwitterPopup', width: 395, height: 395, type: 'iframe',
                        changeCallback: function () { console.log("my log"); },
                        closeCallBack: function () { console.log("my close log"); },
                        aftercloseCallBack: function () { console.log("my close log"); }
                    }

    ];
    jQuery.each(magnilist, function (i, val) {
        magnificobj(val);
    });

    var bottomlinesuccess = getUrlVar('success');
    if (ProspectID != "0" && bottomlinesuccess == 'true') {
        OpenOnlyThanksPopup();
    }

    var unsubscribe = $("#bottomLineUnsubscribe").val();
    if ($.trim(unsubscribe).toLowerCase() == "true") {
        $("#lnkBottomLineUnsubscribe").click();
    }

    var showLoginPopUp = $("#showLoginPopUp").val();
    if ($.trim(showLoginPopUp).toLowerCase() == "true") {
        OpenLoginBottomLinePage();
    }
    $(".BottomLineVersion2").each(function (index) //SSD+US15204
    {

        $(".BottomLineVersion2")[index].onclick = function () { 

          /*  if (ProspectID == 0) {
                parent.$("#lnkPublicResponsiveLogin").attr('href', "/LoginPop.aspx?from=urlReferrer&pageUrl=/bottomline-register");
                $('#lnkPublicResponsiveLogin').trigger('click');
            }
            else*/
                parent.window.location.href = "/bottomline-register";
        };
    });
});

var BottomLineValidation = {
    CheckIfValidAgentExist: function (agentId, callback) {
        var result = false;
        $.ajax({
            type: "POST",
            async: false,
            url: "/IsValidAgent",

            data: "{'agentId': '" + agentId + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                if (data == false) {
                    result = false;
                }
                else {
                    result = true;
                }
            },
            complete: function () {
                if (typeof callback != 'undefined') {
                    callback(result);
                }
            },
            error: function (a, b, c) {
                alert(b);
            }
        });

        return result;
    }
};

function onShareClick(item) {

    var type = $(item).attr('data-type');

    OpenSocialWindow(type);

}
function OpenLoginBottomLinePage() {
    $("#lnkPublicResponsiveLogin").attr('href', "/LoginPop.aspx?from=urlReferrer&pageUrl=/bottomline-register");
    OpenLoginPopup();
}
function CloseFancyAndOpenLogin() {
    $.magnificPopup.close();

    if (ProspectID > 0)
        OpenThanksForSharingPopup();
    else {
        OpenLoginBottomLinePage();
    }
}
function CloseMagnificBox() {
    $.magnificPopup.close();
}
function OpenThanksForSharingPopup() {
    $('#lnkThanksForSharingPopup').trigger('click');
}

function OpenOnlyThanksPopup() {
    $('#lnkOnlyThankYouPopup').trigger('click');
}

function OpenLoginPopup() {
    $('#lnkPublicResponsiveLogin').click();
}
function PostFollowMessageOnFaceBook() {

    FB.login(function (response) {
        if (response.authResponse) {
            FB.api('/me', function (fbData) {

                FB.api('/me/feed', 'post', { message: 'acnbcbsakjdjkas' }, function (response) {
                    if (!response || response.error) {
                        alert('Error occured');
                    } else {
                        alert('Post ID: ' + response.id);
                    }
                });

            });
        } else {
            console.log('User cancelled login or did not fully authorize.');
        }
    }, { scope: 'email,publish_actions', return_scopes: true });


};


function PostFollowMessageOnTwitter() {



};
function PostFollowMessageOnFaceBook2() {
    var message_str = 'Facebook JavaScript Graph API Tutorial';
    FB.api('/me/feed', 'post', { message: message_str }, function (response) {
        if (!response || response.error) {
            alert("Couldn't Publish Data");
        } else {

            $.ajax({
                type: "POST",
                url: "/Stateless.asmx/SendEmailAndGetHasLeadsForProspect",
                data: JSON.stringify({ 'prospectID': emailAddress }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                cache: false,

                success: function (data) {
                    var results = JSON.parse(data.d);

                    if (results.returnCode == "0") {
                        if ($("#lnkThanksForSharingPopup").attr('href').indexOf('HasLeads') < 0)
                            $("#lnkThanksForSharingPopup").attr('href', $("#lnkThanksForSharingPopup").attr('href') + "&HasLeads=0");
                    }
                    else {
                        if ($("#lnkThanksForSharingPopup").attr('href').indexOf('HasLeads') < 0)
                            $("#lnkThanksForSharingPopup").attr('href', $("#lnkThanksForSharingPopup").attr('href') + "&HasLeads=1");
                    }
                    OpenThanksForSharingPopup();
                },
                error: function (a, b, c) {
                    alert(a.responseText);
                }
            });
        }
    });

};

function OnlySendEmailAndForProspect() {

    $.ajax({
        type: "POST",
        url: "/Stateless.asmx/SendEmailAndGetHasLeadsForProspect",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        cache: false,

        success: function (data) {

        },
        error: function (a, b, c) {
            alert(a.responseText);
        }
    });

}



function GetHasLeadsForProspect() {

    $.ajax({
        type: "POST",
        url: "/Stateless.asmx/GetHasLeadsForProspect",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        cache: false,

        success: function (data) {
            /* if (ProspectID > 0) {*/
            var results = JSON.parse(data.d);
            if (results.returnCode == "0") {
                if ($("#lnkThanksForSharingPopup").attr('href').indexOf('HasLeads') < 0)
                    $("#lnkThanksForSharingPopup").attr('href', $("#lnkThanksForSharingPopup").attr('href') + "&HasLeads=0");
            }
            else {
                if ($("#lnkThanksForSharingPopup").attr('href').indexOf('HasLeads') < 0)
                    $("#lnkThanksForSharingPopup").attr('href', $("#lnkThanksForSharingPopup").attr('href') + "&HasLeads=1");
            }
            OpenThanksForSharingPopup();

        },
        error: function (a, b, c) {
            alert(a.responseText);
        }
    });

}
function SendEmailAndGetHasLeadsForProspect() {

    $.ajax({
        type: "POST",
        url: "/Stateless.asmx/SendEmailAndGetHasLeadsForProspect",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        cache: false,

        success: function (data) {
            /* if (ProspectID > 0) {*/
            var results = JSON.parse(data.d);
            if (results.returnCode == "0") {
                if ($("#lnkThanksForSharingPopup").attr('href').indexOf('HasLeads') < 0)
                    $("#lnkThanksForSharingPopup").attr('href', $("#lnkThanksForSharingPopup").attr('href') + "&HasLeads=0");
            }
            else {
                if ($("#lnkThanksForSharingPopup").attr('href').indexOf('HasLeads') < 0)
                    $("#lnkThanksForSharingPopup").attr('href', $("#lnkThanksForSharingPopup").attr('href') + "&HasLeads=1");
            }
            OpenThanksForSharingPopup();

        },
        error: function (a, b, c) {
            alert(a.responseText);
        }
    });

}

function OpenSocialWindow(type) {
    var x = screen.width / 2 - 700 / 2;
    var y = screen.height / 2 - 450 / 2;
    var options = 'height=320, width=640, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, directories=no, status=no,left=' + x + ',top=' + y;


    if (type == "facebook") {


        FB.ui(
                {
                    method: 'share',
                    href: facebookShareURL

                }, function (response) {
                    var result = JSON.stringify(response);
                    if (!response.hasOwnProperty("error_code")) {
                        GetHasLeadsForProspect();
                        AddBottomLineRecord('facebook');
                        BottomLine.InsertToStats('Shared via Facebook', 'click');
                    }
                    /*if (result.indexOf('post_id') > -1) {
                      
                    }*/
                });
    }
    else if (type == "twitter") {



        newwindow2 = window.open(decodeURIComponent(twitterShareURL), 'name', options);
        if (window.focus) { newwindow2.focus() }

        var loop2 = setInterval(function () {

            if (newwindow2.closed) {
                clearInterval(loop2);

                GetHasLeadsForProspect();
                AddBottomLineRecord('twitter');
                BottomLine.InsertToStats('Shared via Twitter', 'click');
            }
        }, 1000);

    }
    else if (type == "email") {
        $('#lnkSendRewardEmail').trigger('click');
        BottomLine.InsertToStats('Shared via Email', 'click');
    }
    return false;
}

function adjustPlaceholder() {
    $("#input_fullName").attr('placeholder', '* Your Full Name');
    $("#input_AgreementName").attr('placeholder', '* Name on Agreement');
    $("#input_PhoneAgreement").attr('placeholder', '* Phone Number on Agreement');
    $("#input_EmailAgreement").attr('placeholder', '* Email on Agreement');
    $("#input_InfoRequest").attr('placeholder', '* Info Request#');
    $("#input_TransactionType").attr('placeholder', '* Transaction Type');
    if ($("#input_AgentName").hasClass("requiredField"))
        $("#input_AgentName").attr('placeholder', '* Agent Name');
    else
        $("#input_AgentName").attr('placeholder', 'Agent Name');
    $("#input_Development").attr('placeholder', '* Development');
    $("#input_Developer").attr('placeholder', '* Developer(s)');
    $("#input_Address").attr('placeholder', '* Address');
    $("#input_UnitNumber").attr('placeholder', '* Unit Number');
    $("#input_DateOfPurchase").attr('placeholder', '* Date of Purchase');
    $("#input_ClosingDate").attr('placeholder', '* Projected Closing Date');
}

$(document).click(function (event) {
    if ($("div#AgentSearchSuggestionDiv").is(":visible") && $(event.target).closest("div#AgentSearchSuggestionDiv").length < 1) {
        $("div#AgentSearchSuggestionDiv").css("display", "");
    }

    if ($("div#DeveloperSuggestionDiv").is(":visible") && $(event.target).closest("div#DeveloperSuggestionDiv").length < 1) {
        $("div#DeveloperSuggestionDiv").css("display", "");
    }

    if ($("div#dvPurchaseDatePicker").is(":visible") && $(event.target).closest("div#dvPurchaseDatePicker").length < 1 && $(event.target).closest("#input_DateOfPurchase").length < 1) {
        $("div#dvPurchaseDatePicker").removeClass("open-datePicker");
    }

    if ($("div#dvClosingDatePicker").is(":visible") && $(event.target).closest("div#dvClosingDatePicker").length < 1 && $(event.target).closest("#input_ClosingDate").length < 1) {
        $("div#dvClosingDatePicker").removeClass("open-datePicker");
    }

    if ($("div.TransactionTypeFloatingDiv").is(":visible") && $(event.target).closest("div#transactionType").length < 1) {
        $("div.TransactionTypeFloatingDiv").css("display", "none");
    }
});

function validateEmail(email) {
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
}

function validatePhone(email) {
	var re = /^([+0-9])?((011[ 0-9\s]*)|(1?[-+\s]?([(]?[0-9\s]{1}\d{2}[)]?[-\s ]?\d{3}[-\s ]?\d{4})([ ]?(ext|Ext|EXT|x|X|Ex|ex)?[.\s]?[\s ]?\d{1,6})?))$/;
	return re.test(email);
}
function validationClear(element) {
    element.parent().parent().removeClass("TextBoxValidationError");
    element.next().css({ "visibility": "hidden" });
    element.next().next().css({ "visibility": "hidden" });
}

function validationEffect(element) {

    if (element.attr('id') == 'input_Development') {
        if ($('#input_Development').attr('data-value').trim().length > 0 && $('#input_Development').attr('data-value') > 0) {
            return true;
        }
    } else if (element.attr('id') == 'input_AgentName') {
        if ($('#input_AgentName').attr('data-value').trim().length > 0 && $('#input_AgentName').attr('data-value') > 0) {
            return true;
        }
    } else if (element.attr('id') == 'input_UnitNumber') {
        if (BottomLine.TransactionType == 1) {
            return true;
        }
    }


    if (element.val() == "") {
        element.parent().parent().addClass("TextBoxValidationError");

        if (element.attr('id') == 'input_EmailAgreement') {
            element.next().text("Required");
        }

        element.next().css({ "visibility": "visible" });
    } else {
        if (element.attr('id') == 'input_EmailAgreement') {
            if (!validateEmail(element.val())) {
                element.next().css({ "visibility": "visible" });
                element.next().text("Enter Correct Email");
                isValidationSucceed = false;
            } else {
                element.parent().parent().removeClass("TextBoxValidationError");
                element.next().css({ "visibility": "hidden" });
            }
        }
		else if (element.attr('id') == 'input_PhoneAgreement') {
			if (!validatePhone(element.val())) {
				element.next().css({ "visibility": "visible" });
				element.next().text("Enter Correct Tel Number");
                isValidationSucceed = false;
            } else {
                element.parent().parent().removeClass("TextBoxValidationError");
                element.next().css({ "visibility": "hidden" });
            }
        }
        else if (element.parent().parent().hasClass("TextBoxValidationError")) {
            element.parent().parent().removeClass("TextBoxValidationError");
            element.next().css({ "visibility": "hidden" });
        }
    }
}

function validationEffectForAgent(element) {
    element = $(element);
    if (element.attr('id') == 'input_AgentName' && $("#input_AgentName").hasClass("requiredField")) {
        if (($('#input_AgentName').attr('data-value').trim().length > 0 && $('#input_AgentName').attr('data-value') > 0) && isAgentSugg) {
            element.parent().parent().removeClass("TextBoxValidationError");
            element.next().next().css({ "visibility": "hidden" });
            return true;
        }
        else {

            var agentName = $('#input_AgentName').val().trim();
            agentName = agentName.length > 0 ? agentName : $('.agentName').html().trim();
            if (agentName != "") {
                element.parent().parent().addClass("TextBoxValidationError");
                element.next().css({ "visibility": "hidden" });
                element.next().next().css({ "visibility": "visible" });
            }
            else {
                element.parent().parent().addClass("TextBoxValidationError");
                element.next().css({ "visibility": "visible" });
                element.next().next().css({ "visibility": "hidden" });
            }
        }
    }

}
function validationCheck() {
    var elements = $(".requiredField");
    var length = elements.length;
    for (var i = 0; i < length; i++) {
        validationEffect($(elements[i]));
    }

}




function CheckIfValidAgent(agentId, callback) {
    //var searchData = agentId;
    var isValidAgent = false;
    if (agentId == "") {
        $(".AgentSearchSuggestionDiv").hide();
        isAgentSugg = false;
        return;
    }

    $.get("/IsValidAgent", { agentId: agentId }).done(function (data) {
        isValidAgent = (data == "false") ? false : true;

        callback();
    });
    return isValidAgent;
}




function isValidationSucceeded() {
    $('#registrationSave').prop('disabled', true);
    ShowLoader();
    isValidationSucceed = true;
    validationCheck();
    var elements = $(".requiredField");
    var length = elements.length;
    for (var i = 0; i < length; i++) {
        if ($(elements[i]).val() == "") {

            if ($(elements[i]).attr('id') == 'input_AgentName') {
                if (!$('#input_AgentName').attr('data-value').trim().length > 0) {
                    isValidationSucceed = false;
                }
            }
            else if ($(elements[i]).attr('id') == 'input_Development') {
                if (BottomLine.TransactionType == 0 && !$('#input_Development').attr('data-value').trim().length > 0 && !$('#input_Development').attr('data-value') > 0)
                    isValidationSucceed = false;
            }
            else if ($(elements[i]).attr('id') == 'input_Address') {
                if (BottomLine.TransactionType == 1)
                    isValidationSucceed = false;
            }
            else if ($($(elements[i]).attr('id') == 'input_UnitNumber')) {
                if (BottomLine.TransactionType == 0)
                    isValidationSucceed = false;
            }
            else {
                isValidationSucceed = false;
            }
        }
    }

    if ($('#input_AgentName').hasClass("requiredField")) {

        var agentName = $('#input_AgentName').val().trim();
        agentName = agentName.length > 0 ? agentName : $('.agentName').html().trim();
        if (agentName != "") {
            var agentId = $('#input_AgentName').attr('data-value').trim();
            if (agentId == "") {
                $(".AgentSearchSuggestionDiv").hide();
                validationEffectForAgent("#input_AgentName");
                isAgentSugg = false;
                return;
            }
            BottomLineValidation.CheckIfValidAgentExist(agentId, ifAgentNameAlreadyExists);
        }
        else {
            validationEffectForAgent("#input_AgentName");
            isValidationSucceed = false;
        }
    }
    else
    {
        if (isValidationSucceed)
            ifAgentNameAlreadyExists(true);

    }

    if (!isValidationSucceed) {
        $('#registrationSave').prop('disabled', false);
        HideLoader();
    }

}


function ifAgentNameAlreadyExists(result) {
    if (!result) {
        try {
            validationEffectForAgent("#input_AgentName");
            isValidationSucceed = false;
        }
        catch (err) { }
    }
    else {
        try {
            if (isValidationSucceed && result) {
                BottomLine.InsertToStats('Click on BottomLine Registration', 'click');
                saveRegistration();
            }
        }
        catch (err) { }

       
    }

    return result;
}



var RegData = {};

function RegistrationFormData() {
    RegData.FullName = $("#input_fullName").val();
    RegData.AgreementName = $("#input_AgreementName").val();
    RegData.AgreementPhone = $("#input_PhoneAgreement").val();
    RegData.AgreementEmail = $("#input_EmailAgreement").val();
    RegData.InfoRequest = $("#input_InfoRequest").val();
    RegData.TransactionType = $("#input_TransactionType").val();
    RegData.Address = $("#input_Address").val();
    RegData.UnitNumber = $("#input_UnitNumber").val();
    RegData.DateOfPurchase = $("#input_DateOfPurchase").val();
    /*//RegData.AgreementNumber = $("#input_AgreementNumber").val*/
    RegData.AgentID = $("#input_AgentName").attr("data-value");
    RegData.DevelopmentID = $("#input_Development").attr("data-value");
    RegData.ProjectedClosingDate = $("#input_ClosingDate").val();

    RegData.AirNumber = $("#input_AirNumber").val();
    RegData.PromoCode = $("#input_PromoCode").val();
    if (RegData.AgentID != "" && RegData.AgentID != "0")
        RegData.AgentName = $("#BrokerNameSelected .agentName").text().trim() + ' - ' + $("#BrokerNameSelected .brokerageName").text().trim();
    else
        RegData.AgentName = $("#input_AgentName").val();
    RegData.DevelopmentName = $("#input_Development").val();
    RegData.DeveloperName = $("#input_Developer").val();
    RegData.Notes = $("#input_NoteAgreement").val(); //SSD+US15204
    if (BottomLine.TransactionType === 0) {
        RegData.Address = "";
    }
    else if (BottomLine.TransactionType === 1) {
        RegData.DevelopmentID = "";
    }
}

function saveRegistration() {
    RegistrationFormData();
    $.post("/saveRegistration", RegData).done(function (data) {
        if (data == 1) {
            RegData = {};
            BottomLine.InsertToStats('BottomLine Registration Success', 'click');
            /*//$("#ancBottomLineRegistrationConfirm").trigger("click");*/
            window.location.href = BottomLine.PageUrl.BottomLineRegistrationConfirm;
        }
    });
}



function autoSuggest() {

    delay(function () {
        createSuggestionDiv();
    }, 500);
}

function developerAutoSuggest() {

    delay(function () {
        createDeveloperSuggestionDiv();
    }, 500);
}

var delay = (function () {
    var timer = 0;
    return function (callback, ms) {
        clearTimeout(timer);
        timer = setTimeout(callback, ms);
    };
})();


function getSuggestionData() {

}


function createDeveloperSuggestionDiv() {
    if ($("#input_InfoRequest").val() != 'Other / Not Sure') return;
    $(".DeveloperSuggestionDiv").empty();

    var searchData = $("#input_Development").val();

    if (searchData == "") {
        $(".DeveloperSuggestionDiv").hide();
        return;
    }

    $.get("/DeveloperAutoSuggestion", { DeveloperName: searchData }).done(function (data) {



        var length = data.length;

        if (length > 0) {
            $(".DeveloperSuggestionDiv").show();
        }


        DevelopmentDataStore = [];

        for (var i = 0; i < length; i++) {


            var newObject = {};

            newObject.projectId = data[i].projectId;
            newObject.developerName = data[i].developerName;
            newObject.projectName = data[i].projectName;

            DevelopmentDataStore.push(newObject);

            DeveloperSuggestionDOM(data[i].projectId, data[i].developerName, data[i].projectName);
        }
    });

}

var AgentSuggestDataStore = [];
var DevelopmentDataStore = [];

function createSuggestionDiv() {
    isValidAgent = false
    if ($('#input_AgentName').hasClass("requiredField")) {
    $("#input_AgentName").parent().parent().removeClass("TextBoxValidationError");
    $("#input_AgentName").next().next().css({ "visibility": "hidden" });
    }
    $(".AgentSearchSuggestionDiv").empty();

    var searchData = $("#input_AgentName").val();

    if (searchData == "") {
        $(".AgentSearchSuggestionDiv").hide();
        return;
    }

    $.get("/AgentAutoSuggestion", { projectName: searchData }).done(function (data) {


        var length = data.length;

        if (length > 0) {
            isAgentSugg = true;
            $(".AgentSearchSuggestionDiv").show();
        }
        else {
            isAgentSugg = false;
            validationEffectForAgent("#input_AgentName");
        }

        AgentSuggestDataStore = [];

        for (var i = 0; i < length; i++) {

            var newObject = {};

            newObject.BrokerID = data[i].BrokerID;
            newObject.BrokerName = data[i].BrokerName;
            newObject.BrokerageName = data[i].BrokerageName;
            newObject.Title = data[i].Title;
            AgentSuggestDataStore.push(newObject);

            AgentSuggestionDOM(data[i].BrokerID, data[i].BrokerName, data[i].BrokerageName, data[i].imgProfileImage, data[i].Title);
        }
    });
}

function displayNone(id) {
    $("#input_AgentName").removeAttr("readonly").attr("data-value", "").attr("placeholder", "Enter Agent Name").focus();
    $(id).hide();
}

function showAgentNameOnTextBox(id) {

    RegData.AgentID = id;

    $('#BrokerNameSelected').show();
    $('#input_AgentName').val("");

    var length = AgentSuggestDataStore.length;

    for (var i = 0; i < length; i++) {

        if (AgentSuggestDataStore[i].BrokerID == id) {

            var BrokerName = AgentSuggestDataStore[i].BrokerName;
            var BrokerageName = AgentSuggestDataStore[i].BrokerageName;

            $("#input_AgentName").attr('placeholder', '').attr("data-value", id)

            $($('#BrokerNameSelected').children()[0]).text(BrokerName);
            $($('#BrokerNameSelected').children()[1]).text(BrokerageName);

            $('.AgentSearchSuggestionDiv').hide();
            $("#section-agent").css("position", "relative");
        }
    }
}


function showDevelopmentNameOnTextBox(id) {

    RegData.DevelopmentID = id;

    $('#DevelopmentNameSelected').show();
    $('#input_Development').val("");

    var length = DevelopmentDataStore.length;

    for (var i = 0; i < length; i++) {

        if (DevelopmentDataStore[i].projectId == id) {

            var developerName = DevelopmentDataStore[i].developerName;
            var projectName = DevelopmentDataStore[i].projectName;

            $("#input_Development").attr('placeholder', '').attr("data-value", id);

            $('#input_Development').val(projectName);
            $('#input_Developer').val(developerName);

            $('.DeveloperSuggestionDiv').hide();

        }
    }
}


function DeveloperSuggestionDOM(projectId, text1, text2) {

    var suggestionDiv = $(".DeveloperSuggestionDiv");
    var WrapperDiv = $('<div/>', { click: function () { showDevelopmentNameOnTextBox($(this).attr('id')) } });
    var agentInfo = $('<div/>');
    var developerName = $('<div/>');
    var DevelopmentName = $('<div/>');
    var clearDiv = $('<div/>');

    agentInfo.addClass('agentInfo');
    DevelopmentName.addClass('agentName');
    clearDiv.addClass('clear');

    developerName.text(text1);
    DevelopmentName.text(text2);

    agentInfo.append(DevelopmentName);
    agentInfo.append(developerName);

    WrapperDiv.addClass('agentWrapperDiv');

    WrapperDiv.attr('id', projectId);

    WrapperDiv.append(agentInfo);
    WrapperDiv.append(clearDiv);

    suggestionDiv.append(WrapperDiv);

}



function AgentSuggestionDOM(BrokerID, text1, text2, imgProfileImage, title) {

    var suggestionDiv = $(".AgentSearchSuggestionDiv");
    var WrapperDiv = $('<div/>', { click: function () { showAgentNameOnTextBox($(this).attr('id')) } });
    var agentImage = $('<div/>');
    var agentInfo = $('<div/>');
    var developerName = $('<div/>');
    var salesPerson = $('<div/>');
    var DevelopmentName = $('<div/>');
    var img = $('<img/>');

    agentImage.addClass('agentImage');
    agentInfo.addClass('agentInfo');

    salesPerson.addClass('salesinfo')
    salesPerson.css('font-size', '11px');
    developerName.addClass('agentName');
    DevelopmentName.css('font-size', '11px');

    img.attr('src', imgProfileImage);
    agentImage.append(img);

    developerName.text(text1);
    DevelopmentName.text(text2);
    salesPerson.text(title);
    agentInfo.append(developerName);
    agentInfo.append(salesPerson);
    agentInfo.append(DevelopmentName);

    WrapperDiv.addClass('agentWrapperDiv');

    WrapperDiv.attr('id', BrokerID);

    WrapperDiv.append(agentImage);
    WrapperDiv.append(agentInfo);

    suggestionDiv.append(WrapperDiv);
    $("#section-agent").css("position", "");
}

var BottomLine = {
    TransactionType: 0,
    SiteName: "",
    FromBackPage: false,
    SiteDomain: $("input#siteDomain").val(),
    FacebookAppId: $("#facebookAppId").val(),
    TwitterShareText: $("#twitterShareText").val(),
    PageUrl: {
        BottomLine: "/BottomLine",
        BottomLineCoupon: "/BottomLine-Coupon",
        BottomLineVendors: "/BottomLine-Vendors",
        BottomLineRegistration: "/BottomLine-Register",
        BottomLineRegistrationConfirm: "/BottomLine-Registration-Confirm"
    },

    InsertToStats: function (action, eventname) {

        var url = "/InsertToStats";

        var statsModel = {
            PageUrl: location.href,
            Action: action,
            ReferrerUrl: encodeURI(document.referrer == undefined ? '' : document.referrer),
            PageTitle: $(document).find("title").text()
        }

        $.ajax({
            type: "POST",
            url: url,
            data: JSON.stringify(statsModel),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            cache: false,
            success: function (data) {
                if (typeof data != 'undefined' && data == true) {

                }
            },
            error: function (a, b, c) {
                var message = a.responseText;

            }
        });
    },
    InsertToGoogleAnalytics: function (options, action) {
        ga('send', 'event', action, options.eventName, options.value);
    },
    ChangeUrl: function (url) {
        if (!BottomLine.FromBackPage) {
            var newUrl = url;
            if (history.pushState) {
                history.pushState({
                    old_url: "/",
                    new_url: newUrl
                }, null, newUrl);
            }
        }

        BottomLine.FromBackPage = false;
    },
    UpdateBottomLineMenu: function (activeMenu) {
        $(".menuLinks").removeClass("selected");
        $("a[data-href='" + activeMenu + "']").parent().addClass("selected");
    },
    OpenVendors: function (ctrl) {
        BottomLine.SiteName = $(ctrl).attr("data-name");
        window.location.href = "/BottomLine-Vendors#" + BottomLine.SiteName;
    },
    OpenDetails: function (dataHref) {
        $("#" + dataHref).trigger("click");
    },
    OpenDetailPage: function () {
        $(".menuLinks").click(function () {
            var dataHref = $(this).find("a").attr("data-href");
            $("#" + dataHref).trigger("click");
        });
    },
    AdjustClass: function (className) {
        $("#actionDescription").removeClassPrefix("page-").addClass(className);
    },
    AdjustShareUrl: function (shareUrl) {

        shareUrl = BottomLine.SiteDomain + shareUrl;
        $("#facebookShareUrl").attr("href", shareUrl.toFacebookShareUrl(BottomLine.FacebookAppId));
        $("#twitterShareUrl").attr("href", shareUrl.toTwitterShareUrl(BottomLine.TwitterShareText));
    },
    ChageMetaUrl: function (url) {
        $("meta[property='og:url']").attr("content", BottomLine.SiteDomain + url);
    },
    AdjustRegistrationForm: function () {
        var infoRequest = $("#input_InfoRequest").val();

        if (infoRequest == "Other / Not Sure") {
            $("#input_AgentName").removeAttr("readonly").attr("placeholder", "Enter Agent Name");
            $("#input_Development").removeAttr("readonly");
        }
        else {
            if ($("#input_AgentName").length > 0 && ($("#input_AgentName").attr("data-value").trim().length < 1 || $("#input_AgentName").attr("data-value") < 1)) {
                $("#input_AgentName").removeAttr("readonly").attr("placeholder", "Enter Agent Name");
            }
            else {
            }

            $("#input_Development").attr("readonly", "readonly");
        }
    },
    OnCompleteBottomLineVendors: function () {
        if (BottomLine.SiteName.length > 0) {
            var scrollTop = $("div[data-name='" + BottomLine.SiteName + "']").position().top;
            $(document).scrollTop(scrollTop);
            BottomLine.AdjustClass("page-bottomlinevendors");
            BottomLine.ChangeUrl(BottomLine.PageUrl.BottomLineVendors);
            BottomLine.ChageMetaUrl(BottomLine.PageUrl.BottomLineVendors);
            BottomLine.AdjustShareUrl(BottomLine.PageUrl.BottomLineVendors);
            BottomLine.UpdateBottomLineMenu("ancBottomLineCoupon");
            BottomLine.SiteName = "";
        }
    },
    OnCompleteBottomLineInfo: function () {
        $(document).scrollTop(0);
        BottomLine.AdjustClass("page-bottomlineinfo");
        BottomLine.ChangeUrl(BottomLine.PageUrl.BottomLine);
        BottomLine.ChageMetaUrl(BottomLine.PageUrl.BottomLine);
        BottomLine.AdjustShareUrl(BottomLine.PageUrl.BottomLine);
        BottomLine.UpdateBottomLineMenu("ancBottomLineInfo");
    },
    OnCompleteProgramDetails: function () {
        $(document).scrollTop(0);
        BottomLine.AdjustClass("page-botttomlineprogramdetails");
        BottomLine.ChangeUrl(BottomLine.PageUrl.BottomLineCoupon);
        BottomLine.ChageMetaUrl(BottomLine.PageUrl.BottomLineCoupon);
        BottomLine.AdjustShareUrl(BottomLine.PageUrl.BottomLineCoupon);
        BottomLine.UpdateBottomLineMenu("ancBottomLineCoupon");
    },
    OnCompleteRegistrationForm: function () {
        $(document).scrollTop(0);
        BottomLine.AdjustClass("page-bottomlineregistration");
        BottomLine.ChangeUrl(BottomLine.PageUrl.BottomLineRegistration);
        BottomLine.ChageMetaUrl(BottomLine.PageUrl.BottomLine);
        BottomLine.AdjustShareUrl(BottomLine.PageUrl.BottomLine);
        BottomLine.UpdateBottomLineMenu("ancBottomLineRegister");
        var RegData = {};

        BottomLine.InitializeRegistrationEvent();
    },
    OnCompleteBottomLineRegistrationConfirm: function () {
        $(document).scrollTop(0);
        BottomLine.AdjustClass("page-bottomlineregconfirm");
        BottomLine.ChangeUrl(BottomLine.PageUrl.BottomLineRegistrationConfirm);
        BottomLine.ChageMetaUrl(BottomLine.PageUrl.BottomLine);
        BottomLine.AdjustShareUrl(BottomLine.PageUrl.BottomLine);
        BottomLine.UpdateBottomLineMenu("ancBottomLineRegister");
    },
    InitializePurchaseDatePicker: function () {
        var purchaseDateTime = $("#input_DateOfPurchase").val();
        purchaseDateTime = purchaseDateTime == "" ? "" : new Date(purchaseDateTime);
        purchaseDate = new IphoneDateTimePicker($("#PurchaseDatePickerSection"), purchaseDateTime);
    },
    InitializeClosingDatePicker: function () {
        var closingDateTime = $("#input_ClosingDate").val();
        closingDateTime = closingDateTime == "" ? "" : new Date(closingDateTime);
        closingDate = new IphoneDateTimePicker($("#ClosingDatePickerSection"), closingDateTime);
    },
    InitializeRegistrationEvent: function () {
        if (!$(".left-part-reg").is(':visible')) {
            adjustPlaceholder();
        }

        BottomLine.InitializePurchaseDatePicker();
        BottomLine.InitializeClosingDatePicker();

        $("#transactionType").on('click', function () {
            $(".TransactionTypeFloatingDiv").show();
        });

        $("#saveDateTime").click(function () {
            var month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
            var selectedDateString = purchaseDate.GetSelectedDateTime();
            var selectedDate = new Date(selectedDateString);
            $("#input_DateOfPurchase").val(month[selectedDate.getMonth()] + " " + selectedDate.getDate() + ", " + selectedDate.getFullYear());
            $("#dvPurchaseDatePicker").removeClass("open-datePicker");
            validationClear($("#input_DateOfPurchase"));
        });

        $("#input_DateOfPurchase").on('focus', function () {
            $("#dvPurchaseDatePicker").addClass("open-datePicker");
        });

        $("#saveClosingDateTime").click(function () {
            var month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
            var selectedDateString = closingDate.GetSelectedDateTime();
            var selectedDate = new Date(selectedDateString);
            $("#input_ClosingDate").val(month[selectedDate.getMonth()] + " " + selectedDate.getDate() + ", " + selectedDate.getFullYear());
            $("#dvClosingDatePicker").removeClass("open-datePicker");
            validationClear($("#input_ClosingDate"));
        });

        $("#input_ClosingDate").on('focus', function () {
            $("#dvClosingDatePicker").addClass("open-datePicker");
        });
        $("#input_TransactionType").change(function () {
            if ($("#input_TransactionType").val() == "Resale / Rental") {
                $("#DevelopmentFieldBox").hide();
                $("#DeveloperFieldBox").hide();
                $("#AddressFieldBox").show();
                $("#lblUnitNumber").text("  Unit Number");
                BottomLine.TransactionType = 1;
            }
            else {
                $("#DevelopmentFieldBox").show();
                $("#DeveloperFieldBox").show();
                $("#AddressFieldBox").hide();
                $("#lblUnitNumber").text("* Unit Number");
                BottomLine.TransactionType = 0;
            }
        });
        $(".selectionBox").on('click', function (event) {

            $(".selectionBox > .optionBox").removeClass("selected");
            $(this).find("div.optionBox").addClass("selected");
            BottomLine.TransactionType = parseInt($(this).attr("data-options"));

            if ($(this).attr('id') == 'selectionFirst') {
                $("#input_TransactionType").val("New Home");
                $("#input_TransactionType").next().css({ "visibility": "hidden" });
                $("#input_TransactionType").parent().parent().removeClass("TextBoxValidationError");
                $("#DevelopmentFieldBox").show();
                $("#DeveloperFieldBox").show();
                $("#AddressFieldBox").hide();
                $("#lblUnitNumber").text("* Unit Number");
                $("#input_UnitNumber").attr("placeholder", "* Unit Number");
                $("#lblPurchaseDate").text("* Date of Purchase");
                $("#input_DateOfPurchase").attr("placeholder", "* Date of Purchase");
                $("#lblUnitNumber").blur();

            } else if ($(this).attr('id') == 'selectionSecond') {
                $("#input_TransactionType").val("Resale / Rental");
                $("#input_TransactionType").next().css({ "visibility": "hidden" });
                $("#input_TransactionType").parent().parent().removeClass("TextBoxValidationError");
                $("#DevelopmentFieldBox").hide();
                $("#DeveloperFieldBox").hide();
                $("#AddressFieldBox").show();
                $("#lblUnitNumber").text("Unit Number");
                $("#input_UnitNumber").attr("placeholder", "Unit Number");
                $("#lblPurchaseDate").text("* Date of Purchase/Rental");
                $("#input_DateOfPurchase").attr("placeholder", "* Date of Purchase/Rental");
                validationClear($("#input_UnitNumber"));

            }

            $("#lastSection").show();
            $("#TransactionTypeDiv").removeClass("singleTextBox").addClass("firstTextBox");
            $("#AgentNameDiv").css({ "visibility": "visible" });

            $(".mobileVersionElements").css({ "position": "initial", "margin-top": "10px" });

            $(".TransactionTypeFloatingDiv").hide();

            event.stopPropagation();

        });

        $('#registrationSave').on('click', function () {
            isValidationSucceeded();
        });

        $(".requiredField:not([readonly])").on("blur", function () {
            validationEffect($(this));
        });

        $(".requiredField").on("focus", function () {
            validationClear($(this));
        });

        $("#input_AgentName").on("focus", function () {
            validationClear($(this));
        });


        if (document.getElementById('input_Address') != null) {
            var inputDev = document.getElementById('input_Address');
        }

        $("#input_InfoRequest").change(function () {
            var infoRequest = $(this).val();

            if (infoRequest == "Other / Not Sure") {
                $("#input_AgentName").attr("data-value", "").attr("placeholder", "Enter Agent Name");
                $("#BrokerNameSelected > .agentName").html("");
                $("#BrokerNameSelected > .brokerageName").html("");

                $("#input_Development").val("");
                $("#input_Development").attr("data-value", "");

                $("#input_Developer").val("");
                $("#input_Developer").attr("data-value", "");

                $("#input_UnitNumber").val("");

                $("#input_DateOfPurchase").val("");
                BottomLine.InitializePurchaseDatePicker();

                $("#input_ClosingDate").val("");
                BottomLine.InitializeClosingDatePicker();

                BottomLine.AdjustRegistrationForm();
            }
            else {
                $.ajax({
                    type: "GET",
                    url: "BottomLineInfoByProspectID",
                    data: { infoRequest: infoRequest },
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    cache: false,
                    beforeSend: function () { },
                    complete: function () { },
                    success: function (data) {
                        $("#input_AgentName").val('');
                        $("#BrokerNameSelected").show();
                        $("#input_AgentName").attr("data-value", data.Result.BrokerID);
                        $("#BrokerNameSelected > .agentName").html(data.Result.BrokerName);
                        $("#BrokerNameSelected > .brokerageName").html(data.Result.BrokerageName);

                        $("#input_Development").val(data.Result.ProjectName);
                        $("#input_Development").attr("data-value", data.Result.ProjectID);

                        $("#input_Developer").val(data.Result.DeveloperNames);
                        $("#input_Developer").attr("data-value", data.Result.DeveloperIDs);

                        $("#input_AgentName").attr("placeholder", "");

                        $("#input_Development").attr("readonly", "readonly");

                        $("#input_UnitNumber").val(data.Result.UnitNumber);

                        $("#input_DateOfPurchase").val(data.Result.DateOfPurchaseString);
                        BottomLine.InitializePurchaseDatePicker();

                        $("#input_ClosingDate").val(data.Result.ProjectedClosingDate);
                        BottomLine.InitializeClosingDatePicker();

                        if (data.Result.BrokerID > 0) validationClear($("#input_AgentName"));
                        validationClear($("#input_Development"));
                        validationClear($("#input_Developer"));

                        BottomLine.AdjustRegistrationForm();
                    }
                });
            }
        });
    },
    OpenVideo: function () {

        var videoURL = $(".youTubeVideo").attr("data");
        $("a#inline").fancybox({
            'hideOnContentClick': true,
            openSpeed: 100,
            closeSpeed: 100,
            afterClose: function () {
                setTimeout(function () {
                    $("#iframePopUPVideo").removeAttr("src").html("");
                }, 600);
            },

            beforeShow: function () {
                $("#iframePopUPVideo").attr("src", videoURL + "?autoplay=1&rel=0&showinfo=0&enablejsapi=1&wmode=opaque");
                $(".fancybox-skin").css("padding", "0px");
            }

        });

        $(".youTubeVideo").click(function () {
            

            
            $("a#inline").click();
        });
    },
    GetAnchorByUrl: function (url) {
        if (url == "/bottomline-coupon")
            return "ancBottomLineCoupon";
        if (url == "/bottomline-register")
            return "ancBottomLineRegister";
        if (url == "/bottomline-vendors")
            return "ancBottomLineVendor";
        if (url == "/bottomline-registration-confirm")
            return "ancBottomLineRegistrationConfirm";

        return "ancBottomLineInfo";
    },
    BackPage: function () {
        window.addEventListener('popstate', function (event) {
            BottomLine.FromBackPage = true;
            var anchorName = BottomLine.GetAnchorByUrl(location.pathname.toLocaleLowerCase());
            $("#" + anchorName).trigger("click");
        });
    }
}

var AddBottomLineRecord = function (sharedvia) {

    var url = "/AddRecordBottomLineShared";
    $.ajax({
        type: "POST",
        url: url,
        data: "{'sharedvia': '" + sharedvia + "'}",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        beforeSend: function () { $("#ajax_spinner").show(); },
        complete: function () { $("#ajax_spinner").hide(); },
        success: function (data) {
            if (data.d != "") {

            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        }
    });
}
var AddressGenerationHelper = {
    _country_ga: "",
    _City: "",
    _State: "",
    _Country: "",
    _Zip: "",
    _Street: "",
    SetAddressPartsForProject: function (place, addressType, predicted_address) {
        var objCountry = AddressGenerationHelper.GetObjectByType(place.address_components, 'country');
        var objState = AddressGenerationHelper.GetObjectByType(place.address_components, "administrative_area_level_1");
        var objZip = AddressGenerationHelper.GetObjectByType(place.address_components, "postal_code");
        var objCity = AddressGenerationHelper.GetObjectByType(place.address_components, "locality");
        var objStreet = AddressGenerationHelper.GetObjectByType(place.address_components, "street_number");
        var objRoute = AddressGenerationHelper.GetObjectByType(place.address_components, "route");

        AddressGenerationHelper._City = objCity ? objCity.short_name : "";
        AddressGenerationHelper._Zip = objZip ? objZip.short_name : "";
        AddressGenerationHelper._State = objState ? objState.short_name : "";
        AddressGenerationHelper._Country = objCountry ? objCountry.short_name : "";
        var addressRouteValue = objRoute ? objRoute.short_name : "";
        var addressStreetValue = objStreet ? objStreet.short_name : "";

        if (addressRouteValue == "" && addressStreetValue == "")
            AddressGenerationHelper._Street = "";
        else if (addressRouteValue == "")
            AddressGenerationHelper._Street = addressStreetValue;
        else if (addressStreetValue == "")
            AddressGenerationHelper._Street = addressRouteValue;
        else
            AddressGenerationHelper._Street = addressStreetValue + " " + addressRouteValue;

        $("#City").val(AddressGenerationHelper._City);
        $("#Zip").val(AddressGenerationHelper._Zip);
        $("#State").val(AddressGenerationHelper._State);
        $("#Country").val(AddressGenerationHelper._Country);
        $("#Street").val(AddressGenerationHelper._Street);
    },
    GetObjectByType: function (objects, type) {
        var objectArray = $(objects).toArray();
        for (var count = 0; count < objectArray.length; count++) {
            var objType = objectArray[count].types[0];
            if (objType == type)
                return objectArray[count];
        }
        return null;
    },
    SetAddressAutoCompleteForControl: function (input, addressType) {
        $(input).focus(function () {
            if ($(this).val() == "Enter a location") {
                $(this).val('');
            }
        });
        var lat = 43.767421;
        var long = -79.475509;
        var defaultBounds = new google.maps.LatLngBounds(new google.maps.LatLng(lat, long));
        var options = {
            bounds: defaultBounds,
            types: ['geocode', 'establishment']
        };
        if (this._country_ga != '') {
            options.componentRestrictions = {
                country: this._country_ga.toLowerCase()
            };
        }
        var autocomplete = new google.maps.places.Autocomplete(input, options);
        address_type = addressType;
        google.maps.event.addListener(autocomplete, 'place_changed', function () {
            var place = autocomplete.getPlace();
            if (place.address_components.length < 2) {
                var service = new google.maps.places.AutocompleteService();
                service.getQueryPredictions({
                    input: place.name
                }, function (predictions, status) {
                    var addr1 = predictions[0].terms[0].value;
                    var city = predictions[0].terms[1].value;
                    var country = predictions[0].terms[predictions[0].terms.length - 1].value;
                    var state = predictions[0].terms.length > 3 ? predictions[0].terms[2].value : '';
                    pre_address = {
                        address1: addr1,
                        city: city,
                        state: state,
                        country: country
                    };
                    AddressGenerationHelper.SetAddressPartsForProject(null, address_type, pre_address);
                    $("#" + input.id.substr(0, input.id.length - 1) + "2").focus();
                });
            } else {

                AddressGenerationHelper.SetAddressPartsForProject(place, addressType, null);
            }
        });
    }
}


var HomeScreen = {
    showVideoFullScreen: function () {
        $("#divHomeVideo").show();
        HomeScreen.playVideo();
        $(divvideoPlayPause).hide();
        $(divvideoPlayPause).attr('playtrack', '1');
        CondonowVideoStats();
        MakeChangeUrl(true, false, false, true);
    },
    playVideo: function () {
        try {
            var mediaPlayer = document.getElementById(condoplayer);
            mediaPlayer.currentTime = 0;
            mediaPlayer.load();
            mediaPlayer.play();
        }
        catch (err) {
        }

    },
    onLearnMoreClick: function () {
        new parent.ProjectStats().recordProjectStats(parent.ProjectID, undefined, parent.ProjectStatsUtil.GetPageUrl(), "Learn more", 0, undefined, undefined);
    },
    pauseVideo: function () {
        var mediaPlayer = document.getElementById(condoplayer);
        mediaPlayer.pause();
    },
    hideAndStopVideo: function () {
        new parent.ProjectStats().recordProjectStats(parent.ProjectID, undefined, parent.window.location.href, "Close video", 0, undefined, undefined);
        try {
            HomeScreen.pauseVideo();
        }
        catch (err) {
        }
        $("#divHomeVideo").hide();
        $(divvideoPlayPause).attr('playtrack', '0');
        MakeChangeUrl();

    },
    onVideoClick: function () {
        try {
            HomeScreen.pauseVideo();
        }
        catch (err) {
        }
        $(divvideoPlayPause).show();
        $(divvideoPlayPause).attr('playtrack', '0');
    },
    onVideoArrowClick: function () {
        if ($(divvideoPlayPause).attr('playtrack') == '0') {
            $(divvideoPlayPause).hide();
            $(divvideoPlayPause).attr('playtrack', '1');
            var mediaPlayer = document.getElementById(condoplayer);
            mediaPlayer.play();
        }
    }
}
function ShowLoader() {
  $("body").append($("<div class='customSpinner'><span class='customLoading'></span></div>"));
}
function HideLoader() {
    $("div.customSpinner").remove();
}
