// legacy page init script 0.1.0
// requires lib.array, lib.cls, lib.elm, lib.evt
// 
// Launch sequence
//   1) run page.init immediately
//   2) run page.onDomReady after DOM is ready
//   3) run page.onLoad after everything is loaded and definitely after page.onDomReady

var page = page || {};




page.name = "page";
page.head = null; // link to page head
page.body = null; // link to page body
page.tagNames = ["tbody", "form", "table", "ul", "dl","div", "a", "span", "input", "textarea", "select", "img" ]; // tags that should be initialized

page.tags         = {}; // collection of page elements sorted by tagName
page.initByTag    = {}; // init functions by tag
page.classes      = {}; // collection of page elements sorted by className
page.initByClass  = {}; // init functions by className
page.initById     = {}; // init functions by id

page.images = { url:"", preload: [] }; // image related data

page._debug = false;
page._debugTimes = [];




page.initElement = function (elm) {
	// initializes the new element
	
	// init by tagName
	var tagName = elm.tagName.toLowerCase();
	if (typeof page.tags[tagName] == "undefined") {
		page.tags[tagName] = [];
	}
	lib.array.push(page.tags[tagName], elm); // collect elements for easy search
	if (typeof page.initByTag[tagName] == "function") {
		page.initByTag[tagName](elm);
	}
	if (elm.className) {
		// init by class
		// group by className
		var classNames = lib.cls.get(elm);
		for (var i = 0, l = classNames.length; i < l; i++) {
			var className = classNames[i];
			if (typeof page.classes[className] == "undefined") {
				page.classes[className] = [];
			}
			lib.array.push(page.classes[className], elm);
			if (typeof page.initByClass[className] == "function") {
				page.initByClass[className](elm);
			}
		} // endfor
	}
	if (elm.id && (typeof page.initById[elm.id] == "function")) {
		// init by id
		page.initById[elm.id](elm);
	}
	
	if (elm.title) {
		lib.tooltip.add(elm);
	}
	
	return true;
};




page.initByTag.form = function (formElm) {
	lib.showSwitch.initForm(formElm);
	return true;
};

page.initByTag.input = function (inputElm) {
	
	// add calendar icon and init calendar app for that icon
	if (lib.cls.has(inputElm, "date")) {
		var button = elm.button.create(elm.button.types.calendar);
		lib.cls.add(button, "trigger");
		
		var envelope = lib.elm.envelope(inputElm, {tagName:"span"});
		lib.cls.add(envelope, "anchor");
		lib.cls.add(button, "hangRight");
		envelope.appendChild(button);
		
		Calendar.setup({
			button:     button,
			inputField: inputElm,
			ifFormat       : Calendar.localFormat, // format of the input field
			align          : "bR",                 // alignment (defaults to "Bl")
			singleClick    : true,
			step           : 1                     // show all years in drop-down boxes (instead of every other year as default)
		});
	}
	
	return true;
};

page.initById.img_root = function (elm) {
	// read img root from the meta tag
	page.images.url = lib.elm.getAttribute(lib.elm.get(page.images.id), "content");
	return true;
};

page.initById.redirectUrl = function (elm) {
	var redirectUrlInput = elm;
	var processLink = function (elm, e, evId) {
		if (elm.href) {
			lib.elm.setValue(redirectUrlInput, elm.href);
			redirectUrlInput.form.submit();
			lib.evt.cancel(e);
		}
		return true;
	};
	var links = lib.elm.getByTag("a");
	var i, l;
	for (i = 0, l = links.length; i < l; i++) {
		if (links[i].href) {
			lib.evt.add(links[i], "click", processLink);
		}
	}
	var processSubmitBtn = function (elm, e, evtId) {
		lib.elm.setValue(redirectUrlInput, "");
	};
	var submits = lib.elm.getByTag("input");
	for (i = 0, l = submits.length; i < l; i++) {
		if (submits[i].type && ( (submits[i].type == "submit") || (submits[i].type == "image") ) ) {
			lib.evt.add(submits[i], "click", processSubmitBtn);
		}
	}
};

page.initById.WishEditorPage_editText = function (elm) {
	// cause this button to open wishEditor
	if (dmk.wishEditor) {
		lib.evt.add(elm, "click", dmk.wishEditor.editText);
	}
	return true;
};

page.initById.cartForm = function (formElm) {
	if (dmk.cartList) {
		dmk.cartList.init(formElm);
	}
	return true;
};

page.initById.paymentForm = function (formElm) {
	if (dmk.cartBilling) {
		dmk.cartBilling.init(formElm);
	}
	return true;
};

page.initById.introFlash = function (elm) {
	var link01 = lib.elm.get("introLink01");
	var link02 = lib.elm.get("introLink02");
	var link03 = lib.elm.get("introLink03");
	var intro = link01.parentNode;
	
	if (link01) {
		lib.evt.add(link01, "mouseover", function (elm, e) {
			lib.evt.cancel(e);
		});
	}
	if (link02) {
		lib.evt.add(link02, "mouseover", function (elm, e) {
			if (lib.data.get(link01, "href") === null) {
				lib.data.set(link01, "href", link01.href);
			}
			link01.href = link02.href;
			lib.cls.remove(intro, "introWishOnWishPromo");
			lib.cls.add(intro, "introEWishPromo");
			lib.evt.cancel(e);
		});
	}
	if (link03) {
		lib.evt.add(link03, "mouseover", function (elm, e) {
			link01.href = link03.href;
			lib.cls.remove(intro, "introEWishPromo");
			lib.cls.add(intro, "introWishOnWishPromo");
			lib.evt.cancel(e);
		});
	}
	
	lib.evt.add(document.body, "mouseover", function () {
		if (link03) { // ePrani
			link01.href = link02.href;
		} else { // Papirove prani
			link01.href = lib.data.get(link01, "href") || link01.href;
		}
		lib.cls.remove(intro, "introEWishPromo");
		lib.cls.remove(intro, "introWishOnWishPromo");
	});
	return true;
};

page.initByClass.pageForm = function (formElm) {
	
	var submitPageForm = function (linkElm, e) {
		var pageForm = lib.elm.getByClass("pageForm", null, "form")[0];
		if (pageForm.redirectUrl && linkElm.href && linkElm.href.lastIndexOf("#") + 1 != linkElm.href.length) {
			lib.elm.setValue(pageForm.redirectUrl, linkElm.href);
		}
		pageForm.submit();
		lib.evt.cancel(e);
		return true;
	};
	
	var links = lib.elm.getByTag("a");
	lib.array.apply(links, function (linkElm) { lib.evt.add(linkElm, "click", submitPageForm); } );
	
	return true;
};

page.createPulldownMenu = function () {
	// start creating the pulldown menu
	$("#menuL1 ul>li") 
		.append($('<div class="dmkEPraniMenuL2"></div>'))
		.each(function () {
			// find the proper data entry
			var data = menu.data;
			var href = $("a", this).attr("href");
			var i, l, index;
			for (i = 0, l = data.length; i < l; i++) {
				if (href.indexOf("/occasion/" + data[i].value) != -1) {
					index = i;
					break;
				}
			}
			// use the data entry to create the menu items
			var menuL2 = $(".dmkEPraniMenuL2", this);
			for (i = 0, l = data[index].items.length; i < l; i++) {
				menuL2.append(
					$('<div class="dmkEPraniMenuL2item"><a href ="' +
						menu.occasion.url + "/" +
						data[index].value + "/" + 
						data[index].items[i].value + '">' + 
						data[index].items[i].title +
						'</a></div>'
					)
				);
			}
			menuL2.css({
				"position": "absolute",
				"padding-top": "10px",
				"height": "auto"
			});
			menuL2.hide();
			$("a", menuL2).css({
				"padding-right": "10px"
			});
		});
	// pulldown menu has been created
	
	// add menu item toggle
	$("#menuL1 ul>li").hover(function () { // on mouse over
		$(".dmkEPraniMenuL2", this).slideDown(100);
	}, function () { // on mouse out
		$(".dmkEPraniMenuL2", this).slideUp(100);
	});
};






(function ($) {
	
	/**
	 * run this instantly
	 */	 	
	try { // this fixes the "image flickering" caching bug in MSIE 6 SP-1
		document.execCommand("BackgroundImageCache", false, true);
	} catch (e) {}

	
	/**
	 * this runs after the DOM has been loaded	
 	 */
	$(document).ready(function () {
	// test if function has been called. If it was, exit.
		if (arguments.callee.done) {
			return false;
		} else {
			arguments.callee.done = true;
		}

		// custom code start
		if (page._debug) {
			lib.array.push(page._debugTimes, {time: new Date().getTime(), message: "starting the page.onDomReady function"});
		}
		lib.log.init(); // start logging
		
		page.createPulldownMenu();
		
		page.head = lib.elm.getByTag("head")[0];
	
		// detect JS
		if ((typeof dmk != "undefined") && (typeof dmk.jsDetector == "string") && (dmk.jsDetector !== "")) {
			var jsDetector = lib.elm.create( {tagName: "script", type:"text/javascript", src: dmk.jsDetector} );
			page.head.appendChild(jsDetector);
		}
	
		page.body = lib.elm.getByTag("body")[0];
	
		// collect elements by tagName
		for (var i = 0, l = page.tagNames.length; i < l; i++) {
			var tagName = page.tagNames[i].toLowerCase();
			var elements = lib.elm.getByTag(tagName);
			
			// init every element collected
			lib.array.apply(elements, page.initElement);
		}
	
		// elements are initialized now
		
		if (page._debug) {
			lib.array.push(page._debugTimes, {time: new Date().getTime(), message: "ending the page.onDomReady function"});
		}
		// custom code end
		return true;
	});
	
	
	/**
	 * this runs after whole document has been loaded
	 * including all images etc.	 
	 */	 	
	$(window).load(function () {
	
		// test if function has been called. If it was, exit.
		if (arguments.callee.done) {
			return false;
		} else {
			arguments.callee.done = true;
		}
		// custom code start
		if (page._debug) {
			lib.array.push(page._debugTimes, {time: new Date().getTime(), message: "starting the onLoad function"});
		}
		
		if (typeof dmk != "undefined") {
			if (typeof dmk.ePrani != "undefined") {
				dmk.ePrani.init(); // initiate ePrani
			}
			if (typeof dmk.wishEditor != "undefined") {
				dmk.wishEditor.init();
			}
		}
		
		if (page._debug) {
			lib.array.push(page._debugTimes, {time: new Date().getTime(), message: "ending the onLoad function"});
			var report = "Performance report:\n";
			for (var i = 0, l = page._debugTimes.length; i < l; i++) {
				report += page._debugTimes[i].time - page._debugTimes[0].time + " - " + page._debugTimes[i].message + "\n";
			}
			lib.log.write(report, "info");
		}
		// custom code end
		return true;
	});
})(jQuery);

