// -- ie6 and 7
var IE6 = /MSIE 6.0/g.test(navigator.userAgent),
IE7 = /MSIE 7.0/g.test(navigator.userAgent),
classType = (IE6 || IE7) ? "className" : "class";
// -- navigation dropdown function
(function(){
   var target, oldTarget, navOpen, visible, animHeight;
    $("#nav > li a").click(function(){
        var me = $(this).parent();
        var dd = me.find("ul");
        if(dd.length > 0) {      
            target = me.attr("id");
            if(target == oldTarget && navOpen) {
                visible = "hidden";
                navHeight = 126;
                navOpen = false;
            } else {
                me.siblings().find("ul").css("visibility","hidden");
                dd.css("visibility","visible");
                navOpen = true;
                visible = "visible";
                navHeight = dd.outerHeight() + 126;
            };
            $("#header").stop().animate({
                "height" : navHeight
            },function(){
                dd.css("visibility",visible);
            });
            oldTarget = me.attr("id");
            return false;
        };
    });
})();

function isArray(obj) {
    return obj.constructor == Array;
}

// -- social network tooltips

(function(output){
	$(".socialBtn").hover(function(){
		output.innerHTML = $(this).html();
	},function(){
		output.innerHTML = '';
	});
})(document.getElementById("socialTip"));

// -- equal height columns

(function(lCol,rCol){
	if(lCol && rCol) {
		if(lCol.offsetHeight > rCol.offsetHeight) {rCol.style.height = (lCol.offsetHeight - 20) + "px"}
		else {lCol.style.height = (rCol.offsetHeight - 20) + "px"};
	};
})(document.getElementById("leftCol"),document.getElementById("rightCol"));

// -- placeholder attributes for those without

(function(placeholder) {
	if(!placeholder) {
		$(document.forms).find('input').each(function() {
			var me = $(this),
			text = me.attr("placeholder");
			if(!!text) {
				me.val(text).css({"color":"#999"});
				me.focus(function(){
					if(me.val() == text) me.val('').removeAttr("style");
				});
				me.blur(function(){
					if(me.val() == '') me.val(text).css({"color":"#999"});
				});
			};
		});
	};
})(typeof Modernizr !== "undefined" ? Modernizr.input.placeholder : true);

// -- tooltip constructor

function Tooltip(html,parent) {
	this.html = html;
	this.parentElement = parent;
	this.elem = document.createElement("div");
	this.elem.setAttribute(classType,"tooltip");
	this.visible = false;
	this.html = html;
	var tip = new Image();
	tip.src = "images/tooltip.png";
	tip.setAttribute(classType,"tipImg");
	this.show = function(x,y){
		if(typeof this.html !== 'undefined' && this.html !== '') {
			if(this.parentElement.jquery) this.parentElement.append(this.elem)
			else this.parentElement.appendChild(this.elem);
			this.elem.innerHTML = this.html;
			this.elem.appendChild(tip);
			var width = this.elem.offsetWidth,
			height = this.elem.offsetHeight,
			posX = x-(width + 20), posY = y-(height/2);
			if(posY < 0) posY = 0;
			if(posX < 0) posX = 0;
			if(posY + width > document.body.offsetWidth) posY = document.body.offsetWidth - width;
			this.elem.style.top =  posY + "px";
			this.elem.style.left = posX + "px";
			this.visible = true;
			$(this.elem).stop().animate({"opacity":1},150);
		};
	};
	this.remove = function(){
		if(this.visible) {
			var me = this;
			$(me.elem).stop().animate({"opacity":0},150,function(){
				if(me.parentElement.jquery) $(me.elem).remove()
				else me.parentElement.removeChild(me.elem);
			});
			this.visible = false;
		};
	};
};


// -- filter dropdown
(function (div) {
    var btn = document.getElementById("filterBy"),
	expanded = false,
	divHeight = $(div).height() - 24;

    if (btn != undefined) {
        btn.onclick = function () {
            expanded ? $(div).slideUp() : $(div).slideDown();
            expanded ? $(btn).animate({ "top": "-45px" }) : $(btn).animate({ "top": +divHeight + "px" });
            expanded = !expanded;
        };
    };
    // -- bind the links to the session control
    $("#filters .projects ul li a").click( function() {
        FilterChange($(this).siblings("input.hidSelChosen").val(), 'project', $(this).siblings("input.hidSelUID").val());
    });

    $("#filters .categories ul li a").click( function() {
        FilterChange($(this).siblings("input.hidSelChosen").val(), 'category', $(this).siblings("input.hidSelUID").val());
    });
    
})(document.getElementById("filters"));


function FilterChange(fltSwitch, fltType,fltUID)
{
    var serviceURL = "/Services/WDS.asmx/";

    var b = false;

    if (fltSwitch == "false")
        b = true;

    if (b)
        serviceURL += "FilterAdd";
    else
        serviceURL += "FilterRemove";

    var o = new Object();
		var objArray = new Array(1);				
        o = $.ajax({
            type: "POST",
            url: serviceURL,
            data: "{ FType: '" + fltType + "', UID: " + fltUID + " }",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
		    error: function(msg,status,err){

		    },
            success: function(msg) {
			    
            }
        });
}

function ClearFilter()
{
    var o = $.ajax({
        type: "POST",
        url: "/Services/WDS.asmx/ClearFilters",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        error: function (msg, status, err) {

        },
        success: function (msg) {
            document.location.reload();
        }
    });

}

function commentSubmission() {

    $(".reply").click(function () {

        $(".reply").each(function () {

            var TreplyRoot = $(this).parents(".comment").children("#addComment");

            if (!TreplyRoot.hasClass("hidden")) {
                TreplyRoot.addClass("hidden");
                TreplyRoot.children("textarea.addComment").val("");
                TreplyRoot.children("textarea.addComment").height("12px");
            }
        });

        var replyRoot = $(this).parents(".comment").children("#addComment");

        replyRoot.removeClass("hidden");
        replyRoot.children("textarea.addComment").val("@" + $(this).siblings(".comLeftCol").children("strong").text() + ": ");
        replyRoot.children("textarea.addComment").height("125px");

    });

//    $(".subComm").colorbox({ width: 550, height: 350, inline: true, href: "#contactForm", onOpen: function () {
//        var newValue = $(this).siblings("textarea.addComment");
//         $("#commCred .chosenComment").val(newValue.val());
//        }
//    });

    $(".subComm").click(function () {

        var p = $(this);
        var allow = true;

        var comSel = "textarea.addComment";
        var emaSel = "input.commentEmail";
        var namSel = "input.commentName";
        var homSel = "input.commentUrl";
        var repSel = "input.replyUID";

        // -- reset
        p.parents(".comment").find(comSel).css("border-color", "#D1D1D1")
        p.parents(".comment").find(emaSel).css("border-color", "#D1D1D1")
        p.parents(".comment").find(namSel).css("border-color", "#D1D1D1")

        if ($("input.docTitle").val() == undefined || $("input.docTitle").val() == "")
            allow = false;

        if (p.siblings(comSel).val().length < 20) {
            allow = false;
            p.parents(".comment").find(comSel).css("border-color", "#DC3819");
        }

        if (p.parents(".comment").find(emaSel).val().length < 2 || p.parents(".comment").find(emaSel).val() == p.parents(".comment").find(emaSel).attr("placeholder")) {
            allow = false;
            p.parents(".comment").find(emaSel).css("border-color", "#DC3819");
        }

        if (p.parents(".comment").find(namSel).val().length < 2 || p.parents(".comment").find(namSel).val() == p.parents(".comment").find(namSel).attr("placeholder")) {
            allow = false;
            p.parents(".comment").find(namSel).css("border-color", "#DC3819");
        }

        

        if (allow) {

            $(p).append("<span id='ajaxLoad'></span>");

            var hom = p.parents(".comment").find(homSel).val();
            if (hom == p.parents(".comment").find(homSel).attr("placeholder"))
            {
                hom = "";
            }   

            SubmitComment($("input.docTitle").val(), p.siblings(comSel).val(), p.parents(".comment").find(emaSel).val(), p.parents(".comment").find(namSel).val(), hom, p.parents(".comment").find(repSel).val());
        }

    });

    $(".addComment").focus(function () {
        $(this).height("125px");
    });

    $(".addComment").blur(function () {
        $(this).height("12px");
    });
}

function SubmitComment(title, message, email, name, homepage, replyid) {

    message = escapeCharacters(message);

    if (homepage.length > 5)
    {
        message = message + "<br/><br/>" + homepage;
    }

    var o = $.ajax({
        type: "POST",
        url: "/Services/WDS.asmx/SubmitComment",
        data: "{ URLTitle:'" + title + "', Message:'" + message + "', Email:'" + email + "', Name:'" + name + "', rtu: " + replyid + " }",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        error: function (msg, status, err) {
            $("#ajaxLoad").remove();
        },
        success: function (msg) {
            $.colorbox({ width: 450, height: 200, opacity: 0.2, html: "<div style='margin:20px;'><h1>Thank you!</h1><p>Your comment has been submitted.</p></div>" });
            $("#ajaxLoad").remove();
        }
    });

    

}


function escapeCharacters(str) {
    str = str.replace(/\"/g, escape("\"")).replace(/\'/g, escape("\""));
    return str;
}

function trimSpaces(str) {
    str = str.replace(/\s{3,}/g, "").replace(/\t/g, "");
    return str;
}

function SEOTextReplacement(fieldFrom, fieldTo) {

    var fieldArray = fieldFrom.split("|");

    for (var j = 0; j < fieldArray.length; j++) {

        $(fieldArray[j]).blur(function () {

            var fields = fieldFrom.split("|");
            var origValue = "";

            for (var i = 0; i < fields.length; i++) {
                origValue += $(fields[i]).val() + " ";
            }

            origValue = origValue.substring(0, origValue.length-1)

            var punctuationless = origValue.replace(/\W/g, "-");
            var finalString = punctuationless.replace(/\s{1,100}/g, "-");
            finalString = finalString.replace(/-{2,100}/g, "-");

            $(fieldTo).val(finalString);

        });    
    }

}

function CopyFieldContentLengthLimit(content, fieldTo, limit) {
        if (content.length == 0) {
            content = "";
        }
        
        if (content.length >= limit && limit != 0) {
            content = content.substring(0, limit);
        } else {
            content = content;
        }

        $(fieldTo).val(content);
}
