﻿// this is an additional js-code for some common features

/* **********************************************************
* Forgotten your password
********************************************************** */ 

    function SendMeMyPassword2(targetUrl) {
        $.ajax({
            type: 'POST',
            url: targetUrl,
            data: $('#LoginBoxForm').serialize(),
            success: function (pResult) {
                $('#ForgotPasswordPopup-content').html(pResult);
                $('#ForgotPasswordPopup')
                    .data('tWindow')
                    .center()
                    .open();
            },
            async: false,
            error: function (pResult) {
                onWcfCallFailure(pResult);
            }
        });
	}

	function Login2(targetUrl) {
		$.ajax({
			type: 'POST',
			url: targetUrl,
			data: $('#LoginForm').serialize(),
			success: function (pResult) {
			    onNotificationLogonSuccess2(pResult);
			},
			error: function(pResult) {
				onWCFFailure(pResult);
			}
		});
	}

	function LoginCancel2(cancelMsg) {
		if ($('#NotificationPopup-content').length) {
			$('#NotificationPopup-content').html(cancelMsg);
		} else {
			$('#CreateNotificationPopup-content').html(cancelMsg);
		}
	}

	function onNotificationLogonSuccess2(pResult) {
		for (key in pResult) {
			if ("failed" == key) {
			    $("#LogOnPane .error-message-block").html(pResult[key]).show();
			}
	        if ("success" == key) {
				if ($("#confirmSent").length) {
					$("#LoginForm").hide();
					$("#confirmSent").show();
				} else {
	            window.document.location.reload();
			}
		}
	}
}

	function OnSendMePasswdClick2(enterEmail,msg,sendPswdUrl) {
        jQuery.validator.setDefaults({
	        debug: false,
	        success: "valid"
	    });

	    $('#SendPasswdForm').validate({
	        rules: {
	            userEmail: {
	                email: true,
	                required: true
	            }
	        },
	        messages: {
	            userEmail: {
	                email: enterEmail,
	                required: enterEmail
	            }
	        },
	        showErrors: function (errorMap, errorList) {
	            var messageTmpl = msg;
	            $("#sendPassword div.error-message-block:first").html($.formatString(messageTmpl, this.numberOfInvalids()));
	            $("#sendPassword div.error-message-block:first").show();
	            this.defaultShowErrors();
	            if (this.numberOfInvalids() == 0) { $("#sendPassword div.error-message-block:first").hide(); }
	        },
	        highlight: function (element) { $(element).parent("li").addClass('error'); },
	        unhighlight: function (element) { $(element).parent("li").removeClass('error'); },
	        errorPlacement: function (error, element) {
	            error.appendTo(element.parent("li").attr("title", error.text()));
	            error.remove();
	        }
	    });

	    if ($('#SendPasswdForm').valid()) {
	        $.ajax({
	            type: 'POST',
	            url: sendPswdUrl,
	            data: $('#SendPasswdForm').serialize(),
	            success: function (pResult) {
	                var key;
	                for (key in pResult) {
	                    switch (key) {
	                        case "invalidEmail":
	                            $("#sendPassword div.error-message-block:first").show();
	                            $("#SendPasswdForm-mail li").addClass('error');
	                            $("#sendPassword div.error-message-block:first").html(pResult[key]);
	                            break;
	                        case "passSent":
	                            $("#sendPassword").html('<div class="message-box Password-Sent"><h4>' + pResult[key] + '</h4></div>');
	                            break;
	                    }
	                }
	            },
                async: false,
	            error: function (pResult) {
	                onWcfCallFailure(pResult);
	            }
	        });
	    }
	}

	function AlertNotSavedPopupClose() {
		if ($('#CampaignPopUpContainer').length == 0)
			window.location.reload();
		else
			$('#CreateNotificationPopup').data('tWindow').close();
	}


/* **********************************************************
* Send to Friend
********************************************************** */ 

var validatorSTF;

function SendToFriendOpen2(dialogTitle) {
    $('#SendToFriend')
        .data('tWindow')
        .center()
        .open();
}

function OnSendToFriendClick2(sendToFriendSubject, targetUrl) {
	document.getElementById("subject").value = (
		$('#fromName').val()
		+ " "
		+ $('#fromLastName').val()
		+ " "
		+ sendToFriendSubject
	);

	if (!FormIsValidByJQuerySTF()) {
		return;
	}

	$.ajax({
	    type: 'POST',
	    url: targetUrl,
	    data: ({
	        userFirstName: $('#fromName').val(),
	        userLastName: $('#fromLastName').val(),
	        userEmail: $('#fromAddress').val(),
	        toAddress: $('#toAddress').val(),
	        subject: $('#subject').val(),
	        message: $('#message').val(),
	        campaignLink: $('#campaignLink').val(),
	        campaignLinkMessage: $('#campaignLinkMessage').val()
	    }),
	    success: function (pResult) {
	        $('#SendToFriendMain').hide();
	        $('#SendToFriendResult')
                .html(pResult)
			    .show();
	        $('#confirmButtonSTF').click(function () {
	            $('#SendToFriend')
                    .data('tWindow')
                    .close();
	            $('#SendToFriendResult').hide()
	            $('#SendToFriendMain').show();
	        });
	    },
	    error: function (pResult) {
	        onWcfCallFailure(pResult);
	    }
	});
}

function FormIsValidByJQuerySTF() {
	jQuery.validator.setDefaults({
		debug: false,
		success: "valid"
	});

	validatorSTF = $('#SendToFriendForm').validate({
		rules: {
			fromName: { required: true, maxlength: 255 },
			fromLastName: { required: true, maxlength: 255 },
			fromAddress: { required: true, email: true, maxlength: 255 },
			toAddress: { required: true, email: true, maxlength: 255 },
			subject: { required: true, maxlength: 255 }
		},
		showErrors: function(errorMap, errorList) {
			var messageTmpl = $('#FormErrorMessage').val();
			$("#SendToFriendForm div.error-message-block:first").html($.formatString(messageTmpl, this.numberOfInvalids()));
			$("#SendToFriendForm div.error-message-block:first").show();
			this.defaultShowErrors();
			if(this.numberOfInvalids() > 0) {
				$("html").scrollTop($('#SendToFriendForm div.error-message-block:first').position().top);
			} else {
				if(this.numberOfInvalids()==0) { $("#SendToFriendForm div.error-message-block:first").hide(); }
			}
		},
		highlight: function(element) { $(element).parent("li").addClass('error'); },
		unhighlight: function(element) { $(element).parent("li").removeClass('error'); },
		errorPlacement: function(error, element) {
			error.appendTo(element.parent("li").attr("title",error.text()));
			error.remove();
		},
		messages: {
			fromName: {
				required: $('#fromNameErrorMessage').val(),
				maxlength: $.validator.format($('#fromNameValidator').val(), 255)
			},
			fromLastName: {
				required: $('#fromLastNameErrorMessage').val(),
				maxlength: $.validator.format($('#fromLastNameValidator').val(), 255)
			},
			fromAddress: {
				required: $('#fromAddressErrorMessage').val(),
				email: $('#fromAddressValidator').val()
			},
			toAddress: {
				required: $('#toAddressErrorMessage').val(),
				email: $('#toAddressValidator').val()
			},
			subject: {
				required: $('#subjectErrorMessage').val(),
				maxlength: $.validator.format($('#subjectValidator').val(), 255)
			}
		}
	});
	return $('#SendToFriendForm').valid();
}


/* **********************************************************
* Campaign Alert
********************************************************** */ 

var userContactEmailTEMP = '';
var registerPaneUserFirstNameTEMP = '';
var registerPaneUserLastNameTEMP = '';

var CampaignSubscribeFormData = {
    DialogId: 'NotificationPopup-content',
	chkOfferDay: true
};

function CampaignAlert2(targetUrl, tempLanguage, tempTitle, campaignId, chkProvider, targetAdZoneModuleGUID) {
	CampaignSubscribeFormData['CampaignId'] = campaignId;
	CampaignSubscribeFormData['chkProvider'] = chkProvider;
	CampaignSubscribeFormData['TargetAdZoneModuleGUID'] = targetAdZoneModuleGUID;

	$.ajax({
	    type: 'POST',
	    url: targetUrl,
	    data: CampaignSubscribeFormData,
	    success: function (pResult) {
	        UpdateMenu(tempLanguage);
	        $('#NotificationPopup-content').html(pResult);
	        $('#NotificationPopup')
                .data('tWindow')
                .center()
                .open();
	        if ($('#EnterEmailContactForm').length > 0 && typeof (userContactEmailTEMP))
	            $('#userContactEmail').val(userContactEmailTEMP);
	    },
	    error: function (pResult) {
	        onWcfCallFailure(pResult);
	    }
	});

	if (CampaignSubscribeFormData['userContactEmail'])
		userContactEmailTEMP = CampaignSubscribeFormData['userContactEmail'];
}

function LeaveNotificationPopup(withReloadPage) {
	if (withReloadPage=='True') {
		if ($.browser.msie && $.browser.version < 8) {
			window.location = window.location;
			window.location.reload();
			document.location.reload();
		} else {
			location.reload();
		}
    } else {
        if (typeof $('#CreateNotificationPopup').data('tWindow') !== "undefined") {
            $('#CreateNotificationPopup')
                .data('tWindow')
                .close();
        }
        if (typeof $('#NotificationPopup').data('tWindow') !== "undefined") {
            $('#NotificationPopup')
                .data('tWindow')
                .close();
        }
	}
}

$('#EnterEmailContactForm').ready(function () {
	if (typeof (userContactEmailTEMP))
		$('#userContactEmail').val(userContactEmailTEMP);
});

function EmailFormIsValidByJQueryCampaignAlert(messageTmpl1) {
	jQuery.validator.setDefaults({
		debug: false,
		success: "valid"
	});

	$('#EnterEmailContactForm').validate({
		rules: {
			userContactEmail: { required: true, email: true, maxlength: 255 }
		},
		showErrors: function(errorMap, errorList) {
			var messageTmpl = messageTmpl1;
			$("#EnterEmailContactForm div.error-message-block:first").html($.formatString(messageTmpl, this.numberOfInvalids()));
			$("#EnterEmailContactForm div.error-message-block:first").show();
			this.defaultShowErrors();
			if(this.numberOfInvalids() > 0) {
				$("html").scrollTop($('#EnterEmailContactForm div.error-message-block:first').position().top);
			} else {
				if(this.numberOfInvalids()==0) { $("#EnterEmailContactForm div.error-message-block:first").hide(); }
			}
		},
		highlight: function(element) { $(element).parent("li").addClass('error'); },
		unhighlight: function(element) { $(element).parent("li").removeClass('error'); },
		errorPlacement: function(error, element) {
			error.appendTo(element.parent("li").attr("title",error.text()));
			error.remove();
		},
		messages: {
			userContactEmail: {
				required: $('#userContactEmailRequired'),
				email: $('#userContactEmailEmail')
			}
		}
	});

	return $('#EnterEmailContactForm').valid();
}


	function OnEnterEmailClick2(messageTmpl1, targetUrl, tempLanguage, tempTitle, campaignId, chkProvider, targetAdZoneModuleGUID) {
		if (!EmailFormIsValidByJQueryCampaignAlert(messageTmpl1)) {
			return false;
		}

		CampaignSubscribeFormData['userContactEmail'] = $('#userContactEmail').val();
		CampaignAlert2(targetUrl, tempLanguage, tempTitle, campaignId, chkProvider, targetAdZoneModuleGUID)
		return true;
	}



//Campaign.ascx general


	function IsPanoAvailable2() {
		if ($('#Campaign-Tool-toStreetView').length > 0) {
			var center = new google.maps.LatLng(
				$('#Campaign-Tool-toStreetView-Latitude').val()
				, $('#Campaign-Tool-toStreetView-Longitude').val()
			);
			var panoService = new google.maps.StreetViewService();

			panoService.getPanoramaByLocation(center, 50, function (result, status) {
				if (status == google.maps.StreetViewStatus.OK) {
					document.getElementById('Campaign-Tool-toStreetView').style.display = (result != null ? 'block' : 'none');
				}
			})
		}
	}






