var swm_channel = $.cookie('swm_channel');
var popular = $.cookie('popular');
var related = $.cookie('related');
var mappit;
var alertTimerId = 0;
var counterId = 0;

$(document).ready(function() {

    if ($("select.organisation").val() == "Other") {
        $(".organisation-option").show();
    } else {
        $(".organisation-option").hide();
    }

    $("select.organisation").change(function() {

        if ($(this).val() == "Other") {
            $(".organisation-option").show();
        } else {
            $(".organisation-option").hide();
        }

    });

    if ($("select.sector").val() == "Other") {
        $(".sector-option").show();
    } else {
        $(".sector-option").hide();
    }


    $("select.sector").change(function() {

        if ($(this).val() == "Other") {
            $(".sector-option").show();
        } else {
            $(".sector-option").hide();
        }

    });

    if ($("select.contacts").val() == "Other") {
        $(".contacts-option").show();
    } else {
        $(".contacts-option").hide();
    }

    $("select.contacts").change(function() {

        if ($(this).val() == "Other") {
            $(".contacts-option").show();
        } else {
            $(".contacts-option").hide();
        }

    });



    $('fieldset.press_login,fieldset.contact').attr("onkeypress", "javascript:return CustomWebForm_FireDefaultButton(event, 'tak_PageBody_btn_submit')");
    $('fieldset.the_comments').attr("onkeypress", "javascript:return Ajax_CustomWebForm_FireDefaultButton(event, 'tak_PageBody_btn_submit')");
    $('div.search').attr("onkeypress", "javascript:return CustomWebForm_FireDefaultButton(event, 'tak_search_btn')");

    // Events/Channel dropdown select
    if ($("ul.cat").length > 0) {
        var uri = window.location.href;
        uri = uri.replace("http://", "");
        uri = uri.replace("https://", "");
        uri = uri.split('/');
        var url = null;

        // Events
        if (uri[1] == "events" && uri.length >= 4) {
            url = "/" + uri[1] + "/" + uri[2] + "/" + uri[3] + "/" + uri[4] + "/";
            $("ul#categories li a").each(function() {
                if ($(this).attr("href") == url) {
                    var value = $(this).html();
                    $("ul#categories li a.first").html(value);
                }
            });
            // Channel
        } else if (uri[1] == "swm_channel" && uri.length >= 2) {
            url = "/" + uri[1] + "/" + uri[2] + "/";
            $("ul#categories li a").each(function() {
                if ($(this).attr("href") == url) {
                    var value = $(this).html();
                    $("ul#categories li a.first").html(value);
                }
            });
        }

    }

    // News Comments
    $("input.cmnt_click").unbind();
    $("input.cmnt_click").click(function() {

        var Name = $("#tak_PageBody_txtName").val();
        var Email = $("#tak_PageBody_txtEmail").val();
        var Comment = $("#tak_PageBody_txtComment").val();
        var Check = 0;

        $("#tak_PageBody_txtRemember:checkbox").each(function() {
            if (this.checked) {
                Check = 1;
            }
        });

        var NewsID = $("fieldset").attr("id").replace("form_", "");
        var eID = $("dl").attr("rel");

        if (eID == null) {
            eID = 0;
        }

        $.ajax({
            type: "POST",
            url: myAjaxPath,
            data: '{"Name":"' + Name + '","Email":"' + Email + '","Comment":"' + escape(Comment) + '","NewsID":' + NewsID + ',"eID":' + eID + ',"Check":' + Check + '}',
            beforeSend: function(xhr) {
                xhr.setRequestHeader("X-AjaxPro-Method", "GetPosted");
            },
            success: function(response) {

                //alert(response);

                var o = null;
                eval("o = " + response + ";");

                var detail;
                var id;
                var count;
                var xmlobject = "";

                if (o.value != null) {
                    if (document.implementation.createDocument) {
                        // Mozilla, create a new DOMParser 
                        var parser = new DOMParser();
                        xmlobject = parser.parseFromString(o.value, "text/xml");
                    } else if (window.ActiveXObject) {
                        // Internet Explorer, create a new XML document using ActiveX 
                        // and use loadXML as a DOM parser. 
                        xmlobject = new ActiveXObject("Microsoft.XMLDOM")
                        xmlobject.async = "false";
                        xmlobject.loadXML(o.value);
                    }
                    //xmlobject = (new DOMParser()).parseFromString(o.value, "text/xml");
                }

                $(xmlobject).find("response").each(function() {
                    detail = $(this).find("detail").text();
                    id = $(this).find("id").text();
                    count = $(this).find("count").text();
                    count++;
                });

                if (detail == "OK") {

                    //if(count == 1)
                    //{
                    //	$("h3.header").html(count + " comment");
                    //}else{
                    //	$("h3.header").html(count + " comments");
                    //}

                    $("h3.header").attr("style", "");
                    $("a.comment").attr("style", "");

                    $("div.edit").remove();

                    var html = "<div class='citem edit'><div class='detail'>" +
									"<p class='cname'>By " + Name + "</p>" +
									"<p class='cdate'>Today</p>" +
									"</div>" +
									"<div class='text'>" +
									"<p>" + Comment + "</p>" +
									"</div></div>";

                    $("dl").attr("style", "display:none;");

                    $("div.comments").append(html);

                    startTimer();

                    //$("div.edit").unbind();
                    //$("div.edit").click(function() {
                    $("h3.timer").unbind();
                    $("h3.timer").click(function() {
                        clearTimeout(alertTimerId);
                        clearTimeout(counterId);
                        $("dl").attr("style", "");
                        $("dl").attr("rel", id);
                        $("h3.timer").html("Please update your comment...");
                    });

                }
                else if (detail == "FAILED") {

                    alert("Your comment could not be posted, please check the content and ensure if any, only basic HTML is used");
                }
                else {
                    alert("All fields are required, please check you have entered a valid email address");
                }

            }
        });

        return false;

    });

    // init the tooltip
    tooltip();

    // All form elements
    $("img.zoom").unbind();
    $("img.zoom").click(
        function() {
            var imgdetail = $(this).attr("id");
            imgdetail = imgdetail.replace("wrapper_", "");
            var t = null;
            var a = '/imagezoom.axd?id=' + imgdetail;
            var g = '1';
            tb_show(t, a, g);
        }
    );

    // All form elements
    $("input:not(.btn),textarea,select").focus(
        function() {
            $(this).attr("style", "border:1px solid #00ffff;");
        }
    );

    $("input:not(.btn),textarea,select").blur(
        function() {
            $(this).attr("style", "");
        }
    );

    // Search events
    $("div.search input.search").focus(
        function() {
            if ($(this).val() == "Search Screen WM") {
                $(this).val("");
                //$(this).attr("style","border:1px solid #00ffff;");
            }
            $("div.search input.btn").attr("src", "/app_images/search_btn_over.gif");

        }
    );

    $("div.search input.search").blur(
        function() {
            if ($(this).val() == "") {
                $(this).val("Search Screen WM");
                //$(this).attr("style","");
            }
            $("div.search input.btn").attr("src", "/app_images/search_btn.gif");
        }
    );

    // Calednar events
    $("a.event").hover(
        function() {
            var c = $(this).attr("rel");
            $("div.calendar table a." + c).addClass("over");
        },
        function() {
            var c = $(this).attr("rel");
            $("div.calendar table a." + c).removeClass("over");
        }
    );

    // Category dropdown
    $("ul#categories li a").unbind();
    $("ul#categories li a").click(
        function() {
            var value = $(this).html();
            $("ul#categories li a.first").html(value);
            if ($("ul#categories li").attr("class") == "sfHover") {
                $("ul#categories li").removeClass("sfHover");
            } else {
                $("ul#categories li").addClass("sfHover");
            }
        }
    );

    // Check if related (open|closed)
    if (related == 'collapsed') {
        $("ul.related").addClass("hide");
        $("ul.related").children('li:not(.heading)').slideUp();
        $("ul.related").removeClass("hide");
        $("ul.related").addClass("closed");
    };

    // Check if popular (open|closed)
    if (popular == 'collapsed') {
        $("ul.popular").addClass("hide");
        $("ul.popular").children('li:not(.heading)').slideUp();
        $("ul.popular").removeClass("hide");
        $("ul.popular").addClass("closed");
    };

    // Check if swm channel (open|closed)
    if (swm_channel == 'collapsed') {
        $("ul.swm_channel").addClass("hide");
        $("ul.swm_channel").children('li:not(.heading)').slideUp();
        $("ul.swm_channel").removeClass("hide");
        $("ul.swm_channel").addClass("closed");
    };

    // SWM Channel (open|close)
    $("ul.swm_channel li.heading").click(

		function() {
		    var me = $(this).parent();

		    if ($(me).attr("class") == 'swm_channel') {
		        $(me).children('li:not(.heading)').slideUp();
		        $(me).addClass("closed");
		        $.cookie('swm_channel', 'collapsed', { expires: 7, path: '/' });

		    } else {
		        $(me).children('li:not(.heading)').slideDown();
		        $(me).removeClass("closed");
		        $.cookie('swm_channel', 'expanded', { expires: 7, path: '/' });
		    }
		}

    );

    // Popular (open|close)
    $("ul.popular li.heading").click(

		function() {
		    var me = $(this).parent();

		    if ($(me).attr("class") == 'popular') {
		        $(me).children('li:not(.heading)').slideUp();
		        $(me).addClass("closed");
		        $.cookie('popular', 'collapsed', { expires: 7, path: '/' });
		    } else {
		        $(me).children('li:not(.heading)').slideDown();
		        $(me).removeClass("closed");
		        $.cookie('popular', 'expanded', { expires: 7, path: '/' });
		    }
		}

    );

    // Related (open|close)
    $("ul.related li.heading").click(

		function() {
		    var me = $(this).parent();

		    if ($(me).attr("class") == 'related') {
		        $(me).children('li:not(.heading)').slideUp();
		        $(me).addClass("closed");
		        $.cookie('related', 'collapsed', { expires: 7, path: '/' });
		    } else {
		        $(me).children('li:not(.heading)').slideDown();
		        $(me).removeClass("closed");
		        $.cookie('related', 'expanded', { expires: 7, path: '/' });
		    }
		}

    );

    // All form elements
    $("a.map").unbind();
    $("a.map").click(
        function() {

            var postcode = $(this).attr("title");
            mapped = $(this).attr("rel");
            mappit = mapped;

            $("div." + mapped).slideToggle(1, function() {

                if (GBrowserIsCompatible()) {
                    mappit = new GMap2(document.getElementById(mapped));
                    mappit.addControl(new GLargeMapControl());
                    mappit.setCenter(new GLatLng(54.622978, -2.592773), 14, G_PHYSICAL_MAP);
                }

                usePointFromPostcode(postcode, setPointer);
                //usePointFromPostcode(postcode, placeMarkerAtPoint);

            });

        });

});

// Calendar tool tip function
this.tooltip = function() {

    var hoverTimer = 0;
    var width = 0;
    var height = 0;
    var xOffset = 0;
    var yOffset = 0;

    $("a.tooltip").hover(function(e) {

        this.t = this.rel.replace("cal_", "info_");

        $("body").append("<p id='tooltip'><span class='top'>" + $("div#" + this.t).html() + "</span></p>");

        //alert($("div#" + this.t).html());

        width = $("div#" + this.t).width();
        height = $("div#" + this.t).height();
        xOffset = height + 20;
        yOffset = -(width / 2) + 5;

        if (height < 50) {
            $("p#tooltip span.top").css("background", "#000");
        }

        hoverTimer = setTimeout('$("#tooltip").fadeIn("fast", function(e) {  });', 750);

    }, function() {

        clearTimeout(hoverTimer);
        $("#tooltip").remove();

    }).mousemove(function(e) {

        width = $("div#" + this.t).width();
        height = $("div#" + this.t).height();
        xOffset = height + 20;
        yOffset = -(width / 2) + 5;

        if (height < 50) {
            $("p#tooltip span.top").css("background", "#000");
        }

        $("#tooltip").css("top", (e.pageY - xOffset) + "px").css("left", (e.pageX + yOffset) + "px");

    });

};

// Email check
/*function emailCheck(emailStr) {
    var emailPat = /^(.+)@(.+)$/;
    var specialChars = "\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
    var validChars = "\[^\\s" + specialChars + "\]";
    var quotedUser = "(\"[^\"]*\")";
    var ipDomainPat = /^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
    var atom = validChars + '+';
    var word = "(" + atom + "|" + quotedUser + ")";
    var userPat = new RegExp("^" + word + "(\\." + word + ")*$");
    var domainPat = new RegExp("^" + atom + "(\\." + atom + ")*$");
    var matchArray = emailStr.match(emailPat);
    if (matchArray == null) { return false; }
    var user = matchArray[1];
    var domain = matchArray[2];
    if (user.match(userPat) == null) { return false; }
    var IPArray = domain.match(ipDomainPat);
    if (IPArray != null) { for (var i = 1; i <= 4; i++) { if (IPArray[i] > 255) { return false; } } return true; }
    var domainArray = domain.match(domainPat);
    if (domainArray == null) { return false; }
    var atomPat = new RegExp(atom, "g");
    var domArr = domain.match(atomPat);
    var len = domArr.length;
    if (domArr[domArr.length - 1].length < 2 || domArr[domArr.length - 1].length > 3) { return false; }
    if (len < 2) { return false; } return true;
}*/

function emailCheck(email){
   	/*var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
   	if (filter.test(email)) {
   		return true;
   	}*/
   	return true;
}

function usePointFromPostcode(postcode, callbackFunction) {
    localSearch.setSearchCompleteCallback(null, function() {
        if (localSearch.results[0]) {
            var resultLat = localSearch.results[0].lat;
            var resultLng = localSearch.results[0].lng;
            var point = new GLatLng(resultLat, resultLng);
            callbackFunction(point);
        }
    });
    localSearch.execute(postcode + ", UK");
}

function setPointer(point) {
    mappit.setCenter(point, 14);
    var marker = new GMarker(point);
    mappit.addOverlay(marker);
}

function startTimer() {
    alertTimerId = setTimeout('resetTimer()', 60000);
    updateCounter('60');
}

function resetTimer() {
    clearTimeout(alertTimerId);
    clearTimeout(counterId);
    $("#tak_PageBody_txtName").val("");
    $("#tak_PageBody_txtEmail").val("");
    $("#tak_PageBody_txtComment").val("");
    $("dl").attr("rel", 0);
    $("dl").attr("style", "");
    //$("div.edit").removeClass("edit");
    $("div.edit").remove();
    $("h3.timer").html("Add to the discussion leave a comment");
}

function updateCounter(count) {
    count = count - 1;
    $('h3.timer').html("Thank you. " + count + " seconds to review your comment &ndash; click here to edit. Your comment will go live once it has been reviewed.");
    counterId = setTimeout('updateCounter(\'' + count + '\')', 1000);
}


function CustomWebForm_FireDefaultButton(event, target) {
    var __defaultFired = false;
    var element = event.target || event.srcElement;
    if (!__defaultFired && event.keyCode == 13 && !(element && (element.tagName.toLowerCase() == "textarea"))) {
        var defaultButton;
        if (__nonMSDOMBrowser) {
            defaultButton = document.getElementById(target);
        } else {
            defaultButton = document.all[target];
        }

        if (defaultButton && typeof (defaultButton.click) != "undefined") {
            __defaultFired = true;
            defaultButton.click();
            event.cancelBubble = true;
            if (event.stopPropagation) event.stopPropagation();
            return false;
        }

    }
    return true;
}

function Ajax_CustomWebForm_FireDefaultButton(event, target) {
    var __defaultFired = false;
    var element = event.target || event.srcElement;
    if (!__defaultFired && event.keyCode == 13 && !(element && (element.tagName.toLowerCase() == "textarea"))) {
        return false;
    } else {
        return true;
    }
}