/* Helpers */
function El(x) {
	if (typeof x === "object") return x;
	if (x == "body") return document.getElementsByTagName("body")[0];
	if (x == "head") return document.getElementsByTagName("head")[0];
	return document.getElementById(x);
}
function trim(s, c) {
	if(c) {
		var r1 = new RegExp("^"+ c +"+");
		var r2 = new RegExp(c +"+$");
		return (""+ s).replace(r1, "").replace(r2, "");
	} else
		return (""+ s).replace(/^\s+/, "").replace(/\s+$/, "").replace(/\n{2,}/g, "\n\n");
}

function empty(v) {
	// return typeof v === "undefined" ||  v === "undefined" || v === null  || v === "";
	if (v === "" || v === 0 || v === "0" || v === null || v === false || typeof v === "undefined")
		return true;
	if (typeof v === "object") {
		for (var i in v)
			return false;
		return true;
	} 
	return false;
}

function each(a, f) {
	if (typeof f != "function")
		f = window[f];
	
	var arr = a || [], i;
	for (i = 0; i < arr.length; i++)
		f(arr[i]);
}

function arrayMap(a, f) {
	if (typeof f != "function")
		f = window[f];
	
	var arr = a || [], array = [], i;
	for (i = 0; i < arr.length; i++)
		array.push(f(arr[i]));
	
	return array;
}

function isArray(a, l) {
	var r = Object.prototype.toString.call(a) === "[object Array]";
	return !l ? r : r && (typeof a.length != "undefined" && a.length > 0);
}

function inArray(a, s) {
	if (!isArray(a)) return false;
	for (i in a)
		if (a[i] == s)
			return true;
	return false;
}

function arraySearch(a, s) {
	if (!isArray(a)) return false;
	for (i in a)
		if (a[i] == s)
			return i;
	return false;
}

function stripTags(v, full) {
	if (!full)
		// strip_tags
		return (""+ v).replace(/<[^>]+>(.*?)<\/?[^>]+>/gi, "$1");
	// remove_tags
	return (""+ v).replace(/<[^>]+>.*?<\/?[^>]+>/gi, "");
}

function strtr(s, a) {
	for (var i in a)
		s = s.replace(new RegExp(i, "g"), a[i]);
	return s;
}

function objectMerge(destination, source) {
    for (var property in source)
        destination[property] = source[property];
    return destination;
}

function parseStr(str) {
	var tmp = (""+ str).split("&"), r = {};
	for (i in tmp) {
		tmp[i].replace(/(.*?)=([^&]*)/, function($0, $1, $2) {
			r[$1] = $2;
		});
	}
	return r;
}
/* Helpers end */

/* Date & Time */
function getDate() {
	var D = new Date;
	var y = D.getFullYear(); y = y < 10 ? "0"+ y : y;
	var m = D.getMonth() + 1; m = m < 10 ? "0"+ m : m;
	var d = D.getDate(); d = d < 10 ? "0"+ d : d;
	return [y, m, d].join("-");
}
function getTime() {
	var D = new Date;
	var h = D.getHours(); h = h < 10 ? "0"+ h : h;
	var i = D.getMinutes(); i = i < 10 ? "0"+ i : i;
	var s = D.getSeconds(); s = s < 10 ? "0"+ s : s;
	return [h, i, s].join(":");
}
function getNow() {
	return getDate() +" "+ getTime();
}
/* Date & Time end */

function disableSelection(target) {
	if (typeof target.onselectstart != "undefined") { // IE
		target.onselectstart = function(){ return false; };
	} else if (typeof target.style.MozUserSelect != "undefined") { // FF
		target.style.MozUserSelect = "none";
	} else {
		target.onmousedown = function(){ return false; };
	}
}

function imagePreview(link, width, height) {
	var win = window.open("about:blank", "", "width="+ (parseInt(width)+30) +",height="+ (parseInt(height)+20) +",top=0,left=0,status=1,scrollbars=1,resizable=1");
	win.document.write("<html><head><script>document.onkeydown=function(e){if(!e)var e=window.event;if(((e.which)?e.which:e.keyCode)==27)self.close();}</script></head><body style='text-align:center;margin:9px 0;padding:0'><img src='"+ link +"'></body></html>");
	win.document.close();
	return !1;
}

/* Video */
var Video = {
	width: 420,
	height: 300,
	preview: function(data, url) {
		var video = this.parseData(data);
		var html = this.getHtmlObject(
			video.service,
			video.size[0],
			video.size[1],
			{"id": video.id, "name": video.name, "url": url}
		);
		var win = window.open("about:blank", "", "width=500,height=350,top=1,left=1,status=1,scrollbars=1,resizable=1");
		html = prepareHTML({"title": video.name, "body": "<b>"+ video.name +"</b><br />"+ html});
		win.document.write(html);
		win.document.close();
	},
	parseData: function(data) {
		// [video=local|site/upload/video/2011/06/michael-jackson-thriller.mp4|420x315|Michael%20Jackson%20-%20Thriller]
		var m = data.match(/\[video=(.*?)\]/i) || [];
		var t = arrayMap((m[1] || "|").split("|"), "trim");
		var s = arrayMap((t[2] || "x").split("x"), "trim");
		return {"service": t[0], "id": t[1], "size": [s[0], s[1]], "name": decodeURIComponent(t[3])};
	},
	getHtmlObject: function(service, width, height, data) {
		var object = this.templates[service], http = ENV.get("http");
		if (!object) object = '<object width="%{WIDTH}" height="%{HEIGHT}" data="'+ http +'site/asset/media/player.swf" type="application/x-shockwave-flash"><param value="opaque" name="wmode"><param value="file='+ http + (data.url || data.id) +'&volume=50" name="flashvars"><param value="true" name="allowfullscreen"><param value="always" name="allowscriptaccess"><param value="true" name="enablejs"></object>';
		return object.replace(/%{WIDTH}/g, width).replace(/%{HEIGHT}/g, height).replace(/%{ID}/g, data.id).replace(/%{NAME}/g, data.name);
	},
	templates: {
		// YOUTUBE
		"youtube.com": '<object width="%{WIDTH}" height="%{HEIGHT}"><param value="http://www.youtube.com/v/%{ID}?version=3&amp;rel=1&amp;fs=1&amp;showsearch=0&amp;showinfo=1&amp;iv_load_policy=1" name="movie"><param value="true" name="allowfullscreen"><param value="opaque" name="wmode"><embed width="%{WIDTH}" height="%{HEIGHT}" wmode="opaque" allowfullscreen="true" type="application/x-shockwave-flash" src="http://www.youtube.com/v/%{ID}?version=3&amp;rel=1&amp;fs=1&amp;showsearch=0&amp;showinfo=1&amp;iv_load_policy=1"></object>',
		// VIMEO
		"vimeo.com": '<object width="%{WIDTH}" height="%{HEIGHT}" data="http://www.vimeo.com/moogaloop.swf?clip_id=%{ID}&amp;server=www.vimeo.com&amp;fullscreen=1&amp;show_title=1&amp;show_byline=0&amp;show_portrait=0&amp;color=01AAEA" type="application/x-shockwave-flash"><param value="best" name="quality"><param value="true" name="allowfullscreen"><param value="showAll" name="scale"><param value="http://www.vimeo.com/moogaloop.swf?clip_id=%{ID}&amp;server=www.vimeo.com&amp;fullscreen=1&amp;show_title=1&amp;show_byline=0&amp;show_portrait=0&amp;color=01AAEA" name="movie"><param value="opaque" name="wmode"></object>',
		// DAILYMOTION
		"dailymotion.com": '<object width="%{WIDTH}" height="%{HEIGHT}"><param value="http://www.dailymotion.com/swf/%{ID}" name="movie"><param value="true" name="allowfullscreen"><param value="opaque" name="wmode"><embed width="%{WIDTH}" height="%{HEIGHT}" wmode="opaque" allowfullscreen="true" src="http://www.dailymotion.com/swf/%{ID}"></object>',
		// GOOGLE
		"video.google.com": '<object width="%{WIDTH}" height="%{HEIGHT}" data="http://video.google.com/googleplayer.swf?docId=%{ID}" type="application/x-shockwave-flash"><param value="never" name="allowScriptAccess"><param value="http://video.google.com/googleplayer.swf?docId=%{ID}" name="movie"><param value="best" name="quality"><param value="#000000" name="bgcolor"><param value="noScale" name="scale"><param value="opaque" name="wmode"></object>'
	}
};
/* Video end */

function prepareHTML(content) {
	return "<html><head><script>document.onkeydown=function(e){if(!e)var e=window.event;if(((e.which)?e.which:e.keyCode)==27)self.close();}</script><title>"+ (content.title || "") +"</title></head><body style='font:12px arial'>"+ (content.body || "") +"</body></html>";
}

function popup(u, w, h, t, l, n, s, r) {
	var url = u || "about:blank", width = w || 500, height = h || 300, top = t !== undefined ? t : ((screen.height / 2) - height / 2), left = l !== undefined ? l : ((screen.width / 2) - width / 2), name = n || "", scrollbars = s || 1, resizable = r || 1, win = window.open(url, name, "status=1,scrollbars="+ scrollbars +",resizable="+ resizable +",width="+ width +",height="+ height +",top="+ top +",left="+ left);
	win.focus();
}

function changeLocation(select, ignore, start) {
	var search = window.location.search.substring(1), start = start || "start", target;
	if(search != "") {
		var split = search.split("&");
		if(split != "") {
			var getVars = [];
			for(i = 0; i < split.length; i++)
				if(split[i].indexOf(ignore) == -1 && split[i].indexOf(start) == -1) /* pager start */
					getVars.push(split[i]);
			
			getVars = getVars.join("&");
			if(getVars != "")
				target = "?"+ getVars +"&"+ ignore +"="+ select.value;
		}
	}
	else target = "?"+ ignore +"="+ select.value;
	
	if(!target || typeof target == "undefined") /* debug */
		target = "?"+ ignore +"="+ select.value;
	
	self.location = target;
}

function slug(s) {
	var str = (""+ s).toLowerCase();
	str = trim(str);
	str = toASCII(str);
	str = str.replace(/[^a-z0-9]/gi, "-").replace(/-+/g, "-");
	return str;
}

function toASCII(v) {
	var chrs = {
		// lower
		'à':'a',  'ô':'o',  'ď':'d',  'ḟ':'f',  'ë':'e',  'š':'s',  'ơ':'o',
		'ß':'ss', 'ă':'a',  'ř':'r',  'ț':'t',  'ň':'n',  'ā':'a',  'ķ':'k',
		'ŝ':'s',  'ỳ':'y',  'ņ':'n',  'ĺ':'l',  'ħ':'h',  'ṗ':'p',  'ó':'o',
		'ú':'u',  'ě':'e',  'é':'e',  'ç':'c',  'ẁ':'w',  'ċ':'c',  'õ':'o',
		'ṡ':'s',  'ø':'o',  'ģ':'g',  'ŧ':'t',  'ș':'s',  'ė':'e',  'ĉ':'c',
		'ś':'s',  'î':'i',  'ű':'u',  'ć':'c',  'ę':'e',  'ŵ':'w',  'ṫ':'t',
		'ū':'u',  'č':'c',  'ö':'o',  'è':'e',  'ŷ':'y',  'ą':'a',  'ł':'l',
		'ų':'u',  'ů':'u',  'ş':'s',  'ğ':'g',  'ļ':'l',  'ƒ':'f',  'ž':'z',
		'ẃ':'w',  'ḃ':'b',  'å':'a',  'ì':'i',  'ï':'i',  'ḋ':'d',  'ť':'t',
		'ŗ':'r',  'ä':'a',  'í':'i',  'ŕ':'r',  'ê':'e',  'ü':'u',  'ò':'o',
		'ē':'e',  'ñ':'n',  'ń':'n',  'ĥ':'h',  'ĝ':'g',  'đ':'d',  'ĵ':'j',
		'ÿ':'y',  'ũ':'u',  'ŭ':'u',  'ư':'u',  'ţ':'t',  'ý':'y',  'ő':'o',
		'â':'a',  'ľ':'l',  'ẅ':'w',  'ż':'z',  'ī':'i',  'ã':'a',  'ġ':'g',
		'ṁ':'m',  'ō':'o',  'ĩ':'i',  'ù':'u',  'į':'i',  'ź':'z',  'á':'a',
		'û':'u',  'þ':'th', 'ð':'dh', 'æ':'ae', 'µ':'u',  'ĕ':'e',  'ı':'i',
		// upper
		'À':'A',  'Ô':'O',  'Ď':'D',  'Ḟ':'F',  'Ë':'E',  'Š':'S',  'Ơ':'O',
		'Ă':'A',  'Ř':'R',  'Ț':'T',  'Ň':'N',  'Ā':'A',  'Ķ':'K',  'Ĕ':'E',
		'Ŝ':'S',  'Ỳ':'Y',  'Ņ':'N',  'Ĺ':'L',  'Ħ':'H',  'Ṗ':'P',  'Ó':'O',
		'Ú':'U',  'Ě':'E',  'É':'E',  'Ç':'C',  'Ẁ':'W',  'Ċ':'C',  'Õ':'O',
		'Ṡ':'S',  'Ø':'O',  'Ģ':'G',  'Ŧ':'T',  'Ș':'S',  'Ė':'E',  'Ĉ':'C',
		'Ś':'S',  'Î':'I',  'Ű':'U',  'Ć':'C',  'Ę':'E',  'Ŵ':'W',  'Ṫ':'T',
		'Ū':'U',  'Č':'C',  'Ö':'O',  'È':'E',  'Ŷ':'Y',  'Ą':'A',  'Ł':'L',
		'Ų':'U',  'Ů':'U',  'Ş':'S',  'Ğ':'G',  'Ļ':'L',  'Ƒ':'F',  'Ž':'Z',
		'Ẃ':'W',  'Ḃ':'B',  'Å':'A',  'Ì':'I',  'Ï':'I',  'Ḋ':'D',  'Ť':'T',
		'Ŗ':'R',  'Ä':'A',  'Í':'I',  'Ŕ':'R',  'Ê':'E',  'Ü':'U',  'Ò':'O',
		'Ē':'E',  'Ñ':'N',  'Ń':'N',  'Ĥ':'H',  'Ĝ':'G',  'Đ':'D',  'Ĵ':'J',
		'Ÿ':'Y',  'Ũ':'U',  'Ŭ':'U',  'Ư':'U',  'Ţ':'T',  'Ý':'Y',  'Ő':'O',
		'Â':'A',  'Ľ':'L',  'Ẅ':'W',  'Ż':'Z',  'Ī':'I',  'Ã':'A',  'Ġ':'G',
		'Ṁ':'M',  'Ō':'O',  'Ĩ':'I',  'Ù':'U',  'Į':'I',  'Ź':'Z',  'Á':'A',
		'Û':'U',  'Þ':'Th', 'Ð':'Dh', 'Æ':'Ae', 'İ':'I'
	};
	
	return strtr(v, chrs);
}

var Ajax = {
	type: "GET",
	url: ENV.get("ajax", "url"),
	data: {},
	dataType: "json",
	cache: true,
	success: function(r) {},
	error: function(r) { $("#loading").removeClass("loading-notice").addClass("loading-error").html("Hata!<br>İşlem tamamlanamadı.").show(); /* alert("Error! \""+ r.statusText +"\""); */ },
	complete: function(r) { /* $("#loading").hide(); */ },
	set: function(opts) {
		for (i in (opts || {}))
			this[i] = opts[i];
	},
	send: function(type, file, data, s, e, c) {
		$("#loading").show();
		$.ajax({
			url: Ajax.url + file,
			type: type || Ajax.type,
			data: data || Ajax.data,
			dataType: Ajax.dataType,
			cache: Ajax.cache,
			success: function(r) {
				var fn = typeof s == "function" ? s : Ajax.success;
				fn(r);
				$("#loading").removeClass("loading-notice").addClass("loading-success").text("İşlem tamamlandı.").show();
				window.setTimeout(function() {
					$("#loading").fadeOut("slow", function() {
						$(this).removeClass("loading-success").addClass("loading-notice");
					});
				}, 3000);
			},
			error: function(r) {
				var fn = typeof e == "function" ? e : Ajax.error;
				fn(r);
			},
			complete: function(r) {
				var fn = typeof c == "function" ? c : Ajax.complete;
				fn(r);
			}
		});
	}
};

function redirect(x) {
	x = x || ""; // undefined olmasın!!!
	if (!/^http(s|):\/\//.test(x))
		window.location.href = ENV.http + x;
	else
		window.location.href = x;
	return !1;
}

/* bu n'olucak? */
/* function generateShorturl(id) {
	Ajax.send("", "main.php?action=generate_shorturl", {id:id}, function(r) {
		if (r.error) { alert(r.error); return; }
		if (r.hash)
			$("#shorturl-"+ id).html("<a href='http://hbrvsr.com/"+ r.hash +"'\
				target='_blank' title='http://hbrvsr.com/"+ r.hash +"'>"+ r.hash +"</a>");
	});
} */

/* Share */
var Share = {
	favorite: function() {
		if(Browser.IE) {
			window.external.AddFavorite(location.href, document.title);
		} else if(window.sidebar) {
			window.sidebar.addPanel(document.title, location.href, "");
		} else {
			alert("Lütfen Ctrl+D (Cmd+D) tuşlarını kullanınız!")
		}
	},
	email: function() {
		popup(
			ENV.get("http") +
			"site/tool/popup/news_send.php?u=" +
			encodeURIComponent(document.location.href) +
			"&t="+ encodeURIComponent(document.title),
			"", "", "", "", "NewsSend"
		);
	},
	print: function(id) {
		popup(
			ENV.get("http") +
			"site/tool/popup/news_print.php?id="+ id,
			650, 700, 0, 0, "NewsPrint"
		);
	},
	facebook: function(shorturl) {
		var u = shorturl || $("#shorturl_hidden").val() || document.location.href;
		var t = encodeURIComponent(document.title);
		popup(
			"http://www.facebook.com/sharer.php?u="+ u +"&t="+ t,
			"", 450, "", "", "Facebook"
		);
	},
	twitter: function(shorturl) {
		var u = shorturl || $("#shorturl_hidden").val() || document.location.href;
		/* var t = encodeURIComponent($("p.spot").text().substring(0, 100)); */
		var t = encodeURIComponent(trim(document.title.replace(/\|\s+HaberVesaire$/i, "").replace(/\s+/g, " ")));
		popup(
			"http://twitter.com/share?text="+ t +" ...&url="+ u +"&via=HaberVesaire",
			"", 350, "", "", "Twitter"
		);
	},
	shorturl: function() {
		$(".shorturl div:first").toggle();
		$(".shorturl input:first").select().click(function() {
			$(this).select();
		}).blur(function() {
			$(this).parent().hide();
		})/* .mouseout(function() {
			var div = $(this).parent();
			setTimeout(function() {
				div.hide();
			}, 150);
		}) */;
	}
};

/* getElementsByClassName */
(function(document) {
	if (typeof document.getElementsByClassName !== "function") {
		document.getElementsByClassName = function(pattern, tagName, el) {
			var className = new RegExp("(^|\\s)"+ pattern +"(\\s|$)", "i");
			var tagName = tagName || "*";
			var el = el || document;
			var tags = el.getElementsByTagName(tagName);
			var i = 0, cur, els = [];
			while(i < tags.length) {
				cur = tags[i];
				if (className.test(cur.className)) {
					els.push(cur);
				}
				i++;
			}
			return els;
		}
	}
})(document);

/* Browser */
(function(window) {
	if (typeof Browser === "undefined") {
		var Browser = {};
	}	
	// Mozilla/5.0 (Windows NT 5.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1
	// Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.205 Safari/534.16
	// Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/533.19.4 (KHTML, like Gecko) Version/5.0.3 Safari/533.19.4
	// Opera/9.64 (Windows NT 5.1; U; en) Presto/2.1.1
	// Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0;)
	Browser = (function(Browser) {
		Browser.UA = navigator.userAgent;
		Browser.FF = /Firefox\/\d+/i.test(Browser.UA);
		Browser.CR = /Chrome\/\d+/i.test(Browser.UA);
		Browser.SF = /Safari\/\d+/i.test(Browser.UA) && !Browser.CR;
		Browser.OP = /Opera\/\d+/i.test(Browser.UA);
		Browser.IE = /MSIE\s\d+/i.test(Browser.UA);
		var m = [], v;
		if(Browser.FF) {
			m = Browser.UA.match(/Firefox\/([^\s]*)/i);
			v = m[1];
			Browser.version = v.substring(0, v.indexOf("."));
			Browser.versionFull = m[1];
			Browser.name = "Firefox";
		} else if(Browser.CR) {
			m = Browser.UA.match(/Chrome\/([^\s]*)/i);
			v = m[1];
			Browser.version = v.substring(0, v.indexOf("."));
			Browser.versionFull = m[1];
			Browser.name = "Chrome";
		} else if(Browser.SF) {
			m = Browser.UA.match(/Version\/([^\s]*)/i);
			v = m[1];
			Browser.version = v.substring(0, v.indexOf("."));
			Browser.versionFull = m[1];
			Browser.name = "Safari";
		} else if(Browser.OP) {
			m = Browser.UA.match(/Opera\/([^\s]*)/i);
			v = m[1];
			Browser.version = v.substring(0, v.indexOf("."));
			Browser.versionFull = m[1];
			Browser.name = "Opera";
		} else if(Browser.IE) {
			m = Browser.UA.match(/MSIE\s([^;]*)/i);
			v = m[1];
			Browser.version = v.substring(0, v.indexOf("."));
			Browser.versionFull = m[1];
			Browser.name = "Internet Explorer";
		}
		return Browser;
	})(Browser);

	window.Browser = Browser;
})(window);

/* Extensions */
String.prototype.htmlEncode = function() {
	return (""+ this)
		.replace(/&/gi, "&amp;")
		.replace(/"/gi, "&quot;")
		.replace(/'/gi, "&#039;")
		.replace(/</gi, "&lt;")
		.replace(/>/gi, "&gt;");
};
String.prototype.htmlDecode = function() {
	return (""+ this)
		.replace(/&amp;/gi, "&")
		.replace(/&quot;/gi, "\"")
		.replace(/&#039;/gi, "'")
		.replace(/&lt;/gi, "<")
		.replace(/&gt;/gi, ">");
};

