﻿
 $(document).ready(function () {
	$('a[rel=qtip]').each(function () {
	    $(this).qtip({
	    content: $(this).attr("title"),
        position: {
            adjust: {
                y: 15,
                x: -8
            },
            my: 'top center'
        },
        style: {
            classes: 'ui-tooltip-dark ui-tooltip-shadow ui-tooltip-rounded'
        }
	    })
	});
});


var userlocation = {
    email: "",
    label: "",
    lat: "",
    lon: "",
    ctag: ""
};
var usertemplocation = {
    email: "",
    label: "",
    lat: "",
    lon: ""
};

//Handles pressing enter.  Set containing div with class ".form" and the default button or link with class ".form-submit"
$(document).ready(function () {
    $('.form').keypress(function (e) {
        
        var element = e.target || e.srcElement;
        var defaultButton = null;

        if (e.keyCode == 13 && !(element && (element.tagName.toLowerCase() == "textarea"))) {

            var foundButton = $(this).find('.form-submit');
            if (foundButton) defaultButton = foundButton[0];

            if (defaultButton) {
                if (typeof (defaultButton.click) != "undefined")
                    defaultButton.click();
                else
                    eval(unescape(defaultButton.href.replace("javascript:", "")));

                event.cancelBubble = true;

                if (event.stopPropagation) event.stopPropagation();
                return false;
            }
        }

        return true;
    });

    $('#changeLocation').keydown(function (e) {
        var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
        if (key == 13) {
            //alert('press');
            if ($('.ui-autocomplete').is(":visible")) {
                //alert('vis');
                e.preventDefault();
                return false;
            }

            //alert('enter');
            submitChangeLocation();
            e.preventDefault();
            return false;
        } else {
            //alert('clear');
            $('#changeloc-error').html('');
            usertemplocation.email = "";
            usertemplocation.label = "";
            usertemplocation.lat = "";
            usertemplocation.lon = "";
        }


    });

    $("#changeLocation").autocomplete({
        source: function (request, response) {
            searchLocations(request.term, function (items) {
                response(items);
            });

        },
        minLength: 4,
        delay: 100,
        autoFocus: false,
        //selectFirst: true,
        change: function (e, ui) {
        },
        select: function (e, ui) {
            displayChangedLocation(ui.item.data);
            $(this).val(ui.item.data.name);
            e.preventDefault();
            return false;
        },
        focus: function (e, ui) {
            e.preventDefault();
            return false;
        }
    })

});

function searchLocations(term, response) {
    $.ajax({
        url: "http://dev.virtualearth.net/REST/v1/Locations",
        dataType: "jsonp",
        data: {
            key: "ArNxi7FzI91w0EftrXqeULBpQv1p8bE4qfw_hUMhcdE5sk3Q16rkyiR1lyU4ThUV",
            q: term
        },
        jsonp: "jsonp",
        success: function (data) {
            var result = data.resourceSets[0];
            if (result) {
                if (result.estimatedTotal > 0) {
                    var items = $.map(result.resources, function (item) {
                        if (item.address.countryRegion == "United States") {
                            return {
                                data: item,
                                label: item.name,
                                value: item.name
                            }
                        }
                    });
                    response(items);
                }
            }
        }
    });
}

//location selected
function displayChangedLocation(item) {
    //$("#searchResult").empty().append('Result: ' + item.name).append(' (Latitude: ' + item.point.coordinates[0] + ' Longitude: ' + item.point.coordinates[1] + ')');

    usertemplocation.label = item.name;
    usertemplocation.lat = item.point.coordinates[0];
    usertemplocation.lon = item.point.coordinates[1];

    //getDealsForMap(item.point.coordinates[0], item.point.coordinates[1], 0, 0, 0, 0, false);

}

//intializes facebook
jQuery(document).ready(function () {
	FB_Init();
});

//google analytics
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-11417770-19']);
_gaq.push(['_setDomainName', '.localdeal.com']);
_gaq.push(['_trackPageview']);
_gaq.push(['_trackPageLoadTime']);
(function () {
	var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
	ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
	var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

function common_Logout() {
	var isIE6 = $.browser.msie && parseFloat($.browser.version) < 7;
	if (isIE6) {
		window.document.location.href = '/logout/';
	}
	else {
		FB_Logout()
	}
}

function closeInfoLine() {
	jQuery(".InfoLine").slideUp(300);
}

function displayInfoLine(className, title, str) {

	jQuery(document).ready(function () {

		var msgText = "";
		if (className == "message-so")
			msgText = "";
		else
			msgText = "<div class=\"message " + className + "\"><span class=\"title\">" + title + "</span><table><tr><td><p>" + str + "</p></td></tr></table></div>"

		jQuery("#message-holder").html(msgText);
		jQuery("#message-holder").slideDown(1000);
	});
}

function resendActivationEmail(email) {
	jQuery.ajaxDotNet(window.LDService + "SendActivationEmail",
    {
    	data: { pEmailAddress: email },
    	success: function (o) {
    		if (o != null) {
    			displayInfoLine('message-info', 'Success', 'Your activation email was resent.');
    		}
    		else {

    		}
    	},
    	error: onCommonError
    });
}

function loadNotActive() {
    jQuery.facebox(function ($) {
        jQuery.get('/social/content/notactive.htm', function (data) {
            jQuery.facebox.settings.modal = false;
            jQuery.facebox(data);
        });
    })
}

$(document).ready(function () {

    $('#txtSubscribeEmail').keypress(function (e) {
        var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
        if (key == 13) {
            e.preventDefault();
            signUpFromMaster($('#txtSubscribeEmail').val(), '#lblErrorSignupMaster');
            return false;
        }
    });

    $('#txtClosedEmail').keypress(function (e) {
        var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
        if (key == 13) {
            e.preventDefault();
            signUpFromMaster($('#txtClosedEmail').val(), '#lblErrorSignupSoldOut');
            return false;
        }
    });

});

function signUpFromMaster(email, errorPlaceHolder) {
	if(!isValidEmail(email)){
	    $(errorPlaceHolder).html('Please enter a valid email address.');
	    return;
    }

    submitEmail(email, false, true,
    function () { //success
        window.document.location.href = '/';
    },
	function (errorCode) {
	    if (errorCode == 1) {
	        $(errorPlaceHolder).html('A user with this email has already signed up.');
	    } else {
	        $(errorPlaceHolder).html('Invalid email address. Do you already have an account?');
	    }
	});
}

function submitEmail(email, setWelcomeCookie, removeWelcomeCookie, success, error) {

    var data = "{ pEmailAddress:'" + email + "', setWelcomeCookie:'" + setWelcomeCookie + "', removeWelcomeCookie:'" + removeWelcomeCookie + "' }";

    $.ajax({
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        url: window.LDService + "AddEmail",
        data: data,
        success: function (o) {
            if (o != null) {
                if (o.d == 0) {
                    success();
                }
                else { error(o.d); }
            } else { error(); }
        },
        error: function () { error(); }
    });
}

function isValidEmail(email) {
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)) {
		return true;
	}
	else
		return false;
}

function onCommonError(o) {
	var str;
	if (o.responseText !== undefined) {
		str = "Error: Transaction id: " + o.tId + " ";
		str += "HTTP status: " + o.status + " ";
		str += "Status code message: " + o.statusText + " ";
		alert(str);
	}
}

function cancelReturn(e) {
	if (getKeyCode(e) == 13) return false;
}

function getKeyCode(e) {
	var evt = (e) ? e : window.event;
	return (evt.charCode) ? evt.charCode : evt.keyCode;
}

function showSubscribeRibbon() {
	$('#show-subscribe').slideUp(100, function () {
		$('#subscribe').show(0, function() {
		});
		deleteCookie('showrib');
	});
	return false;
}

function hideSubscribeRibbon(slideDownInterval) {
	$('#subscribe').hide(0, function() {
		$('#show-subscribe').show();
		setCookie('showrib', '0', 30);
	});
}

jQuery(document).ready(function () {

	if (!getCookie('showrib')) {
		showSubscribeRibbon();
	}
	else {
		hideSubscribeRibbon(0);
	}

	$('#city-select .sel').bind('click', function (e) {

		var $clicked = $(e.target);

		if ( $('#city-select-content').is(":visible") == true) {
            $('#city-select-content').slideUp(300);
			$('#city-select').removeClass('city-select-open');
			$('#main').removeClass('hide-selects'); // class used in IE6 to hide selects due to z-index bug
		} else {
            $('#city-select').addClass('city-select-open');
            $('#main').addClass('hide-selects'); // class used in IE6 to hide selects due to z-index bug
            $('#city-select .textbox-loc').show();
            $('#city-select-content').slideDown(300);
        }
	});


	//	$('#get-email').click(function () {
	//		$('#get-email').hide();
	//		$('#get-email-set').slideDown("fast");
	//		return false;
	//	})


	$('#cancel-email-set').click(function () {
		return hideSubscribeRibbon(200);
	})

	$('#show-subscribe').click(function () {
		return showSubscribeRibbon();
	})

	$('.more').click(function () {
		$('.more-text').show();
		$('.more').hide();
		return false;
	})

	$('#popup-signin-toggle').click(function () {
		$('#popup-signin').show();
		$('#popup-signin-toggle').hide();
		return false;
	})

});

function cancelChangeLocation() {
    $('#city-select-content').slideUp(300);
    $('#city-select').removeClass('city-select-open');
	$('#main').removeClass('hide-selects'); // class used in IE6 to hide selects due to z-index bug
}


// from Facebook plugin file fbconnect.js
if (typeof LocalDeal === 'undefined') {
	LocalDeal = {};
}

function FB_Init() {

	try {

		FB.init({
			appId: '233042913989',
			status: true,
			cookie: true,
			xfbml: true,
			channelUrl: window.location.protocol + '//' + document.domain + '/social/fbchannel.html'
		});
        FB.UIServer.setLoadedNode = function (a, b) { FB.UIServer._loadedNodes[a.id] = b; } // IE hack to correct FB bug
    } catch (e) {
		return null;
    }
    
}


function FB_Logout() {
	FB.logout(function () {
		window.document.location.href = '/logout/';
	});
	window.document.location.href = '/logout/';
}

function FB_Login(redirURL) {

	FB.login(function (response) {
		if (response.session) {
			FB_UpdateSignin(redirURL);
		} else {
			//alert('login cancelled');
			//FB.logout();
		}

	}, { perms: 'email' }

    );

}

function FB_UpdateSignin(redirURL) {

	var uid = FB_GetUid();

	FB.Data.waitOn([
      FB.Data.query("SELECT " + userAttrs.join(",") + " FROM user WHERE uid={0}", uid)
    ],
    function (results) {
    	FB_PostSignin(results, redirURL);
    }
    );

	//FB_GetUserInfoForSignin();
}

var userAttrs = [
    'first_name',
    'last_name',
    'email',
    'contact_email',
    'email_hashes',
    'proxied_email'
];


function FB_GetUid() {
	try {
		return FB.getSession().uid;
	} catch (e) {
		return null;
	}
}

function FB_GetFBUserParams(results) {
	var user = results[0][0];

	var sendObject = {
		first_name: user.first_name,
		last_name: user.last_name,
		email: user.email,
		contact_email: user.contact_email,
		proxied_email: user.proxied_email,
		uid: user.uid
	};

	return sendObject;
}

function FB_PostSignin(results, redirURL) {

    var userInfo = FB_GetFBUserParams(results);

    var data = "{fbUserInfo:{ first_name:'" + userInfo.first_name + "', last_name:'" + userInfo.last_name + "', email:'" + userInfo.email + "', contact_email:'" + userInfo.contact_email + "', proxied_email:'" + userInfo.proxied_email + "', uid:'" + userInfo.uid + "' }}";

    $.ajax({
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        url: window.LDService + "LoginFromFB",
        data: data,
    	success: function (o) {
    		if (o != null) {
    			//0=loggedin
    			//1=Did not log into facebook
    			if (o.d == 0) {
    				if (redirURL == undefined || redirURL == null)
    					window.location.href = '/';
    				else
    					window.location.href = unescape(redirURL);
    			}
    			else if (o.d == 1) {
    				FB_Logout();
    			}
    			else if (o.d == 2) {
    				jQuery.facebox(function ($) {
    					jQuery().unbind('closeExtra.facebox');
    					jQuery.get("/social/content/mergeaccounts.htm?v=1.0", function (data) {
    						jQuery.facebox.settings.modal = false;
    						jQuery.facebox(data);
    						document.getElementById('mergeemail').value = userInfo['email'];

    						jQuery().bind('closeExtra.facebox', function () {
    							window.location.reload();
    						});
    					});
    				});
    			}
    		}
    		else {
    		}
    	},
    	error: onCommonError
    });
}

LocalDeal.Application = function () {
	var loggedIn = false;
	var connectedWithFacebook = false;

	return {
		setLoggedIn: function () {
			loggedIn = true;
		},
		isLoggedIn: function () {
			return loggedIn;
		},
		setConnectedWithFacebook: function () {
			connectedWithFacebook = true;
		},
		isConnectedWithFacebook: function () {
			return connectedWithFacebook;
		},
		logOut: function () {
			window.location.href = "/logout";
		},
		reloadPage: function () {
			window.location.reload(true);
		}

	};
} ();

/* Cookies */
function setCookie(name, value, days) { if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); var expires = "; expires=" + date.toGMTString(); } else var expires = ""; document.cookie = name + "=" + value + expires + "; path=/"; } 
function getCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') c = c.substring(1, c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length); } return null; } 
function deleteCookie(name) { setCookie(name, "", -1); }


function typeOf(value) {
    var s = typeof value; 
    if (s === 'object') {
        if (value) {
            if (typeof value.length === 'number' &&
                !(value.propertyIsEnumerable('length')) && typeof value.splice === 'function') {
                s = 'array';
            }
        } else {
            s = 'null';
        }
    } 
    return s;
}

function submitChangeLocation() {

    var entered = $('#changeLocation').val();

    //validation
    if (entered.length < 1) {
       $('#changeloc-error').html('Please enter a location.');
       return false;
    }

    if (usertemplocation.label.length < 1 || usertemplocation.lat.length < 1 || usertemplocation.lon.length < 1) {
        //$('#lblErrorMessage').html('The location is invalid. Please enter a valid location.').addClass('error-msg').show();
        $('#changeloc-error').html('Location is invalid. Please select from the suggested locations.');
        return false;
    }

    var data = "{ label:'" + usertemplocation.label + "', lat:'" + usertemplocation.lat + "', lon:'" + usertemplocation.lon + "' }";
    $.ajax({
        type: "POST",
        data: data,
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        url: window.LDService + "ChangeLocation",
        success: function (o) {
            if (o != null && o.d != null && o.d != '-1') {
                window.location.href = "/" + o.d;
            } else {
                $('#changeloc-error').html('The location is invalid. Please enter a valid location.');
                return false;
            }
        },
        error: function (request, textStatus, errorThrown) {
            if (request != null && request.responseText != null) {
                try {
                    var err = eval("(" + request.responseText + ")");
                    $('#changeloc-error').html(err.Message);
                    return false;
                } catch (err) { }

                $('#changeloc-error').html('The location is invalid. Please enter a valid location.');
                return false;
            }
        }
    });
}

function setLocationAsDefault(loggedin) {
    var entered = $('#changeLocation').val();

    //validation
    //if (entered.length < 1) {
    //   alert('you need to enter data');
    //}

    if (userlocation.label.length < 1 || userlocation.lat.length < 1 || userlocation.lon.length < 1) {
        $('#lblErrorMessage').html('The location is invalid. Please enter a valid location.').addClass('error-msg').show();
        return;
    }

    var data = "{ label:'" + userlocation.label + "', lat:'" + userlocation.lat + "', lon:'" + userlocation.lon + "' }";
    $.ajax({
        type: "POST",
        data: data,
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        url: window.LDService + "SetLocationAsDefault",
        success: function (o) {
            if (o != null && o.d != null && o.d != '-1') {
                window.location.href = window.location.href;
                //window.location.href = "/" + o.d;
            } else {
                $('#lblErrorMessage').html('The location is invalid. Please enter a valid location.').addClass('error-msg').show();
            }
        },
        error: function (request, textStatus, errorThrown) {
            if (request != null && request.responseText != null) {
                try {
                    var err = eval("(" + request.responseText + ")");
                    $('#lblErrorMessage').html(err.Message).addClass('error-msg').show();
                    return;
                } catch (err) { }

                $('#lblErrorMessage').html('The location is invalid. Please enter a valid location.').addClass('error-msg').show();
            }
        }
    });
}

function displayAllGuides() {

    $('.guide-h').removeClass();
    $('#guideall-link').hide();
}

$(document).ready(function () {
    $('#txtLDSearch').keypress(function (e) {
        var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
        if (key == 13) {
            e.preventDefault();
            searchLocalDeal();
            return false;
        }
    });
});

function searchLocalDeal() {
    window.document.location.href = '/search/?q=' + encodeURI($('#txtLDSearch').val()) + '&citytag=' + userlocation.ctag;
}

/*
* jQuery UI Autocomplete Select First Extension
*
* Copyright 2010, Scott González (http://scottgonzalez.com)
* Dual licensed under the MIT or GPL Version 2 licenses.
*
* http://github.com/scottgonzalez/jquery-ui-extensions
*/
(function( $ ) {

    $( ".ui-autocomplete-input" ).live( "autocompleteopen", function() {
    var autocomplete = $( this ).data( "autocomplete" ),
    menu = autocomplete.menu;

    if ( !autocomplete.options.selectFirst ) {
    return;
    }

    menu.activate( $.Event({ type: "mouseenter" }), menu.element.children().first() );
    });

}( jQuery ));

