/* 
	Use this function instead of $.load
	This turns off caching of pages and politely waits until the page is loaded
*/
function load_into_div(div, url) {
	var content = load_val(url);
        $(div).html(content);
}

function load_val(url) { 
        var content = $.ajax({
                url: url, 
                cache: false,
                async: false
        }).responseText;
	return content;
}


$ = jQuery;
$(document).ready(function() {
	
	$("#header .menu-header ul#menu-main_navigation li").hover(function() {
		var children = $(this).children("ul.sub-menu:first");

		if (children.length > 0) {
			children.stop(true, true).slideDown(250);
		}
	}, function() {
		var children = $(this).children("ul.sub-menu:first");

		if (children.length > 0) {
			children.stop(true, true).slideUp(125);
		}
	});

	
	
	$("#question-email-us").click(function() {
		window.location = '/contact/';
	});
	$("#submit-contact-form").click(function() {
		var full_name = $("#full-name").val();
		var email = $("#email").val();
		var url = $("#url").val();
		var phone = $("#phone").val();	
		var comment = $("#comment").val();
		var submit_url = "/wp-content/themes/imagefreedom/contact_form.php?" +
				"full_name="+encodeURIComponent(full_name) + "&" +
				"email=" + encodeURIComponent(email) + "&" + 
				"url=" + encodeURIComponent(url) + "&" + 
				"phone=" + encodeURIComponent(phone) + "&" + 
				"comment="+ encodeURIComponent(comment);
		var results = load_val(submit_url);
		if (results != "true") {
			if ($("#request-form-error").length <= 0) {
				$("#contact-form").append('<div id="request-form-error">'+results+'</div>');
				$("#request-form-error").slideDown(250);
			} else { 
				$("#request-form-error").hide();
				$("#request-form-error").html(results);
				$("#request-form-error").slideDown(250);
			}
		} else { 
			$("#contact-form").html("<p>Your comment has been received. Someone will get back with you within three business days.</p>");
		}
	});

	$("#submit-request").click(function() {
		var full_name = $("#full-name").val();
		var email = $("#email").val();
		var url = $("#url").val();
		var phone = $("#phone").val();	
		var submit_url = "/wp-content/themes/imagefreedom/request_consultation.php?" +
				"full_name="+encodeURIComponent(full_name) + "&" +
				"email=" + encodeURIComponent(email) + "&" + 
				"url=" + encodeURIComponent(url) + "&" + 
				"phone=" + encodeURIComponent(phone);
		var results = load_val(submit_url);
		if (results != "true") {
			if ($("#request-form-error").length <= 0) {
				$("#contact-form").append('<div id="request-form-error">'+results+'</div>');
				$("#request-form-error").slideDown(250);
			} else { 
				$("#request-form-error").hide();
				$("#request-form-error").html(results);
				$("#request-form-error").slideDown(250);
			}
		} else { 
			$("#contact-form").html("<p>Your consultation request has been received. Someone will get back with you within three business days.</p>");
		}
	});
	if ($(".socialnav.fixed").length > 0) {
		var minTop = $(".socialnav.fixed").offset().top;
		var myHeight = $(".socialnav.fixed").height();
		//var maxTop = $("#wp-content .right").height() - $(".socialnav.fixed").height();
		$(document).scroll(function() {
			
			var rightTop;
			if ($("#wp-content .right").length > 0) { 
				rightTop = $("#wp-content .right").offset().top;
			} else { 
				rightTop = $("#content .right").offset().top;
			} 
			var maxTop = rightTop + $("#wp-content .right").height() - myHeight;
			var scrollTop = $(window).scrollTop();
			var height = $(window).height();
			/*
			if ($("pos").length <= 0)
				$("body").append('<div id="pos" style="position: fixed; top: 25px; left: 0px;"></div>');
			$("#pos").html("scrollTop: " + scrollTop + "\tminTop: " + minTop + "\tmaxTop: "+maxTop+"<br />\n");
			*/
			if (scrollTop < minTop) {
				$(".socialnav.fixed").css({top: minTop - scrollTop});
			} else if (scrollTop> maxTop) {
				$(".socialnav.fixed").css({top: maxTop - scrollTop});
			} else {
				$(".socialnav.fixed").css({top: "10px"});
			}			        
		});

	}
	
	$("#seo-form #url").before('<span class="protocol">http://</span>');
	$("#seo-form #url").val($("#meta-preview .url").html());
	var current_title = $("#meta-preview .link a").html();
	var current_description = $("#meta-preview .description").html();
	if (current_title) { current_title = current_title.replace("&amp;", "&"); } else { current_title = ""; }
	if (current_description) { current_description = current_description.replace("&amp;", "&"); } else { current_description = ""; }
	$("#seo-form #title").val(current_title);
	$("#seo-form #description").val(current_description);
	$("#title-limit").html("(<strong>"+current_title.length+"</strong> / <strong>70</strong> characters)");
	$("#description-limit").html("(<strong>"+current_description.length+"</strong> / <strong>156</strong> characters)");
	
	$("#meta-preview .link a").click(function() {
		return false;
	});
	
	// SEO Meta Tool
	$("#seo-form #url").change(url_change);
	$("#seo-form #url").keyup(url_change);
	$("#seo-form #url").live('paste', url_change);

	// SEO Meta Tool
	$("#seo-form #title").change(title_change);
	$("#seo-form #title").keyup(title_change);
	$("#seo-form #title").live('paste', title_change);
	
	// SEO Meta Tool
	$("#seo-form #description").change(description_change);
	$("#seo-form #description").keyup(description_change);
	$("#seo-form #description").live('paste', description_change);
	
	$("#seo-form #fetch-current").click(fetch_current);
});

function fetch_current() {
	try { 
		var results = load_val("/wp-content/themes/imagefreedom/fetch_meta.php?url="+encodeURIComponent("http://"+$("#url").val()));
		var obj = jQuery.parseJSON(results);
		console.log(encodeURIComponent("http://"+$("#url").val()) + "\t"+ obj.title + "\t" + obj.description + "\n");
		if (obj) {
			$("#seo-form #description").val(obj.description);
			$("#seo-form #title").val(obj.title);
			url_change();
			title_change();
			description_change();
		}
	} catch (ex) { 
		console.log(ex);
	}
	
}


function url_change(event) {
	if (event && event.keyCode && event.keyCode == 13) { 
		fetch_current();
	} else { 
		var url = $("#url").val();
		url = url.replace('http://', '');
		url = url.replace('https://', '');
		$("#meta-preview .url").html(url);
	}
	
}

function description_change(event) {
	var current_description = $("#description").val();
	var len = current_description.length;
	if (len > 156) { 
		$("#description-limit").attr("class", "over");
	} else { 
		$("#description-limit").removeAttr("class");
	}
	
	$("#meta-preview .description").html(htmlspecialchars_decode(current_description.substring(0,156), 'ENT_QUOTES').replace("<","&lt;"));
	$("#description-limit").html("(<strong>" + current_description.length + "</strong> / <strong>156</strong> characters)");
}

function title_change(event) {
	var current_title = $("#title").val();
	var len = current_title.length;
	if (len > 70) { 
		$("#title-limit").attr("class", "over");
	} else { 
		$("#title-limit").removeAttr("class");
	}
	
	$("#meta-preview .link a").html(htmlspecialchars_decode(current_title.substring(0,70), 'ENT_QUOTES').replace("<","&lt;"));
	$("#title-limit").html("(<strong>" + current_title.length + "</strong> / <strong>70</strong> characters)");
}


function htmlspecialchars_decode (string, quote_style) {
    // Convert special HTML entities back to characters  
    // 
    // version: 1103.1210
    // discuss at: http://phpjs.org/functions/htmlspecialchars_decode
    // +   original by: Mirek Slugen
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Mateusz "loonquawl" Zalega
    // +      input by: ReverseSyntax
    // +      input by: Slawomir Kaniecki
    // +      input by: Scott Cariss
    // +      input by: Francois
    // +   bugfixed by: Onno Marsman
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Ratheous
    // +      input by: Mailfaker (http://www.weedem.fr/)
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: htmlspecialchars_decode("<p>this -&gt; &quot;</p>", 'ENT_NOQUOTES');
    // *     returns 1: '<p>this -> &quot;</p>'
    // *     example 2: htmlspecialchars_decode("&amp;quot;");
    // *     returns 2: '&quot;'
    var optTemp = 0,
        i = 0,
        noquotes = false;
    if (typeof quote_style === 'undefined') {
        quote_style = 2;
    }
    string = string.toString().replace(/&lt;/g, '<').replace(/&gt;/g, '>');
    var OPTS = {
        'ENT_NOQUOTES': 0,
        'ENT_HTML_QUOTE_SINGLE': 1,
        'ENT_HTML_QUOTE_DOUBLE': 2,
        'ENT_COMPAT': 2,
        'ENT_QUOTES': 3,
        'ENT_IGNORE': 4
    };
    if (quote_style === 0) {
        noquotes = true;
    }
    if (typeof quote_style !== 'number') { // Allow for a single string or an array of string flags
        quote_style = [].concat(quote_style);
        for (i = 0; i < quote_style.length; i++) {
            // Resolve string input to bitwise e.g. 'PATHINFO_EXTENSION' becomes 4
            if (OPTS[quote_style[i]] === 0) {
                noquotes = true;
            } else if (OPTS[quote_style[i]]) {
                optTemp = optTemp | OPTS[quote_style[i]];
            }
        }
        quote_style = optTemp;
    }
    if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) {
        string = string.replace(/&#0*39;/g, "'"); // PHP doesn't currently escape if more than one 0, but it should
        // string = string.replace(/&apos;|&#x0*27;/g, "'"); // This would also be useful here, but not a part of PHP
    }
    if (!noquotes) {
        string = string.replace(/&quot;/g, '"');
    }
    // Put this in last place to avoid escape being double-decoded
    string = string.replace(/&amp;/g, '&');
 
    return string;
}
