var global_domain = "gioo.com";
var global_siteid = "10000727";

function winOpen(_u, _name, _w, _h){
	var myWin = window.open(_u,_name,"toolbar=0,location=0,status=1,menubar=0,scrollbars=1,resizable=1,width=" + _w + ",height=" + _h + "");
	myWin.focus();
}


// 트위터 인증창열기
function oauthOpen(oauth_mode){
	var auto_login = document.getElementById("auto_login");
	if (auto_login)
	{
		if (auto_login.checked)
		{
			setCookie("alc","1",365);
		}else{
			setCookie("alc","0",365);
		}
	}
	window.open('/oauth/oauth_authorize.html?oauth_mode='+oauth_mode, 'oauthWin','width='+800+', height='+600);
}

function setCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/;domain=" + global_domain;
}

function getCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function delCookie(name) {
	setCookie(name,"",-1);
}

function changeCol(col){
	setCookie("view_col",col,9999);
	document.location.reload();
}

function changeCountry(c){
	var curLocationArr = document.location.toString().split("\/");
	if (curLocationArr.length >= 3)
	{
		curLocationArr[2] = c + "." + global_domain;
	}
	setCookie("lang", c, 365);
	document.location.href = curLocationArr.join("\/").toString();
}

function changeRows(n){
	setCookie("rows", n, 365);
	document.location.reload();
}

function qfocus(){
	var q = document.getElementsByName("q");
	if (q[0])
	{
		q[0].focus();	
	}
}

function thumbError(obj){
	obj.style.display = "none";
}


function thumbResize(sourceWidth, sourceHeight, boxWidth, boxHeight, boxMode){
	var nPercentW, nPercentH, nPercent, targetWidth, targetHeight;
	nPercentW = boxWidth / sourceWidth;
	nPercentH = boxHeight / sourceHeight;
	switch (boxMode){
		case 1:
			if(nPercentW > nPercentH){
				nPercent = nPercentH;
			}else{
				nPercent = nPercentW;
			}
			break;
		case 2:
			if(nPercentW < nPercentH){
				nPercent = nPercentH;
			}else{
				nPercent = nPercentW;
			}
			break;
	}
	targetWidth = Math.round(sourceWidth * nPercent);
	targetHeight = Math.round(sourceHeight * nPercent);
	if(targetWidth > sourceWidth || targetHeight > sourceHeight){
		targetWidth = sourceWidth;
		targetHeight = sourceHeight;
	}
	return Array(targetWidth, targetHeight);
}

// explorer는 filters에 alpha(opacity='1-100')로 써줘야함..귀찮네
function setOpacity(el, opacity){
	if(el.filters){
		el.style.filter = 'alpha(opacity=' + opacity * 100 + ')';
	} else {
		el.style.opacity = opacity;
	}	
}

hidden_resizing = function(){
//<-- hiddenLayer크기 조절 -->
	if (document.getElementById('hiddenLayer'))	{
		if (document.documentElement.scrollHeight > document.body.scrollHeight) {
			document.getElementById('hiddenLayer').style.height = document.documentElement.scrollHeight + 'px';
		} else { 
			document.getElementById('hiddenLayer').style.height = document.body.scrollHeight + 'px';
		}

		document.getElementById('hiddenLayer').style.width = document.body.scrollWidth + 'px';

		setOpacity($('hiddenLayer'), 0.1);	
	}
}


// 로그인클릭
function clickLogin(){
	var cur_url = document.location;
	document.location.href = "/user/login.html?r=" + encodeURIComponent(cur_url);
}


// 회원가입클릭
function clickJoin(){
	var cur_url = document.location;
	document.location.href = "/user/join_select.html?r=" + encodeURIComponent(cur_url);
}


// 일반검색, 트위터검색
function searchType(f_id, f_action, focus_id, blur_id){
	if ($(focus_id) && $(blur_id))
	{
		$(focus_id).className = "selected";
		$(blur_id).className = "";
	}
	if ($(f_id))
	{
		$(f_id).action = f_action;
		$("q").focus();
	}
	return false;
}

function urlEncode(str) {
	str = escape(str);
	str = str.replace('+', '%2B');
	str = str.replace('%20', '+');
	str = str.replace('*', '%2A');
	str = str.replace('/', '%2F');
	str = str.replace('@', '%40');
	return str;
}

Array.prototype.has = function(value) {
	var i;
	for (var i = 0, loopCnt = this.length; i < loopCnt; i++) {
		if (this[i] === value) {
			return true;
		}
	}
	return false;
};


(function($){
	$(function(){	
		$(".moreMenu").bind("click", function(){
			if ($("#top_add").css("display") == "none")	{
				$("#top_add").show();
			}
			else {
				$("#top_add").hide();
			}
		});		
		$(".add_link").bind("click",add_link_click);		
	});

	$.fn.toHtml = function(){
		return this.wrapAll("<div></div>").parent().html();
	};
	$.alertTop = function(str){
		if ($("#alertTop").size() == 0)
		{
			$("body").prepend('<div id="alertTop"></div>');
		}
		var alert_count = $("#alertTop div").size();
		$("#alertTop").append('<div id="alert_'+alert_count+'">'+str+'</div>').find('#alert_'+alert_count).css("opacity", "0.8").hide().slideDown("slow",function(){
			setTimeout(function(){$('#alert_'+alert_count).slideUp("slow", function(){$(this).remove();});},5000);
		});
	};
	$.fn.focusEnd=function(){
		return this.each(function(){
			var A=this;
			if(A.style.display!="none"){
				if($.browser.msie){
					A.focus();
					var B=A.createTextRange();
					B.collapse(false);B.select()
				}
				else{
					A.setSelectionRange(A.value.length,A.value.length);A.focus()
				}
			}
		})
	};
	$.fn.focusStart=function(){
		return this.each(function(){
			var A=this;
			if(A.style.display!="none"){
				if($.browser.msie){
					A.focus();var B=A.createTextRange();B.collapse(true);B.select()
				}
				else{
					A.setSelectionRange(0,0);A.focus()
				}
			}
		})
	};

	logout = function(){
		$.ajax({
		  type: "GET",
		  url: "/user/logout.html",
		  success: function(){ location.reload(); }
		});		
	}	

	show_login = function(){	
		oauthOpen('twitter_login');		
	}

	add_link_click = function(){		
		var mode = "add_link_click";
		var obj = eval("(" + $(this).attr("data") + ")");
		var idx = obj.idx;
		var _url = "/link/index.html";
		var _data = {
			mode:mode,
			idx:idx
		}
		$.ajax({
			type:"post",
			url:_url,
			data:_data,
			success:function(msg){ },
			error:function(){ alert("error!!!"); }			
		});
	}	
})(jQuery);






var pMenu = {};
pMenu.mItem = [];
pMenu.mTime = [];
pMenu.mWait = 250;
pMenu.mSet = function(ul){
	if (document.getElementById(ul)) {
		ul = document.getElementById(ul).getElementsByTagName('ul');
		var i, j, e, a, f, b;
		var m = pMenu.mItem.length;
		for (i = 0; i < ul.length; i++) {
			if (e = ul[i].getAttribute('id')) {
				pMenu.mItem[m] = e;
				e = ul[i].parentNode;
				f = new Function('pMenu.mShow(\'' + pMenu.mItem[m] + '\');');
				b = new Function('pMenu.mBlur(\'' + pMenu.mItem[m] + '\');');
				e.onmouseover = f;
				e.onmouseout = b;
				a = e.getElementsByTagName('a');
				for (j = 0; j < a.length; j++) {
					a[j].onfocus = f;
					a[j].onblur = b;
				}
				m++;
			}
		}
	}
}



pMenu.mShow = function(id) {
	for (var i = 0; i < pMenu.mItem.length; i++) {
		if (document.getElementById(pMenu.mItem[i]).style.display != 'none') {
			if (pMenu.mItem[i] != id) mShow.mHide(pMenu.mItem[i]);
			else pMenu.mClear(pMenu.mItem[i]);
		}
	}
	document.getElementById(id).style.display = 'block';
}


pMenu.mHide = function(id) {
	pMenu.mClear(id);
	document.getElementById(id).style.display = 'none';
}


pMenu.mBlur = function(id) {
	pMenu.mTime[id] = setTimeout('pMenu.mHide(\'' + id + '\');', pMenu.mWait);
}


pMenu.mClear = function(id) {
	if (pMenu.mTime[id]) {
		clearTimeout(pMenu.mTime[id]);
		pMenu.mTime[id] = null;
	}
}

/**
* string String::cut(int len)
* 글자를 앞에서부터 원하는 바이트만큼 잘라 리턴합니다.
* 한글의 경우 2바이트로 계산하며, 글자 중간에서 잘리지 않습니다.
*/
String.prototype.cut = function(len) {
	var str = this;
	var l = 0;
	for (var i=0; i<str.length; i++) {
		l += (str.charCodeAt(i) > 128) ? 2 : 1;
		if (l > len) return str.substring(0,i);
	}
	return str;
}

// 바이트단위로 자르고 남은값 반환.
String.prototype.left = function(len) {
	var str = this;
	var l = 0;
	var maxlength = this.length;
	if (len >= maxlength) return "";
	for (var i=0; i<str.length; i++) {
		l += (str.charCodeAt(i) > 128) ? 2 : 1;
		if (l > len) return str.substring(i,maxlength);
	}
	return str;
}

/**
* bool String::bytes(void)
* 해당스트링의 바이트단위 길이를 리턴합니다. (기존의 length 속성은 2바이트 문자를 한글자로 간주합니다)
*/
String.prototype.bytes = function() {
	var str = this;
	var l = 0;
	for (var i=0; i<str.length; i++) l += (str.charCodeAt(i) > 128) ? 2 : 1;
	return l;
}

// Return new array with duplicate values removed
Array.prototype.unique = function() {
	var a = [];
	var l = this.length;
	for(var i=0; i<l; i++) {
		for(var j=i+1; j<l; j++) {
			// If this[i] is found later in the array
			if (this[i] === this[j])
			j = ++i;
		}
		a.push(this[i]);
	}
	return a;
};

alert_error = function(){
	alert("error!!!");
}

convert_kr = function(str){
	if (str == "Status is a duplicate."){
		str = "중복된 글입니다";
	}
	else if (str == "No status found with that ID."){
		str = "해당글을 찾을수 없습니다";
	}
	else if (str == "You cannot send messages to users who are not following you."){
		str = "당신을 팔로우 하지 않은 사람에게 메세지를 보낼수 없습니다.";
	}
	else if (str == "Not found"){
		str = "대상이 없습니다";
	}
	else if (str == "Share sharing is not permissable for this status (Share validations failed)"){
		str = "이미 리트윗하셨거나 리트윗할수 없는 트윗입니다";
	}
	else if (str == "You have already favorited this status."){
		str = "이미 관심글에 등록되어있습니다.";
	}
	else if (str == "A user can only have 20 lists."){
		str = "리스트는 20개까지 생성할수 있습니다.";
	}
	else if (str == "You are not subscribed to this list"){
		str = "당신은 이 리스트에 가입되어 있지 않습니다.";
	}
	else if (str == "A list's name must start with a letter and consist only of 25 or fewer letters, numbers, '-', or '_' characters."){
		str = "리스트 이름은 숫자 또는 '-', '_' 로 시작할수 없습니다. ";
	}
	else if (str == "Could not follow user: You have been blocked from following this account at the request of the user."){
		str = "팔로우할수 없습니다. 이 계정으로부터 블록된 상태입니다";
	}
	else if (str == "Could not follow user: You can't follow yourself!"){
		str = "자기 자신을 팔로우 할 수 없습니다.";
	}
	return str;
}
