/**
    @filename template.js
    @author kgifford@perfectsensedigital.com

	This file contains basic js functionality for the site that is independant of themes
*/


/*	---------------------------
			NAVIGATION
	---------------------------
	Controls the dropdown navigation menus. */
var nav = {
    init: function() {
        var path = location.pathname;
        if(path == "/") path = "/index";
        if(path.indexOf("blog") > -1) path="/blog.html"
        $("#main-nav a[href=" + path + "]").closest("li").addClass("selected");
		var oNav = document.getElementById("main-nav");
		var tabs = $('.tab', oNav);
		for (var i = 0, tLen = tabs.length; i < tLen; i++) {
			sn = $('.sub-nav', tabs[i]);
			if (sn && sn.length > 0) {
				tabs[i].onmouseover = function() {
                        try {
                            $('.sub-nav', this)[0].style.display = "block";
                        } catch(err) {}
                }
				tabs[i].onmouseout = function() {
                        try {
                            $('.sub-nav', this)[0].style.display = "none";
                        } catch(err) {}
                }
			}
		}
    },

    createCareGuidesDropdown: function(response) {
        var div = $("<div class=\"nav sub-nav\"></div>");
        var ul = $("<ul></ul>");
        for(var i in response) {
            if(response[i] > 0) {
                var li = $("<li><a href=\"/care_guide.html?type=" + i + "\">" + i + "</a></li>");
                $(ul).append(li);
            }
        }
        $(div).append(ul);
        return $(div)[0];
    },

    createServicesDropdown: function(items) {
        var div = $("<div class=\"nav sub-nav\"></div>");
        var ul = $("<ul></ul>");
        var maxItems = 10, itemTrack = 0;;
        var fn = function() {
            document.getElementById("serviceDescription").innerHTML = services.svc[this.getAttribute("data-uuid")];
            document.getElementById("servicesHeader").innerHTML = this.getElementsByTagName("a")[0].innerHTML;
            services.updateCMS(this.getAttribute("data-uuid"));
        };
        items = items._sortBy("service").reverse();
        for(var i = 0, len = items.length; i < len; i++) {
            if(!items[i].enabled) continue;
            var li = $("<li data-uuid=\"" + items[i].id + "\"><a href=\"/services.html#" + items[i].id + "\">" + items[i].service + "</a></li>");
            if(location.pathname.indexOf("/services.html") > -1) {
                li[0].onclick = fn;
            }
            $(ul).append(li);
            itemTrack++;
            if(itemTrack == maxItems) break;
        }
        $(ul).append("<li>&nbsp;</li><li><a href=\"/services.html\">See all ...</a></li>");
        $(div).append(ul);
        return $(div)[0];
    },

    careGuidesCallback: function(response) {
        if(response.status == "Ok") {
            var menu = nav.createCareGuidesDropdown(response.result);
            $("#main-nav a[href=/care_guide.html]").closest("li").append(menu);
        } else {

        }
    },

    servicesCallback: function(response) {
        if(response.status == "Ok") {
            var menu = nav.createServicesDropdown(response.result.items);
            $("#main-nav a[href=/services.html]").closest("li").append(menu);
        } else {

        }
    },

    update: function() {
        $(".nav.sub-nav").remove();
        var s = $("<script src=\"/cms-lite/api/find?type=Service&l=11&callback=nav.servicesCallback\"></script>");
        $("head").append(s);

        s = $("<script src=\"/javascripts/animal-types.jsp\"></script>");
        $("head").append(s);
        nav.init();
    }
}


/*	---------------------------
			PET GALLERY
	---------------------------
	Randomly assigns a rotation class to the pictures in the pet gallery (not the memorial gallery).
	Adds validation to the upload photo form.
	Sets up the light boxes needed on the page. */

var pets = {
	rotateClass: ["rotate-3", "rotate-2", "rotate-1", "rotate0", "rotate1", "rotate2", "rotate3"],
	numClasses: 7,
	maxCharCount: 250,
	init: function() {
		// randomly rotate images on the pet galery page (not on the pet memorial page)
		var oPet = document.getElementById("pets");
		if (oPet) {
			var photos = $("#pets .figure");
			for (var i = 0, pLen = photos.length; i < pLen; i++) {
				photos[i].className += " " + pets.rotateClass[Math.floor(Math.random() * pets.numClasses)];
			}
		}
		var oForm = $('.upload-form');
		if (oForm && oForm.length > 0) {
			$(".upload-form .button").click( function(e) {
				e.preventDefault();
				var frm = $('.upload-form')[0];
				if (pets.doUploadValidation(frm)) {
					//TODO: Check out the submission once it has a place to go and figure out what to do next (Does the window close? Does messaging appear in the lightbox?)
					$(frm).submit();
				}
			});
			// Set up character counter
			pets.maxCharCount = $("#txt-counter span.num-char")[0].innerHTML;
			$('textarea').keyup( function() { pets.countCharacters(this); });
			pets.countCharacters($('textarea')[0]);		// To get initial count when the field is not empty
		}
		$(".btn-photo-upload").click( function() {
			lb.showBox($(".upload-form"));
		})
		$(".pets li").click( function() {
			pets.getPhoto();
			lb.showBox($(".gallery"));
		})
		// TODO: Hook up the previous and next buttons

	},
	countCharacters: function(o) {
		var charLength = $(o).val().length;
		$("#txt-counter span.num-char").html(pets.maxCharCount - charLength);
		(charLength > pets.maxCharCount) ? $("#txt-counter").addClass("char-error") : $("#txt-counter").removeClass("char-error");
	},
	doUploadValidation: function(frm) {
		var fields = $('.required', frm);
		var fVal = "";
		var blnSubmit = true;
		for (i = 0, fLen = fields.length; i < fLen; i++) {
			field = fields[i];
			fVal = $("input", field).val();
			if (fVal || fVal=="") {
				fVal = fVal.trim();
				// check for blank
				if (fVal == "") {
					blnSubmit = pets.addErrorClass(field);
				} else {
					// TODO: Check Calendar after figuring out what to implement
					$(field).removeClass("error");
				}
			} else {
				// do other checks
				fVal = $("textarea", field).val();
				if (fVal == "") {
					blnSubmit = pets.addErrorClass(field);
				} else if (fVal.length > pets.maxCharCount) {
					blnSubmit = pets.addErrorClass(field);
				} else {
					$(field).removeClass("error");
				}
			}
		}
		return blnSubmit;
	},
	addErrorClass: function(o) {
		$(o).addClass("error");
		return false;
	},
	getPhoto: function() {
		// TODO: Need to call to get the photo and additional information.


	}
}

var vetsuite = {
    updateYears: function() {
        var ele = psd.util.dom.getElementsByClassName(document.body,"yearBegan");
        var inService = "";
        for(var i = 0, len = ele.length; i < len; i++) {
            var dt = ele[i].getAttribute("datetime");
            if(dt) {
                var yearBegan = new Date(dt).getFullYear();
                var thisYear = new Date().getFullYear();
                inService = thisYear - yearBegan;
                if(inService < 1) inService = 1;
            } else {
                ele[i].setAttribute("datetime",new Date("Sun Apr 07 3011 12:00:00"));
                inService = "";
            }
            try {
                ele[i].innerHTML = inService;
            } catch(err) {}
        }
    },

    updateStaffData: function() {
        var dl = psd.util.dom.getElementsByClassName(document.body,"credentials");
        for(var i = 0; i < dl.length; i++) {
            var children = dl[i].getElementsByTagName("*");
            for(var j = 0; j < children.length; j++) {
                if(children[j].nodeName.toLowerCase() != "dd") continue;
                if(psd.util.dom.getText(children[j]) != "") {
                    $(children[j]).closest("span").show();
                } else {
                    $(children[j]).closest("span").hide();
                }
            }
        }
    },
    mailCallback: function(response) {
        if(response.status == "Ok") {
            $("#contact")[0].reset();
            alert("Thank you for your message!");
        } else {
            alert(response.message);
        }
    }
};

$(document).ready( function() {
	nav.init();
	pets.init();
    vetsuite.updateYears();
    vetsuite.updateStaffData();
});
