﻿// trim bad characters from string 
String.prototype.makeSafe = function() {
    var theText = this;
    theText = theText.replace(/<.+?>/g, "")
    return theText.replace(/[\.,#!$%\^&\*;:{}=\-_`'~"]/g, "-");
}

// replace spaces
String.prototype.replaceSpace = function(replaceChar) {
    var theText = this;
    return theText.replace(/\s+/g, replaceChar)
}

// -- string trim function
String.prototype.trim = function() {
    return this.replace(/[\s\0\n\t\r\f\v]+/g, " ").replace(/(^\s*|\s*$)/g, "");
};

// -- form validations


if ($(".pageForm").length > 0) {


    $(".pageForm").fatValidate();

}

// -- 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";
};

// -- 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);

// -- other locations DD

(function(btn) {
    if (btn) {
        btn.onclick = function() {
            var array = (function() {
                var tmpArr = ["Glasgow", "Leeds", "London-City-EC1", "Gracechurch-St", "Lloyds-Avenue", "London-Greenwich", "London-Marylebone", "Chancery-Place", "Milton-Keynes", "Watford"], i = 0, j = tmpArr.length;
                while (i < j) {
                    if (!!window.location.pathname.match(new RegExp(tmpArr[i]))) {
                        tmpArr.splice(i, 1); break;
                    };
                    i++;
                };
                return tmpArr;
            })(),
            select = document.createElement("select"),
            i = 0, j = array.length;
            select.appendChild((function() {
                var opt = document.createElement("option");
                opt.innerHTML = "Select a location...";
                return opt;
            })());
            while (i < j) {
                var option = document.createElement("option");
                option.value = array[i];

                option.innerHTML = array[i].replace("-", " ");
                select.appendChild(option);
                i++;
            };
            select.onchange = function() {
                window.location = "/" + this.value + "/Serviced-Offices";
            };
            $(this).after(select);
            this.style.display = "none";
            return false;
        };
    };
})(document.getElementById("otherLocationsBtn"));

// -- callback request dropdown

(function(btn) {
    if (btn) {
        var dd = document.getElementById("callbackForm"),
        opened = false;
        btn.onclick = function() {
            var theHeight = opened ? 0 : 206,
            theTop = opened ? 0 : 180;
            $(dd).stop().animate({ "height": theHeight }, function() {
                btn.style.backgroundImage = "url('/images/" + (opened ? "cbr-open" : "cbr") + ".png')";
            });
            $(btn).stop().animate({ "top": theTop });
            opened = !opened;
        };
    };
})(document.getElementById("headerCallback"));

// -- 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"));

// -- 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") {
            propName = child.nodeName + (idx + 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;
};


// -- replace select dropdown with styled ul
(function(selects){ if(selects.length < 1) return;
	var lineheight = 34,
	Fat = {
	    make: function (str) {
	        return document.createElement(str);
	    },
	    getParent: function(elm) {
		    var parent = elm.parentNode;
		    while ( parent.nodeType !== 1 )  parent = parent.parentNode;
		    return parent;
	    }
	},
	replaceElem = function(select){
		var options = select.getElementsByTagName("option"),
		fake_options = [],
		i = -1, j = options.length,
		opt,
		opened = false,
		prev_text = options[0].innerHTML,
		ul = Fat.make("ul"),
		dom_placeholder = Fat.make("div"),
		frag = document.createDocumentFragment();
		dom_placeholder.className = "select-holder";
		ul.className = "fake-select";
		ul.style.height = lineheight + "px";
		ul.onclick = function(){
			opened = !opened;
			this.style.height = (opened ? lineheight*options.length : lineheight) + "px";
			this.style.zIndex = ( opened ? "10003" : "10002" );
			this.className = "fake-select " + (opened ? "open" : "closed");
			if(opened) {
				setTimeout(function() {
					document.onclick = function(){
						ul.onclick();
					};
				},1);
			} else  document.onclick = null;
		};
		while ( ++i < j ) {
			opt = Fat.make("li");
			opt.innerHTML = options[i].innerHTML;
			opt.setAttribute("data-opt-value",options[i].value);
			opt.setAttribute("data-opt-index",i);
			opt.onclick = function(e){
				if(opened) {
					var idx = this.getAttribute("data-opt-index"),
					evt = e || window.event;
					options[select.selectedIndex].setAttribute("selected","false");
					select.selectedIndex = idx;
					options[idx].setAttribute("selected","true");
					prev_text = fake_options[0].innerHTML
					evt.stopPropagation && evt.stopPropagation();
					evt.cancelBubble = true;
					ul.onclick();
					if (idx !="0") select.onchange && select.onchange();
				}
			};
			fake_options.push(opt);
			frag.appendChild(opt);
		};
		ul.appendChild(frag);
		dom_placeholder.appendChild(ul);
		Fat.getParent(select).insertBefore(dom_placeholder,select);
		select.style.display = "none";
	},
	i = selects.length;
	while ( i -- ) selects[i].className.match(/select-replace/gi) && replaceElem(selects[i]);
})(document.getElementsByTagName("select"));


