function Core() {
}

String.prototype.multi_split = function (patterns) {
	var out = null;
	for (var i=0; i<patterns.length; i++) {
		if (!out || out == null) {
			var t_pat = this.split(patterns[i]);
			if (t_pat.length > 1) {
				out = t_pat;
			}
		} else {
			for (var x=0; x<out.length; x++) {
				var t_split = out[x].split(patterns[i]);
				if (t_split.length > 1) {
					out.splice(x,1);
					out = out.concat(t_split);
				}
			}
		}
	}
	return out;
}

Core.openPopupWindow = function Core_openPopupWindow (p_url, name, width, height) {
	var specs = 'scrollbars=yes'; 
	if(width != null && height != null) {
		var left = ((screen.width - width)/2 > 0) ? (screen.width - width)/2 : 0;
		var top = ((screen.height - height)/2 > 0) ? (screen.height - height)/2 : 0;
		specs = specs + ',width=' + width + ',height=' + height + ',top=' + top + ',left=' + left;
	}
	window.open(p_url, name, specs);
}

Core.escape = function Core_escape(data) {
	if (data != null && data != "" && data != 'undefined') {
		data = encodeURIComponent(data);
		return data;
	} else {
		return "";
	}
}

Core.unescape = function Core_unescape(data) {
	if (data != null && data != "" && data != 'undefined') {
		try {
			data = decodeURIComponent(data);
			return data;
		} catch(e) {
			try {
				data = decodeURI(data);
				Logger.log("incorrect bytecode in : " + data + " explain: " + e + "trying again ...");
				return data;
			} catch(e) {
				Logger.log("fatal error");
				return data;
			}
		}
	} else {
		return "";
	}
}

Core.location = document.location + '';

Core.redirectAfterTimeout = function(targetURL, timeout) {
	setTimeout('window.location="' + targetURL + '"', timeout);
}

Core.isStaging = function() {
	return (Core.location.indexOf(".staging.") > -1) ? 1 : 0;
}

Core.isDev = function() {
	return (Core.location.indexOf(".dev.") > -1) ? 1 : 0;
}

Core.isProduction = function() {
	return (Core.location.indexOf(".dev.") == -1 && Core.location.indexOf(".staging.") == -1) ? 1 : 0;
}

Core.getPort= function Core_getPort() {
	var port_pos = Core.location.indexOf(".com:");
	if (port_pos>0) {
      if ((Core.location.substr(port_pos + 5, 4)) == "80") {
         return "";
      } else {
         return ":" + Core.location.substr(port_pos + 5, 4);
      }
	} else {
		return "";
	}
}

Core.getDomainPrefix= function Core_getDomainPrefix() {
	if (Core.isDev()){
		return "dev." ;
	} else  if (Core.isStaging()) {
		return "staging.";
	} else {
		return "";
	}
}

Core.localizeURL= function Core_localizeURL(href) {
	var username = getCookie("username");
	var dev_username =  getCookie("dev_username");
	var port = Core.getPort();
	var dom_prefix = Core.getDomainPrefix();

	if (dom_prefix) {
		href = href.replace(".fotki.com", "." + dom_prefix + "fotki.com");
	}

	if (port) {
		href = href.replace(".fotki.com",".fotki.com" + port);
	}

	if (username != null && getCookie("s_id") != '' && !Core.isDev()) {
		href = href.replace("##username##", username + "/");
	} else if (dev_username != null && getCookie("dev_s_id") != '') {
		href = href.replace("##username##", dev_username + "/");
	} else {
		href = href.replace("##username##", '');
	}

	return(href);
}


Core.isFunction = function Core_isFunction(f) {
	if (f != null) {
		var f = f + '';
		return (f.indexOf("function") > -1);
	}
}

// taken from http://blog.firetree.net/2005/07/17/javascript-onload/
Core.windowOnload= function Core_windowOnload(f) {
	var prev = window.onload;

	window.onload = function() {
		try {
			if (prev) prev();
			if (f) f();
		} catch(e) {
			Logger.log("error putting function to window.onload");
		}
	}
}

// work with DOM elements

Core.elementCache = new Array();

Core.dump= function Core_dump(obj) {
	if (obj != null) {
		Logger.log('dumping object: ' + obj + '---------------');

		for (var i in obj) {
			if (i > -1) {
				Logger.log(i + ":" + obj[i]);
			} else {
				Logger.log(i + ':' + eval("obj." + i));
			}
		}

		Logger.log('---------------------------------------');
	}
}

Core.getElementWidth = function Core_getElementWidth(e) {
	if (e != null) {
		var el = (typeof(e) == 'object') ? e : Core.getElementU(e);

		if(el != null) {
			if (el.tagName == "TD" || el.tagName == "DIV") {
				return el.clientWidth;
			} else if (el.tagName == "IMG") {
				return el.width;
			} else {
				return (el.offsetWidth ? el.offsetWidth : (el.clientWidth || el.width || el.style.width || 0));
			}
		}
	}
}

Core.getElementHeight = function Core_getElementHeight(e) {
	if (e != null) {
		var el = (typeof(e) == 'object') ? e : Core.getElementU(e);

		if(el != null) {
			if (el.tagName == "TD" || el.tagName == "DIV") {
				return el.clientHeight;
			} else if (el.tagName == "IMG") {
				return el.height;
			} else {
				return (el.offsetHeight ? el.offsetHeight : (el.clientHeight || el.height || el.style.height || 0));
			}
		}
	}
}


Core.getSize = function Core_getSize(e) {
	return Core.getElementSize(e);
}

Core.getElementSize = function Core_getElementSize(e) {
	var ret = new Object();
	ret.height = 0;
	ret.width = 0;

	if (e != null) {
		var el = Core.getElementU(e);

		if(el != null) {
			if (el.tagName == "TD") {
				ret.height = el.clientHeight;
				ret.width = el.clientWidth;
			} else if (el.tagName == "IMG") {
				ret.height = el.height;
				ret.width = el.width;
			} else {
				ret.height = el.offsetHeight ? el.offsetHeight : (el.clientHeight || el.height || el.style.height || 0);
				ret.width = el.offsetWidth ? el.offsetWidth : (el.clientWidth || el.width || el.style.height || 0);
			}

			// TODO: write for other objects as well
		}
	}

//document.title = (el.offsetHeight ||'x') + ' - ' + (el.clientHeight||'x') + ' - ' +  (el.style.height||'x') +'  - '+ (el.height||'x');

	return ret;
}

Core.setFocus = function(e) {
		  if (e != null) {
		var el = Core.getElementU(e);

		if(el != null) {
			if (el.tagName == "INPUT" || el.tagName == "TEXTAREA") {
				el.focus();
			}
		}
	}
}

Core.flushElementCache = function() {
	Core.elementCache = new Array();
}

Core.getElementRaw = function Core_getElementRaw(e) {
	return Core.getElementU(e, 'no_cache');
}

Core.getElementU = function Core_getElementU(e, no_cache) {
	if (e != null) {
		if (typeof(e) == 'object') {
			return e;
		}

		if (Core.elementCache[e] == null || no_cache) {
			var el = (document.all) ? document.all[e] : document.getElementById(e);
			Core.elementCache[e] = el;
			return el;
		} else {
			var el = Core.elementCache[e];
			return el;
		}
	}
}

Core.getDocumentBody = function Core_getDocumentBody() {
	return document.getElementsByTagName("body")[0];
}

Core.showElement = function Core_showElement(e) {
	if (e != null) {
		var el = Core.getElementU(e);	
		
		if (el != null) {
			// hack for @import-ed CSS files
			
			if (Core.detectBrowser().isIE && Core.detectBrowser().version == '6.0') {
				try {Core.getElementU('bottomline').style.display = 'none';} catch (e) {}
				try {Core.getElementU('bottomline').style.display = 'block';} catch (e) {}
			}
			
			if (el.className.match('hide')) {
	               Core.replaceInClassName(e,'hide','');
				   el.style.display = '';
			}	
			
			if (el.tagName == "DIV" || el.tagName == "P") {
				el.style.display = 'block';
			} else {
				el.style.display = '';

			}
			
			el.style.visibility = 'visible';
		}
	}
}

Core.hideElement = function Core_hideElement(e) {
	if (e != null) {
		var el = Core.getElementU(e);
		
		if (el != null) {
			// hack for @import-ed CSS files
			if (el.className && el.className.match('hide')) {
	               Core.replaceInClassName(e,'hide','');
				   el.style.display = 'none';
			}
			
			el.style.display = "none";
		} else {
			Logger.log("hideElement doesn't support " + e + " type of objects yet");
		}
	}
}

Core.showHideElement = function (e) {
	if (e != null) {
		var el = Core.getElementU(e);

		if (el != null) {
			// hack for @import-ed CSS files
			if (el.className.match('hide')) {
				el.style.display = 'none';
			}
			if (el.style.display == "none") {
				Core.showElement(e);
			} else {
				Core.hideElement(e);
			}
		}
	}
}

Core.isVisibleElement = function (e) {
	if (e != null) {
		var el = Core.getElementU(e);

		if (el != null) {
			// hack for @import-ed CSS files
			if (el.className.match('hide')) {
				el.style.display = 'none';
			}
			if (el.style.display == "none") {
            return 0;
			} else {
            return 1;
			}
		} else {
         return 0;
      }
	} else {
      return 0;
   }
}

Core.removeElement = function (e) {
	if (e != null) {
		var el = (typeof(e) == 'object') ? e : Core.getElementU(e);
		if (el != null) {
         try {
            el.parentNode.removeChild(el);
         } catch (err) {
         }
		}
	}
}

Core.setText = function (e, text) {
	if (e != null) {
		var el = (typeof(e) == 'object') ? e : Core.getElementU(e);
		if (el != null && text != null) {
			if (el.tagName == "INPUT" || el.tagName == "TEXTAREA" || el.tagName == "SELECT") {
				el.value = text;
			} else {
				el.innerHTML = text;
			}
		}
	}
}

Core.appendText = function (e, text) {
	if (e != null) {
		var el = (typeof(e) == 'object') ? e : Core.getElementU(e);
		if (el != null && text != null) {
			if (el.tagName == "INPUT" || el.tagName == "TEXTAREA" || el.tagName == "SELECT") {
				el.value = el.value+text;
			} else {
				el.innerHTML = el.innerHTML+text;
			}
		}
	}
}

Core.prependText = function (e, text) {
	if (e != null) {
		var el = (typeof(e) == 'object') ? e : Core.getElementU(e);
		if (el != null && text != null) {
			if (el.tagName == "INPUT" || el.tagName == "TEXTAREA" || el.tagName == "SELECT") {
				el.value = text+el.value;
			} else {
				el.innerHTML = text+el.innerHTML;
			}
		}
	}
}

Core.setRadioChecked = function(e) {
   var el = Core.getElementU(e);
   if (el != null) {
      el.checked=true;
   }
}

Core.setRadioUnChecked = function(e) {
   var el = Core.getElementU(e);
   if (el != null) {
      el.checked=false;
   }
}

Core.setSize = function (e, width, height) {
	if (e != null) {
		var el = Core.getElementU(e);
		if (el != null) {
		  try {el.style.width = width + 'px';} catch (e) {}
		  try {el.style.height = height + 'px';} catch (e) {}
		}
	}
}

Core.getText= function Core_getText(e) {
	if (e != null) {
		var el = Core.getElementU(e);
		var text = null;

		if (el != null ) {
			if(el.tagName == "DIV" || el.tagName == "P" || el.tagName == "SPAN" || el.tagName == "TR" || el.tagName == "DD" || el.tagName == "TD" || el.tagName == "UL" || el.tagName == "LI" || el.tagName == "EM" || el.tagName == "B" || el.tagName == "A") {
				 text = el.innerHTML;
			} else if (el.tagName == "INPUT" || el.tagName == "TEXTAREA" || el.tagName == "SELECT") {
				if(el.type == "radio" || el.type == "checkbox") {
					if(el.checked) {
						text = el.value;
					} else {
						text = '';
					}
				} else {
					text = el.value;
				}
			}
			return text;
		}
	}
}

Core.setClassName = function(e, className) {
	if (e != null && className != null) {
		var text = null;
		var el = (e == "object" ? e : Core.getElementU(e));

		if (el != null ) {
			el.className = className;
		}
	}
}

Core.switchClassNames = function(e, from_className, to_className) {
	if (e != null && from_className != null && to_className !=null) {
		var el = Core.getElementU(e);

		if (el != null && el.className == from_className) {
			el.className = to_className;
		} else if (el != null){
			el.className = from_className;
		}
	}
}

Core.getClassName = function(e) {
	if (e != null) {
		var el = Core.getElementU(e);

		if (el != null ) {
			return el.className || '';
		}
	}
}

Core.addToClassName = function(e, className) {
	if (e != null && className != null) {
		Core.setClassName(e, Core.getClassName(e)+ ' ' + className);
	}
}

Core.replaceInClassName = function(e, replace_what, replace_to) {
	if (e != null && replace_what != null && replace_to != null) {
		var el = Core.getElementU(e);

		if (el != null && el.className != null) {
			el.className = el.className.replace(replace_what, replace_to);
		}
	}
}

Core.clearTail = function Core_clearTail(e, numberOfLinesToLeave) {
	var all_lines = Core.getText(e);

	if (all_lines != null) {
		var lines = all_lines.split("<br>");

		if (lines.length > numberOfLinesToLeave) {
			lines = lines.slice(0, numberOfLinesToLeave);
		}

		Core.setText(e, lines.join("<br>"));
	}
}

Core.appendText= function Core_appendText(e, text) {
	Core.setText(e, Core.getText(e) + text);
}

Core.appendTextToTop= function Core_appendTextToTop(e, text) {
	Core.setText(e, text + Core.getText(e));
}

//

Core.parseInt = function(s) {
	if (s != null && s != "") {
		return s.replace(/[^\d]/g, "");
	}
}

//Rounds up the float or int value. precision - is amount of digits after the comma. May be negative.
Core.round = function Core_round(value, precision) {
	if (precision == undefined){
		precision = 0;
	}

	precision = Math.pow(10, precision);
	return Math.round(value*precision)/precision;
}

Core.formatMoney = function formatMoney(value) {
	value = Core.round(value, 2);
	var v = value * 100;
	var return_string = value;

	if (v % 100 == 0) return_string += '.00';
	else if (v % 10 == 0) return_string += '0';
	return return_string;
}

//Adds event listener for elOn object. strEventType = 'scroll', 'resize', 'hover', etc.
Core.addEvent = null;
if (document.addEventListener) {
	Core.addEvent = function Core_addEventA(elOn, strEventType, ptrFunction) {
		elOn.addEventListener(strEventType, ptrFunction, false);
	};
} else if (document.attachEvent) {
	Core.addEvent = function Core_addEventB(elOn, strEventType, ptrFunction) {
		elOn.attachEvent('on' + strEventType, ptrFunction);
	};
} else {
	Logger.log('unable to attach event corresponding to W3C or MS model');
	//Core.addEvent = new Function; // not supported
	Core.addEvent = function Core_addEventC(elOn, strEventType, ptrFunction) {
		if (Core.isFunction(elOn['on' + strEventType])) {
			elOn['on' + strEventType] =
				function() {
					this['on' + strEventType]();  //TODO: check if possible to change elOn to this!
					ptrFunction();
				};
		} else {
			elOn['on' + strEventType] = ptrFunction;
		}
	}
}

Core.addSystemEvent = function Core_addSystemEvent(strEventType, ptrFunction) {
	return Core.addEvent( (document.documentElement ? document.documentElement : window), strEventType, ptrFunction)
}

Core.removeEvent = function Core_removeEvent(elOn, strEventType, ptrFunction) {
	if (elOn.removeEventListener) {
		elOn.removeEventListener(strEventType, ptrFunction, false);
	} else if (elOn.detachEvent) {
		elOn.detachEvent('on' + strEventType, ptrFunction);
	} else {
		elOn['on' + strEventType] = null;
	}
}

Core.removeSystemEvent = function Core_removeSystemEvent(strEventType, ptrFunction) {
	return Core.removeEvent( (document.documentElement ? document.documentElement : window), strEventType, ptrFunction)
}



Core.getPageScrollTop = function Core_getPageScrollTop() {
	var scroll = -1;
	if (document.documentElement && document.documentElement.scrollTop !=null && !Core.detectBrowser().isSafari) {
		// IE6 +4.01 scrolling going on
		scroll = document.documentElement.scrollTop;
	} else if (document.body /*&& document.body.scrollTop*/) {
		scroll = document.body.scrollTop;
	} else if (self.pageYOffset) {
		scroll = self.pageYOffset;
	}
	return scroll;
}

Core.getPageScrollLeft = function Core_getPageScrollLeft() {
	var scroll = -1;
	if (document.documentElement && document.documentElement.scrollLeft !=null && !Core.detectBrowser().isSafari) {
		// IE6 +4.01 scrolling going on
		scroll = document.documentElement.scrollLeft;
	} else if (document.body /*&& document.body.scrollLeft*/) {
		scroll = document.body.scrollLeft;
	} else if (self.pageXOffset) {
		scroll = self.pageXOffset;
	}
	return scroll;
}

Core.getBrowserVisibleArea = function Core_getBrowserVisibleArea() {
	var ret = new Object();

	if (self.innerHeight) {//!Explorer
		ret.width = self.innerWidth;
		ret.height = self.innerHeight;
		ret.outerWidth = self.outerWidth;
		ret.outerHeight = self.outerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) {
		ret.width  = document.documentElement.clientWidth;
		ret.height = document.documentElement.clientHeight;
		ret.outerWidth = document.documentElement.outerWidth;
		ret.outerHeight = document.documentElement.outerHeight;
	} else if (document.body) {// other Explorers
		ret.width = document.body.clientWidth;
		ret.height = document.body.clientHeight;
		ret.outerWidth = document.body.outerWidth;
		ret.outerHeight = document.body.outerHeight;
	} else {
		ret.width = 0; ret.height = 0;
		ret.outerWidth = 0; ret.outerHeight = 0;
	}

//document.title = ret.width + 'x' + ret.height + ' - ' + ret.outerWidth + 'x' + ret.outerHeight;
//document.title = self.outerHeight + ' - ' + document.documentElement.outerHeight + ' - ' + document.body.outerHeight;

	var def_toolbar_height = 100;
	if (!ret.outerHeight) {
		ret.outerHeight = ret.height + def_toolbar_height;
		ret.outerWidth = ret.width;
	}

	ret.toolbarHeight = ret.outerHeight - ret.height;

	return ret;
}


Core.getPageDimensions = function Core_getPageDimensions() {
	var ret = new Object();
	ret.width = 0; ret.height = 0;

	var test1 = document.body.scrollHeight;
	var test2 = document.body.offsetHeight
	if (test1 > test2) { // all but Explorer Mac
		ret.width = document.body.scrollWidth;
		ret.height = document.body.scrollHeight;
	} else { // Explorer Mac;
				//would also work in Explorer 6 Strict, Mozilla and Safari
		ret.width = document.body.offsetWidth;
		ret.height = document.body.offsetHeight;
	}

	return ret;
}

Core.getScreenDimensions = function Core_getScreenDimensions() {
	var ret = new Object();
	ret.width = self.screen.width || 0;
	ret.height = self.screen.height || 0;
	return ret;
}

Core.getElementPos = function Core_getElementPos(e) {
	var currentLeft = 0;
	var currentTop  = 0;

	if (e != null) {
		var el = (typeof(e) == 'object') ? e : Core.getElementU(e);

		if (el != null && el.offsetParent) {
			currentLeft = el.offsetLeft;
			currentTop = el.offsetTop;

			while (el = el.offsetParent) {
				currentLeft += el.offsetLeft;
				currentTop  += el.offsetTop;
			}
		} else {
			return null;
		}
	}

	var ret = new Object();
	ret.currentLeft = currentLeft;
	ret.x = currentLeft;
	ret.currentTop = currentTop;
	ret.y = currentTop;

	return ret;
}


//TODO: make as an extention for Array.prototype.inArray(needle) - test for xbrowser compatibility
Core.inArray = function Core_inArray(array_haystack, search_needle) {
	var i = array_haystack.length;
	if (i > 0) {
		do {
			if (array_haystack[i] === search_needle) {
				return true;
			}
		} while (i--);
	}
	return false;
}


// eats object with parameters or url, window name, size (deprecated);
Core.openWindow = function Core_openWindow(a,b,c) {
	if(a == null) { return };
	var popupWin;
	if (typeof(a) == 'object') {
		if (a.url == null ) { return; }
		a.winname	  = a.winname || "";
		a.scrollbars  = a.scrollbars || "yes";
		a.resizable	= a.resizable || "yes";
		a.width		 = a.width || "400";
		a.height		= a.height || "500";
		a.raised		= a.raised || "yes"; // always raised
		a.dependent	= a.dependent || "yes";
		a.zlock		 = a.zlock || "yes";

		popupWin = window.open(a.url,a.winname,'scrollbars=' + a.scrollbars + ', resizable = ' + a.resizable + ', width = ' + a.width + ', height = ' + a.height + ', alwaysRaised = ' + a.raised + ', dependent = ' + a.dependent + ', z-lock = ' + a.zlock);
		if (a.moveHor && a.moveVert) {
			popupWin.moveTo(a.moveHor, a.moveVert);
		}
	} else if (typeof(a) == 'string'){
		if (b == null) { b = ""; };
		popupWin = window.open(a, b, 'scrollbars=yes,resizable=yes, width=400,height=500 alwaysRaised=yes,dependent=yes,z-lock=yes');
	}
	popupWin.focus();
	return false;
}

Core.mrdescape = function(str) {
	//alert(str);
	data = new String(str);
	data2 = new String;
	var prev;
	var empty=true;
	for (var i=0;i<data.length;i++) {
	   s = str.charCodeAt(i);
	   if (s==32||s==95||s==45) {
         if (prev==s) {
	      } else if ((prev != 32)&& !empty)
	         data2+=String.fromCharCode(95);
	   } else if ( ((s>47)&&(s<58))||(s==45)||((s>64)&&(s<91))||((s>94)&&(s<123))||(s==126)||(s==8)||(s==0)) {
		   data2+=String.fromCharCode(s);
		   empty=false;
	   }
	   prev=s;
	}
	data=data2.toLowerCase();
	if ((data.length>2)&&(data.charCodeAt(data.length-1)==95))
		data=new String(data.substr(0,data.length-1));
	if (empty) {
	 data = new String(str);
	 c=new Number;
	 for (var i=0;i<data.length;i++) {
	  c+=(523*data.charCodeAt(i));
	  c = c % 3200000;
	 }
	 data=c.toString(20);
	}
	return data.toString();
}

function CheckSymbols(str) {
  for (var i=0;i<str.length;i++) {
	s = str.charCodeAt(i);
	if (!( ((s>47)&&(s<58))||(s==45)||((s>64)&&(s<91))||((s>94)&&(s<123))||(s==33)||(s==126)||(s==8)||(s==0)))
			 return false;
  }
  return true;
}

Core.validateEmail = function Core_validateEmail(email) {
	if (/^[^@\s]+@([A-Za-z0-9\-]+\.)+[A-Za-z]{2,4}$/.test(email)) {
		return true;
	} else {
		return false;
	}
}

Core.getArrayUnique = function Core_getArrayUnique(array) {
	// making a hash of array
	var hash_from_array = new Array();
	var array_from_hash = new Array();
	if (typeof(array) == 'object') {
		for (a in array) {
			hash_from_array[array[a]] = 1;
		}
		for (b in hash_from_array) {
			array_from_hash.push(b);
		}
		return array_from_hash;
	}
	return false;
}


Core.chooseLang = function Core_chooseLang(lang) {
	var expdate = new Date();
	fixDate(expdate);
	expdate.setTime(expdate.getTime() + (24 * 60 * 60 * 1000)*365);
	setCookie('lang', lang, expdate, '/', '.fotki.com');
	if (Core.location.indexOf("http://www.dev.fotki.com") != -1 || Core.location.indexOf("http://www.fotki.com") != -1 || Core.location.indexOf("http://www.staging.fotki.com") != -1) {
		location.href='http://' +  location.host + '/';
	} else {
		window.location.reload();
	}
//	window.location.replace("?current_lang=" + lang);
}

Core.chooseRegion = function Core_chooseRegion(region, redirect_url) {
	var expdate = new Date();
	fixDate(expdate);
	expdate.setTime(expdate.getTime() + (24 * 60 * 60 * 1000)*365);

	setCookie('regional_settings', region, expdate, '/', '.fotki.com');
	
	location.href=redirect_url;

}

// get error from ajax response
Core.getResponseError = function Core_get_ajax_error (obj) {
	if(obj.responseText != null && obj.responseText.indexOf('error|') > -1){
		return obj.responseText.substr(6);
	} else {
		Logger.log(obj.responseText);
		return '';
	}
}



// cookies.js starts

var fotki_hostname = location.hostname.match(/fotki\.com$/) ? "fotki.com" : location.hostname;

// name - name of the cookie
// value - value of the cookie
// [expires] - expiration date of the cookie (defaults to end of current session)
// [path] - path for which the cookie is valid (defaults to path of calling document)
// [domain] - domain for which the cookie is valid (defaults to domain of calling document)
// [secure] - Boolean value indicating if the cookie transmission requires a secure transmission
// * an argument defaults when it is assigned null as a placeholder
// * a null placeholder is not required for trailing omitted arguments
function setCookie(name, value, expires, path, domain, secure) {
  var curCookie = name + "=" + escape(value) +
		((expires) ? "; expires=" + expires.toGMTString() : "") +
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		((secure) ? "; secure" : "");
  document.cookie = curCookie;
}

// name - name of the desired cookie
// * return string containing value of specified cookie or null if cookie does not exist
function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
	 begin = dc.indexOf(prefix);
	 if (begin != 0) return null;
  } else
	 begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
	 end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}

// name - name of the cookie
// [path] - path of the cookie (must be same as path used to create cookie)
// [domain] - domain of the cookie (must be same as domain used to create cookie)
// * path and domain default if assigned null or omitted if no explicit argument proceeds
function deleteCookie(name, path, domain) {
  if (getCookie(name)) {
	 document.cookie = name + "=" +
	 ((path) ? "; path=" + path : "") +
	 ((domain) ? "; domain=" + domain : "") +
	 "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

// date - any instance of the Date object
// * hand all instances of the Date object to this function for "repairs"
function fixDate(date) {
  var base = new Date(0);
  var skew = base.getTime();
  if (skew > 0)
	 date.setTime(date.getTime() - skew);
}

// date - any instance of the Date object
// cookies.js ends

// dictionary starts

function LangDict () {
}

LangDict.translateToken = function translateToken(token) {

	 if(LangDict.dict[token] == null){
		  return token;
	 }

	 if(LangDict.dict[token]['translated'] == null) {
		  if(LangDict.dict[token]['en'] == null) {
			  return token;
		  } else {
			  return  LangDict.dict[token]['en'];
		  }
	 } else {
		  return  LangDict.dict[token]['translated'];
	 }
}



// dictionary ends

function switch_tab_splitter() {
	var top_part = Core.getElementU('top_part');
	if (top_part.style.display == "none") {
		Core.showElement('top_part');
		//Core.showElement('tabs_toppart');
		Core.setClassName('line', 'one');
      Core.hideElement('top_part_title_alone');
		setCookie('hide_top_part', 0, "", "/", "." + fotki_hostname);
	} else {
		Core.hideElement('top_part');
		//Core.hideElement('tabs_toppart');
		Core.setClassName('line', 'two');
      Core.showElement('top_part_title_alone');
		setCookie('hide_top_part', 1, "", "/", "." + fotki_hostname);
	}
}

function switch_splitter(cookie_name) {
	if (Core.getClassName('dtree') == 'hide') {
		Core.setClassName('dtree', '');
		Core.showElement('tree');
		setCookie(cookie_name, 0, "", "/", "." +fotki_hostname);
		Core.setClassName('itsplitter', 'two');
	} else {
		Core.setClassName('dtree','hide');
		Core.hideElement('tree');
		setCookie(cookie_name, 1, "", "/", "." +fotki_hostname);
		Core.setClassName('itsplitter', 'one');
	}

}

// README: is this function needed?
Core.photoURLChecker = function Core_photoURLChecker() {
	var location = document.location.href;
	var url_to_send = null;
	if (location.indexOf('#') > -1) {
		var parts = location.match(/(.*)\/(.*)\.html#(.*)/);
		if (parts != null) {
			Core.getPhoto(parts[3]);
		}
	}
}

Core.Template = function Core_Template (text) {

	if(!text) return;
	this.tpl_cont = text;

	this.getContent = function() {
		return this.tpl_cont;
	}

	this.replaceContentHash = function (obj, text) {
		for (var i in obj) {
			if (i.indexOf('if_') == -1) {
				if (text) {
					while (text.indexOf("##" + i + "##") > -1) {
						var pos = text.indexOf("##" + i + "##");
						var i_length = i.length + 4;
						if (pos > -1) {
							var first_part = text.substr(0, pos);
							var second_part = text.substr(pos + i_length);
							text = first_part + obj[i] + second_part;
						}
					}
				} else {
					while (this.tpl_cont.indexOf("##" + i + "##") > -1) {
						var pos = this.tpl_cont.indexOf("##" + i + "##");
						var i_length = i.length + 4;
						if (pos > -1) {
							var first_part = this.tpl_cont.substr(0, pos);
							var second_part = this.tpl_cont.substr(pos + i_length);
							this.tpl_cont = first_part + obj[i] + second_part;
						}
					}
				}
			} else {
				f = i.split("_")[1];
				var cont = text ? text : this.tpl_cont;
				var cnt=0;
				while (cont.indexOf("##if " + f + "##") > -1) {
					var if_start = cont.indexOf("##if " + f + "##");
					var if_end = cont.indexOf("##endif " + f + "##");
					if (if_start > -1 && if_end > -1) {
						var first_part = cont.substr(0, if_start);
						var second_part = cont.substr((if_end+7) + f.length + 3);
						var if_text = cont.substring(if_start + 7 + f.length, if_end);
						if (if_text) {
							cont = first_part + ((obj[i] > 0) ? if_text : "") + second_part;
							if (text) {
								text = cont;
							} else {
								this.tpl_cont = cont;
							}
						} else {
							cont = first_part + second_part;
							if (text) {
								text = cont;
							} else {
								this.tpl_cont = cont;
							}
						}
					} else {
						break;
					}
				}
			}
	}
	if (text) return text;
}

	this.replaceLoopContent = function (marker, array) {
		while (this.tpl_cont.indexOf("@@" + marker + "@@") > -1)  {
			var loop_start = this.tpl_cont.indexOf("@@" + marker + "@@");
			var loop_end = this.tpl_cont.indexOf("@@" + marker + "@@", (loop_start + marker.length +4));
			var first_part = this.tpl_cont.substring(0, loop_start);
			var second_part = this.tpl_cont.substring(loop_end + marker.length + 4);
			var inside_marker = this.tpl_cont.substring((loop_start+marker.length+4), loop_end);
			var out = "";
			if (inside_marker) {
				for (var i in array) {
					out += this.replaceContentHash(array[i], inside_marker);
				}
			}
			this.tpl_cont = first_part + out + second_part;
		}
	}
}

Core.setBg = function(element, bg) {
	if (typeof(element) != "object") {
		element = Core.getElementU(element);
	}
	element.style.background=bg;
}

Core.getBrowserVersion = function Core_getBrowserVersion (version) { // 'version'/'v'/''
//	Logger.log('deprecated: use Core.detectBrowser() instead of this! REMOVE ME');

	var navigatorInfo = new Object();
	navigatorInfo.browser = '';	// string: 'firefox', 'ie', 'opera', 'safari'
	navigatorInfo.version = '';	// browser version

	//alert(navigator.userAgent+'-'+navigator.appCodeName+'--'+navigator.appVersion);
	if(navigator.userAgent.indexOf("Firefox")>-1)	{
		navigatorInfo.browser = "firefox";
		if(version == 'v' || version == 'version') {
			navigatorInfo.version = navigator.userAgent.substring(navigator.userAgent.indexOf("rv:")+3, navigator.userAgent.indexOf(")"));
		}
	} else if((navigator.userAgent.indexOf("MSIE")>-1) || (navigator.appAgent.indexOf("Microsoft")>-1)) {
		navigatorInfo.browser = "ie";
		if(version == 'v' || version == 'version') {
			navigatorInfo.version = navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE ")+5, navigator.userAgent.indexOf("; Windows"));
		}
	} else if(navigator.userAgent.indexOf("Opera")>-1) {
		navigatorInfo.browser = "opera";
		if(version == 'v' || version == 'version') {
			 navigatorInfo.version = navigator.userAgent.substring(navigator.userAgent.indexOf("/")+1, navigator.userAgent.indexOf(" ("));
		}
	} else if(navigator.userAgent.indexOf("Safari")>-1){
		navigatorInfo.browser = "safari";
		if(version == 'v' || version == 'version') {
			 navigatorInfo.version = navigator.userAgent.substring(navigator.userAgent.lastIndexOf("/")+1);
		}
	} else {
		navigatorInfo.browser = navigator.appName;
		if(version == 'v' || version == 'version') {
			navigatorInfo.version = navigator.appVersion;
		}
	}
	
	if (navigator.platform.indexOf("Linux")>-1) {
		navigatorInfo.platform = "linux";
	} else if (navigator.platform.indexOf("MacIntel")>-1) {
		navigatorInfo.platform = "mac";	
	} else {
		navigatorInfo.platform = "windows";
	}

	return navigatorInfo;
}

//returns .browser string name = (ie, opera, mozilla, firefox, safari or maxthon)
//returns browser .version and returns boolean vars:
//.isIE, .isOpera, .isMozilla, .isFirefox, .isSafari, .isMaxthon
// if (Core.detectBrowser().isIE || Core.detectBrowser().browser == 'opera') alert();
Core.detectBrowser = function Core_detectBrowser() {
	if (this.browser == null) {
		this.browser = new Object();
		this.browser.browser = '';
		this.browser.version = '';
	} else {
		return this.browser;
	}

	var ua = navigator.userAgent.toLowerCase();

	if (this.browser.isIE = ((ua.indexOf("msie") != -1) && (ua.indexOf("opera") == -1) && (ua.indexOf("webtv") == -1)) ? 1:0 ) {
		this.browser.browser = "ie";
		this.browser.version = ua.substring(ua.indexOf("msie ")+5, ua.indexOf("; windows"));
	}

	if (this.browser.isOpera = (ua.indexOf("opera") != -1 || window.opera) ? 1:0 ) {
		this.browser.browser = "opera";
		this.browser.version = ua.substring(ua.indexOf("/")+1, ua.indexOf(" ("));
	}

	if (this.browser.isMozilla = (ua.indexOf("gecko") != -1 && ua.indexOf("safari") == -1 && ua.indexOf("firefox") == -1) ? 1:0 ) {
		this.browser.browser = "mozilla";
		this.browser.version = navigator.appVersion;//?
	}

	if (this.browser.isFireFox = (ua.indexOf("firefox") != -1) ? 1:0 ) {
		this.browser.browser = "firefox";
		this.browser.version = ua.substring(ua.indexOf("rv:")+3, ua.indexOf(")"));
	}

	if (this.browser.isSafari = (ua.indexOf("gecko") == -1 && ua.indexOf("safari") != -1 ||
		navigator.vendor && navigator.vendor.toLowerCase().indexOf("apple") != -1) ? 1:0 ) {
		this.browser.browser = "safari";
		this.browser.version = ua.substring(ua.lastIndexOf("/")+1);
	}

	if (this.browser.isMaxthon = ((ua.indexOf("msie") != -1) && (ua.indexOf("maxthon") != -1)) ? 1:0 ) {
		this.browser.browser = "maxthon";
		this.browser.version = navigator.appVersion;//?
	}

	if (navigator.platform.indexOf("Linux")>-1) {
		this.browser.platform = "linux";
	} else if (navigator.platform.indexOf("MacIntel")>-1) {
		this.browser.platform = "mac";
	} else {
		this.browser.platform = "windows";
	}

	return this.browser;
};



// PHOTO TOOLS

function Photo() {
}

var original_photo_width = null;
var photo_resize_still_running = false;
var navigation_resize_still_running = false;
var critial_red_line_size = 6;
var resizing_step = 3;
var minimum_photo_size = 120;

var photo_id = 'stretch_photo_id';
var meter_id = 'red_line';

Photo.resizingPhoto = function() {
  if (original_photo_width == null) { return; }

  Core.hideElement('google_ad_small');
  //Core.hideElement('copyright_block');

  var prop = Core.getElementHeight(photo_id) / Core.getElementWidth(photo_id);
  var line_width = Core.getElementWidth(meter_id);

  if (line_width != null && (line_width < critial_red_line_size)) {
	 for (i=0; i<(680/resizing_step);i++) {
		var red_line_width		= Core.getElementWidth(meter_id);
		var current_photo_width = Core.getElementWidth(photo_id);

		if (current_photo_width == 0) {
		  break;
		}

		if ((red_line_width < critial_red_line_size) && (current_photo_width > (minimum_photo_size) ) ) {
		  Core.setSize(photo_id, current_photo_width - resizing_step);
		  //Core.setText('info_span', current_photo_width - resizing_step);
		} else {
		  break;
		}
	 }
  } else {
	 var photo_width = Core.getElementWidth(photo_id);

	 if (photo_width < original_photo_width) {
		var new_width = (line_width - critial_red_line_size) + photo_width;

		if (new_width > original_photo_width) {
			 new_width = original_photo_width;
		}

		Core.setSize(photo_id, new_width);
		//Core.setText('info_span',new_width);
	 }
  }

  photo_resize_still_running = false;
  Core.showElement('google_ad_small');
  //Core.showElement('copyright_block');
}

Photo.resizingInit = function() {

  Core.addEvent(window, 'resize', function () {
	 if (!photo_resize_still_running) {
		photo_resize_still_running = true;
		setTimeout('Photo.resizingPhoto();',100);
	 }
  }
  );
  Core.addEvent(window, 'load', Photo.resizingPhoto );
}

Photo.cacheImg = function(url) {
  var cache_img = new Image();
  cache_img.src = url;
}

//Fixes XML processing of no static Node defined!
if (!window['Node']) {
	window.Node = new Object();
	Node.ELEMENT_NODE = 1;
	Node.ATTRIBUTE_NODE = 2;
	Node.TEXT_NODE = 3;
	Node.CDATA_SECTION_NODE = 4;
	Node.ENTITY_REFERENCE_NODE = 5;
	Node.ENTITY_NODE = 6;
	Node.PROCESSING_INSTRUCTION_NODE = 7;
	Node.COMMENT_NODE = 8;
	Node.DOCUMENT_NODE = 9;
	Node.DOCUMENT_TYPE_NODE = 10;
	Node.DOCUMENT_FRAGMENT_NODE = 11;
	Node.NOTATION_NODE = 12;
}

// getPageSize()
// Returns array with page width, height and window width, height
Core.getPageSize = function Core_getPageSize () {
	var xScroll, yScroll;

	if (window.innerHeight && window.scrollMaxY) {
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight && (document.body.scrollHeight > document.body.offsetHeight)) { // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}

	var windowWidth = Core.getBrowserVisibleArea().width;
	var windowHeight = Core.getBrowserVisibleArea().height

	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else {
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}

	arrayPageSize = new Array(pageWidth, pageHeight, windowWidth, windowHeight);
	return arrayPageSize;
}


// Core.animation returns object with two functions-properties for start and stops of animation.
// Required parameter:
//		numFrames - frames count;
//		timePerFrame - delay per frame
//		animeFunc - animation function
// Optional:
//		startFunc - start function (one shot run before animeFunc)
//		finishFunc - final function (one shot run after animeFunc)
// ---------------------------------
Core.animation = function Core_animation (numFrames, timePerFrame, animeFunc, startFunc, finishFunc) {
	var frame = 0;

	if (numFrames && timePerFrame && animeFunc) {
		var anime = new Object ();
		anime.intervalID = 0;
		anime.animeFunc = animeFunc;
		anime.startFunc = (startFunc ? startFunc : null);
		anime.finishFunc = (finishFunc ? finishFunc : null);
	} else {
		return null;
	}

	anime.start = function () {
		if (anime.startFunc) anime.startFunc();
		anime.intervalID = setInterval(displayFrame, timePerFrame);
	} // anime.start

	anime.stop = function () {
		clearInterval(anime.intervalID);
	} // anime.stop

	anime.changeAnimeFunc = function (F) {
		anime.animeFunc = F;
	} // anime.changeAnimeFunc

	anime.changeStartFunc = function (F) {
		anime.startFunc = F;
	} // anime.changeStartFunc

	anime.changeFinishFunc = function (F) {
		anime.finishFunc = F;
	} // anime.changeFinishFunc

	anime.isStarted = function () {
		return (anime.intervalID ? true : false);
	} // anime.isStarted

	function displayFrame () {
		if (frame >= numFrames) {
			anime.intervalID = clearInterval(anime.intervalID);
			if (anime.finishFunc) anime.finishFunc();
			frame = 0;
			return;
		}
		anime.animeFunc();
		frame++;
	} // displayFrame

	return anime;
} // Core.animation


Core.keyNum = function Core_keyNum (e) {
	var keynum;

	if(window.event) { // IE
		keynum = e.keyCode;
	} else if(e.which) { // Netscape/Firefox/Opera 
		keynum = e.which;
	}
	return keynum; 
}

// Some examples of valid email addresses that this script will recognize:
//	 * contact@mydomain.com
//	 * jason+lang@gmail.com
//	 * help@nbc.co.uk
//	 * mary.k.ashley@celeb.com
//	 * george@sub.whatever.mydomain.ca
//	 * edward@42.234.12.345
//--------------------------------------------------------------------------------
Core.validateEmail = function Core_validateEmail(email) {
	var emailfilter = /^\w+([\+\.-]*\w+)*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,6}|\d+)$/i;
	return emailfilter.test(email);  
}

//  check for valid numeric value
Core.isAnyNumber = function Core_isAnyNumber(number) {
	var filter = /^-*\d+\.*\d*$/;
	return filter.test(number);
}

Core.isPositiveNumber = function isPositiveNumber(number) {
   if (Core.isAnyNumber(number)) {
      if (number > 0) {
         return true;
      }
   }
   
   return false;
}

Core.isIntegerNumber = function Core_isIntegerNumber(number) {
	var filter = /^\d+$/;
	return filter.test(number);
}

// NEW UNIVERSAL MENU 

function DropMenu () {
}

DropMenu.closing = new Array;
DropMenu.positionX = new Array;
DropMenu.positionY = new Array;

DropMenu.show = function(menu_id, position_id, deltaX, deltaY) {
   if ((DropMenu.closing[menu_id] != 0) && (DropMenu.closing[menu_id] != null)) {
		clearTimeout(DropMenu.closing[menu_id]);
		DropMenu.closing[menu_id] = 0;
   } else {
		var menu = Core.getElementU(menu_id);
		if (position_id) {
			var position = Core.getElementPos(position_id);
			if (position != null) {
				DropMenu.positionX[menu_id] = position.currentLeft;
				DropMenu.positionY[menu_id] = position.currentTop;
				}
			if (menu && deltaX != null) menu.style.left = deltaX + DropMenu.positionX[menu_id] + "px";
			if (menu && deltaY != null) menu.style.top = deltaY + DropMenu.positionY[menu_id] + "px";
			}
        Core.showElement(menu_id);
      }
   }

DropMenu.hide = function(menu_id) {
   DropMenu.closing[menu_id] = setTimeout("DropMenu.close('" + menu_id + "')", 200);
}

DropMenu.close = function(menu_id) {
   Core.hideElement(menu_id);
   DropMenu.closing[menu_id] = 0;
   try { //cobr problem - top_nav.js not loaded
      TopNav.open_menu_id = -1;
   } catch(e) {}
}

// END

// LIMITED EDITION NOTIFICATION
var DialogLimitedEdition = null;

function showLimitedEditionDojo(text) {

   if (!DialogLimitedEdition) {
      DialogLimitedEdition = new ModalDialog('limited_edition_dojo');
   }
   
   DialogLimitedEdition.setContent(text);
   DialogLimitedEdition.show();
}

function showShare() {
   if (Core.isVisibleElement('photo_share')) {
      resetCommentForm();
      return;
   } else {
      resetCommentForm();
   }
   
	Core.setClassName('ph_share','button sel');
	Core.showElement('photo_share');
}
