// -- string trim function
String.prototype.trim = function () {
	return this.replace(/[\s\0\n\t\r\f\v]+/g," ").replace(/(^\s*|\s*$)/g,"");
};

// -- validate forms 

Fat.validate(".pageForm", "a.arrowBtn, .styledBtn");
// -- MSIE 6.0 & 7.0

var ie7 = /MSIE 7.0/g.test(navigator.userAgent),
ie6 = /MSIE 6.0/g.test(navigator.userAgent),
docMode = document.documentMode ? document.documentMode.toString() : "",
classAttr = "class";
if(docMode == "7" || docMode == "5") {
	classAttr = "className";
} else if(docMode == "") {
	classAttr = (ie7 || ie6) ? "className" : "class";
};

// -- convert XML to JS

var jsObjFromXML = function(xml) {
	var obj = {},
	children = xml.children || xml.childNodes,
	len = children.length,
	i = 0,
	idx = 0;
	while(i<len) {
		var child = children[i],
		prop = {},
		propName = child.nodeName;
		if(child.nodeName != "#text" && child.nodeName != "#comment" && child.nodeName != "xml") {
			if(obj[propName]) { propName += (i+1) };
			obj[propName] = {};
			var subChildren = child.children || child.childNodes,
			atts = child.attributes, aI = atts.length;
			if(subChildren.length == 0) {
				obj[propName].nodeText = child.textContent || child.text;
			} else if(subChildren.length == 1 && subChildren[0].nodeName == "#text"){
				obj[propName].nodeText = subChildren[0].textContent || subChildren[0].text;
			} else {
				obj[propName].children = jsObjFromXML(child);
			};
			if(aI > 0) {
			    while(aI--) {
			        var att = atts[aI];
			        obj[propName][att.name] = att.value;
			    };
			};
			idx++;
		};
		i++;
	};	 
	return obj;
};

// -- placeholder attributes for those without

(function(placeholder) {
	if(!placeholder) {
		$(document.forms).find('input').each(function() {
			var text = $(this).attr("placeholder");
			if(!!text && text != "" && this.value == "") {
				this.value = text;
				this.onfocus = function(){
					if(this.value == text) { this.value = '' };
				};
				this.onblur = function(){
					if(this.value == '') { this.value = text };
				};
			};
		});
	};
})((Modernizr && Modernizr.input.placeholder) || false);

// -- highlight first para 

(function(div) {
    if(div) {
        var paras = div.getElementsByTagName("p"),
        p = paras[0] || null;
        p && p.setAttribute(classAttr,"firstPara");
    };
})(document.getElementById("cmsContent"));


// -- further page banner rotation

(function(banner){
    if(banner) {
        var imgs = banner.getElementsByTagName("img"),
        i = imgs.length;
        if(i > 0) {
            banner.setAttribute(classAttr,"headerRotator");
            var curImg = 0,
            showImg = function(i) {
                if(i > imgs.length-1) { i = 0 };
                $(imgs[curImg]).stop().animate({"opacity": 0},function(){
                    this.style.display = "none"
                });
                $(imgs[i]).stop().css("display","block").animate({"opacity": 1});
                curImg = i;
                setTimeout(function(){
                    showImg(curImg+1);
                },5000);
            };
            showImg(0);
        };
    };
    
})(document.getElementById("headerBanner"));

// -- tabbed sections

(function(sections){
    sections.each(function(){
        var $sect = $(this),
        links = $sect.find(".tabLink"),
        tabs = $sect.find(".tab");
        links.each(function(i){
            this.onclick = function() {
                tabs.css("display","none");
                tabs[i].style.display = "block";
                links.removeClass("on");
                $(links[i]).addClass("on");
            };
        });
        links[0] && links[0].onclick();
    });
})($(".tabbed"));

// -- twitter feed

$("#twitter").twitter({
    screenNames: "C2Cleanrooms",
    display: "box",
    date: "difference"
});

// -- faqs section

(function(wrap){
    
    if(wrap) {
    
        var faqs = $(wrap).find(".faq"), len = faqs.length, i = 0,
        answers = [];
        
        while(i < len) {
            var faq = $(faqs[i]),
            answer = faq.find(".answer")[0], btn = faq.find("h3")[0], height = answer.clientHeight;
            answer.style.height = "0px";
            answer.opened = false;
            answers.push(answer);
            btn.targetHeight = height;
            btn.clickIdx = i;
            btn.onclick = function(){
                var theAnswer = answers[this.clickIdx],
                theHeight = theAnswer.opened ? 0 : this.targetHeight;
                $(theAnswer).stop().animate({"height":theHeight});
                theAnswer.opened = !theAnswer.opened;
            };
            i++;
        };
    
    };

})(document.getElementById("faqs"));

// -- testimonials cta 

(function(div){
    if(div) {
        div.innerHTML = "<strong>Loading testimonials...</strong>";
        var tArr = [],
        curT = 0,
        maxHeight = 0,
        showTestim = function(i) {
            if(i >= tArr.length) { i = 0 };
            $(tArr[curT]).stop().animate({"opacity":0});
            $(tArr[i]).stop().animate({"opacity":1});
            curT = i;
            setTimeout(function(){
                showTestim(i+1);
            },5000);
        },
        setTestims = function(data){
            for(var x in data) {
                var t = data[x].children,
                elmHeight,
                elm = document.createElement("div");
                elm.setAttribute(classAttr,"testim");
                elm.innerHTML = "<p>" + t.Text.nodeText + "</p>";
                elm.innerHTML += "<em>" + t.Name.nodeText + " - " + t.Location.nodeText + "</em>";
                div.appendChild(elm);
                elmHeight = elm.clientHeight;
                maxHeight = elmHeight > maxHeight ? elmHeight : maxHeight;
                tArr.push(elm);
            };
            div.style.height = maxHeight + "px";
            showTestim(0);
        },
        x = $.ajax({
            type: 'GET',
            url: '/XML/Testimonials.aspx',
            dataType: 'xml',
            success: function(data) {
                var jsData = jsObjFromXML(data.documentElement);
                div.innerHTML = "";
                setTestims(jsData);
            },
            error: function(e){window.ajaxResponseError = e;}
        });
    };
})(document.getElementById("testimonials"));


/* industry sectors page */

(function(wrap){

    if(wrap) {
        $(window).load(function(){
            var sectors = $(wrap).find(".sector").each(function(){
                var title = this.getElementsByTagName("h3")[0],
                $this = $(this),
                origHeight = this.clientHeight,
                closedHeight = classAttr === "class" ? 40 : 25,
                isOpen = false,
                titleHTML = title.innerHTML;
                title.innerHTML = titleHTML + "<span class='sectorTip'>View &raquo;</span>";
                this.style.height = closedHeight + "px";
                if(title) {
                    title.onclick = function(){
                        $this.stop().animate({
                            "height": (isOpen ? closedHeight : origHeight)
                        });
                        this.setAttribute(classAttr,isOpen ? "open" : "shut");
                        this.innerHTML = titleHTML + "<span class='sectorTip'>" + (isOpen ? "View " : "Hide ") + "&raquo;</span>"
                        isOpen = !isOpen;
                    };
                };
            });
        });
    };

})(document.getElementById("cmsContent"));


// -- livechat buttons
(function(){
    window.$zopim || (function (d, s) {
        var z = $zopim = function (c) { z._.push(c) }, $ =
    z.s = d.createElement(s), e = d.getElementsByTagName(s)[0]; z.set = function (o
    ) { z.set._.push(o) }; $.setAttribute('charset', 'utf-8'); $.async = !0; z.set.
    _ = []; $.src = ('https:' == d.location.protocol ? 'https://ssl' : 'http://cdn') +
    '.zopim.com/?vrD0v1MybyTGuagZooNSOeCzs1F0Jsjq'; $.type = 'text/java' + s; z.
    t = +new Date; z._ = []; e.parentNode.insertBefore($, e)
    })(document, 'script');


    var zopimglink = $(".zopIM");


    (function (zim) {
        if (zim) {
            zim.each(function () {
                var img = this.getElementsByTagName("img")[0];
                this.onclick = function () {
                    $zopim.livechat.window.toggle();
                    return false;
                };
                $zopim(function () {
                    $zopim.livechat.setOnStatus(changeImg);
                    $zopim.livechat.window.hide();
                });
                function changeImg(status) {
                    if (img) {
                        img.src = '/images/liveSupport-' + status + '.png';
                    };
                };
            });
        };
    })($(zopimglink));
})();

// -- hide contact btn on contact page

(function(contact, btn) {
    if(btn && (window.location.pathname === "/contact-us" || contact)) {
        btn.style.display = "none";
    };    
})(document.getElementById("contactForm"),document.getElementById("mainContactBtn"));



(function(mapElem) {

    if(!mapElem) return;

    var mapAtPoint = function (lat,lng) { 
        var latlng = new google.maps.LatLng(lat, lng),
        myOptions = { zoom: 11, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP },
        map = new google.maps.Map(mapElem, myOptions),
        marker = new google.maps.Marker({ position: latlng, map: map, title:"Connect 2 Cleanrooms Head Office" }),
        infowindow = new google.maps.InfoWindow({ content: "Connect 2 Cleanrooms Head Office<br/>Unit 2 Kirkby Lonsdale Business Park<br/>Kirkby Lonsdale<br/> Cumbria<br/> LA6 2HH" });
        google.maps.event.addListener(marker, 'click', function() { infowindow.open(map,marker); });
    }

    mapAtPoint(54.20362, -2.616377);

})(document.getElementById("map_canvas"));
