﻿var $E = $E || YAHOO.util.Event;

Function.prototype.curry = function() {
	if (!arguments.length) return this;
	var __method = this, args = Array.prototype.slice.apply(arguments);
	return function() {
		return __method.apply(this, args.concat(Array.prototype.slice.apply(arguments)));
	}
}



YAHOO.util.Dom.show = function(el) {
	YAHOO.util.Dom.setStyle(el, "display", "");
};
YAHOO.util.Dom.hide = function(el) {
	YAHOO.util.Dom.setStyle(el, "display", "none");
};



String.prototype.trim = function(){
    return this.replace(/^\s*(\S+(\s+\S+)*)\s*$/, "$1");
}

String.prototype.supplant = function(o){
	return this.replace(/{([^{}]*)}/g,
		function(a, b){
			var r = o[b];
			return typeof r === "string" ? r : a;
		}
	);
};

String.prototype.supplantScalar = function(o){
	return this.replace(/{([^{}]*)}/g,
		function(a, b){
			var r = o[b];
			return typeof r === "string" || typeof r === "number" ? r : a;
		}
	);
};

String.prototype.supplantAdvanced = function(o, formatNumbers){
	var getValue = function(hash, key) {
		var m = /^([^\.]*)\.(.*)/.exec(key);
		if (m != null && m.length > 2 && hash[m[1]]) {
			return getValue(hash[m[1]], m[2]);
		} else {
			return hash[key];
		}
	}
	var f = function(a, b){
		var r = getValue(o, b);
		if (typeof r === "string") { 
			return r; 
		} else if (typeof r === "number") { 
			return formatNumbers ? r.toLocaleString() : r; 
		} else return a;
		//return typeof r === "string" || typeof r === "number" ? r : a;
	}
	return this.replace(/{([^{}]*)}/g, f);
};

Number.prototype.formatDk = function() {
	var s = String(this);
	var res = "";
	var regex = /[\d]{3}$/;
	while (regex.test(s)) {
		res = "." + s.substring(s.length-3) + res;
		s = s.substring(0, s.length-3);
	}
	res = s + res;
	if (res.length > 0 && res.charAt(0) == '.') {
		res = res.substring(1);
	}
	return res;
};

// Debug stuff
// if (document.craeteEventObject)
//    console = {log:function(){}};

function adjustImagePopup(type, img) {
    //console.log('type: ' + type);
    // Images are locked to 200x133 px
    // Padding in container is ~(r+1) * 4 px
    // Height of container becomes roughly: r * 200 + (r + 1)  * 4 = 204 * r + 4
    // Thumbnail images are locked to 80x55 px
    if (!type) {
        // Ref. to image container
        var con = document.getElementById('imageHolderDiv');
        // Ref. to popup container
        var popup = con.parentNode.parentNode;
        // Number of rows (1 or 2)
        var r = con.getAttribute('rel') * 1;
        // Get height of container
        var h = r < 3 ? 143 : 280;
    }
    else if (type == 'map') {
        var h = 433;
        var popup = document.getElementById('tipDiv');
    }
    else if (type == 'plan') {
        // Ref. to image container
        var con = document.getElementById('imageHolderDiv');
        // Ref. to popup container
        //var popup = con.parentNode.parentNode;
        // Number of rows (1 or 2)
        var r = con.getAttribute('rel') * 1;
        //console.log('r: ' + r);
        // Get height of container
        var h = r < 3 ? 210 : 414;
        var popup = document.getElementById('tipDiv');
    }
    // y-coord. of image popup
    var y = parseFloat(popup.style.top);
    //console.log('y: ' + y);
    // Height of viewport
    var vh = window.innerHeight != undefined ? window.innerHeight : document.documentElement.clientHeight;
    // Test condition for whether to adjust or not
    //console.log('condition: ' + vh + ' + ' + document.documentElement.scrollTop + ' < ' + h + ' + ' + y);
    //console.log('condition: ' + (vh + document.documentElement.scrollTop) + ' < ' + (h + y));
    if (vh + document.documentElement.scrollTop < h + y) {
        popup.style.top = y - h + 55 + 'px';
        //console.log('y: ' + y + ', h: ' + h);
   }
   //console.log(type + ': tipDiv positioned at: ' + popup.style.top);
}

function elementize(html) {
	var d = document.createElement("div");
	d.innerHTML = html;
	var res = [];
	for (var i = 0; i < d.childNodes.length; i++) {
		res.push(d.childNodes[i]);
	}
	return res;
}

// Tracking Events and XHR with GA
function track(e) {
    // Fail silently - log error in GA
    try {
        // If IE
        if (!e || !e.target) {
	        e = event;
	        e.target = e.srcElement;
	        e.preventDefault =
	            function() {
	                e.returnValue = false;
	                return false;
	            };
        }
        // Only log on main click left)
        if (e.type == 'click' && e.button !== 0)
            return;
        // If key event only track on enter
        if (e.type == 'keyup' && e.keyCode != 13)
            return;
        
        // First handle the normal tracking:
        // Assume no target
        var target = null;
        // If node or parent node have class which we are listening for
        if (/gaT(P|E)/.test(e.target.className))
            target = e.target;
	    else if (/gaT(P|E)/.test(e.target.parentNode.className))
	        target = e.target.parentNode;
	    // If we have a target track page/event
	    if (target) {
	        var m = target.className.match(/gaT(P|E)(\S+)/);
	        // If page track
	        if (m[1] == 'P') {
	            // Prefix with first folder
	            var path = location.pathname.replace(/(.*\/).*/,'$1');
	            pageTracker._trackPageview(path + m[2]);
	        }
	        // else track event
	        else {
	            // Get type / label
	            var evt = m[2].split('$');
	            // Log first folder (ie. /privat) as label to the event
	            var path = location.pathname.replace(/(.*\/).*/,'$1');
	            pageTracker._trackEvent('Valtech', evt[0], path);
	            //console.log('trackEvent', 'Valtech', evt[0], evt[1]);
	        }
	    }
	    
	    if (window.__trackECommerce != null) {
			// Now repeat and check for additional eCommerce tracking:
			// Assume no target
			var target = null;
			// If node or parent node have class which we are listening for
			if (/gaTC/.test(e.target.className))
				target = e.target;
			else if (/gaTC/.test(e.target.parentNode.className))
				target = e.target.parentNode;
			// If we have a target track page/event
			if (target) {
				var m = target.className.match(/gaTC(\S+)/);
				// See of we need to do the eCommerce tracking
				if (m && window.__trackECommerce != null) {
					__trackECommerce(m[1]);
				}
			}
	    }

	}
	catch(err) {
	    pageTracker._trackEvent('Valtech', 'TrackError', 'UA: ' + navigator.userAgent + ' Error: ' + err.message);
	    //console.log('trackEvent', 'Valtech', 'TrackError', 'UA: ' + navigator.userAgent + ' Error: ' + err.message);
	}
}

// Mini console for IE
function createConsole() {
    div = document.createElement('div');
    div.style.borderTop = '1px solid #000';
    div.style.padding = '4px';
    div.style.background = '#fff';
    div.style.overflow = 'auto';
    div.style.position = 'fixed';
    div.style.left = 0;
    div.style.bottom = 0;
    div.style.width = '100%';
    div.style.height = '100px';
    div.log =
        function() {
            var args = Array.prototype.slice.call(arguments);
            div.innerHTML += args + '<br/>';
        };
    window.console = div;
    document.body.appendChild(div);
    document.body.style.marginBottom = '101px';
}

// If IE
if (document.createEventObject) {
    //window.attachEvent('onload', createConsole);
    window.attachEvent('onload',
        function() {
            document.body.attachEvent('onclick', track);
            document.body.attachEvent('onkeyup', track);
        }
    );
}
// not IE
else {
    document.addEventListener('click', track, true);
    document.addEventListener('keyup', track, true);
}

// Define the trackECommerce function
function __trackECommerce(type) {

	// We need the page tracker and the nescessay data to be present. If they aren't do nothing
	if (pageTracker && Danbolig.currentPropertyId && Danbolig.currentBrokerId && Danbolig.currentPropertyTypeId) {
		// start by calculating a "guid" to identify the transaction.
		var guid, i, j;
		guid = '';
		for(j=0; j<32; j++)
		{
			if( j == 8 || j == 12|| j == 16|| j == 20)
			guid = guid + '-';
			i = Math.floor(Math.random()*16).toString(16).toUpperCase();
			guid = guid + i;
		}

		var itemName = 'PID-' + Danbolig.currentPropertyId;
		var category = type.toUpperCase() + '-BID-' + Danbolig.currentBrokerId + '--PT-' + Danbolig.currentPropertyTypeId;
		pageTracker._addTrans(guid, 'DanBolig', '1.0', '', '', '', '', '');
		pageTracker._addItem(guid, Danbolig.currentPropertyId.toString(), itemName, category, '1.0', '1');
		pageTracker._trackTrans();
		
	}
}
