﻿// 블로그, 알라딘 마을에 공통으로 쓰임 - prototype기반
/* Browser 판단 */
var userAgent = navigator.userAgent.toLowerCase();
var isIE = userAgent.indexOf("msie")!=-1;
var isIE7 = userAgent.indexOf("msie 7")!=-1;
var isIE8 = userAgent.indexOf("msie 8")!=-1;
var isGecko = userAgent.indexOf("gecko")!=-1;
var isOpera = userAgent.indexOf("opera")!=-1;
var PATTERN_COOKIESCRIPTS = '(?:<script[^>].*?>)((\n|\r|.)([^<])*?)(cookie+)((\n|\r|.)*?)(?:<\/script>)';

//String 확장 st----------------------------------------------------------------- 
Object.extend(String.prototype, {
  
  //script 태그 안에 cookie가 사용된경우 스크립트를 제거 하여 반환 
  stripCookieScripts: function() {
      return this.replace(new RegExp(PATTERN_COOKIESCRIPTS, 'img'), '');
  },
  
  trim : function () {
	   return trim(this);
  } 
  
});

function trim(str){
    return str.replace(/(^\s*)|(\s*$)/g, ""); 
}
//스트링 확장 end----------------------------------------------------------------- 

Element.copy4Style = function(sourceElement, targetElement, styleName) { 
        /* margin이나 block같은 4방위 객체를 복사할때, 하드코딩보다 효율적인 것이 없음 */
        if(styleName=='padding') {
            Element.setStyle(targetElement, {
                'padding-top' : Element.getStyle(sourceElement, 'padding-top'),
                'padding-right' : Element.getStyle(sourceElement, 'padding-right'),
                'padding-bottom' : Element.getStyle(sourceElement, 'padding-bottom'),
                'padding-left' : Element.getStyle(sourceElement, 'padding-left')
            });
        } else if(styleName=='margin') {
            Element.setStyle(targetElement, {
                'margin-top' : Element.getStyle(sourceElement, 'margin-top'),
                'margin-right' : Element.getStyle(sourceElement, 'margin-right'),
                'margin-bottom' : Element.getStyle(sourceElement, 'margin-bottom'),
                'margin-left' : Element.getStyle(sourceElement, 'margin-left')
            });        
        }
}

Array.prototype.eachAssign = function(fn){
    for(var i=0; i<this.length; i++){
        this[i] = fn(this[i], i);
    }
};


// 개체 el의 width와 height를 가져옴. Computed한 값을 가져옴
function getWidthAndHeight(el){
    var el = $(el);
    var esw = 0;
    var esh = 0;

    esw = parseInt(Element.getStyle(el, 'width'));
    esh = parseInt(Element.getStyle(el, 'height'));
    
    if(isNaN(esw)) esw = 0;
    if(isNaN(esh)) esh = 0;
    return {'x':esw, 'y':esh};   
}

function getScrollOffset(){
    var x=0;
    var y=0;

    if (self.pageYOffset) {
        // IE 외 모든 브라우저
        x = self.pageXOffset;
        y = self.pageYOffset;
    } else if(document.compatMode && document.compatMode != "BackCompat") {
        // } else if (document.documentElement && document.documentElement.scrollTop) { 이전소스에 문제!
         
        // Explorer 6 Strict
        x = document.documentElement.scrollLeft;
        y = document.documentElement.scrollTop;
    } else if (document.body) { 
        // IE 브라우저
        x = document.body.scrollLeft;
        y = document.body.scrollTop;
    }
    return {'x':x, 'y':y};
}

// 나타났다 사라지는 메세지박스
function OpacityMsg(id, speed, delay, onComplete) {
    this._targetEl = $(id);
    this._hideSpeed = 10000/speed;
    this._delay = delay;
    this._opacity_to = null;
    this._times = 0;
    this._limiter = 0;
    if(typeof(onComplete)=='function')
        this._onComplete = onComplete;
}

OpacityMsg.prototype.hide = function() {
    if(isIE) {
        this._targetEl.style.filter = 'alpha(opacity=100 style=0 finishopacity=0)';
    } else if(isGecko) {
        this._targetEl.style.opacity = '1';
    }            
    this._targetEl.style.display = 'block';
    
    this._times = this._hideSpeed;
    this._opacity_to = setTimeout(this._opacityChange.bind(this), this._delay);
}

OpacityMsg.prototype.show = function() {
    if(isIE) {
        this._targetEl.style.filter = 'alpha(opacity=0 style=0 finishopacity=0)';
    } else if(isGecko) {
        this._targetEl.style.opacity = '0';
    }            
    this._targetEl.style.display = '';
    
    this._limiter = this._hideSpeed;
    this._times = 0;
    this._opacity_to = setTimeout(this._opacityChangeUp.bind(this), this._delay);
}

OpacityMsg.prototype._opacityChange = function(){
    try{
        if(isIE) {
	        this._targetEl.style.filter = 'alpha(opacity='+(100/this._hideSpeed*this._times)+' style=0 finishopacity=0)';
        } else if(isGecko || isOpera) {
	        this._targetEl.style.opacity = parseFloat(1.0/this._hideSpeed*this._times);
        }

        this._times--;
    } catch(ex){}
	
    if(this._times<0) {
        this._opacity_to = null;
        this._targetEl.style.display = 'none';
        if(typeof(this._onComplete)=='function') this._onComplete.call();
        return;
    } else {
        this._opacity_to = setTimeout(this._opacityChange.bind(this), 100);
    }
}

OpacityMsg.prototype._opacityChangeUp = function(){
    try{
        if(isIE) {
	        this._targetEl.style.filter = 'alpha(opacity='+(100/this._hideSpeed*this._times)+' style=0 finishopacity=0)';
        } else if(isGecko || isOpera) {
	        this._targetEl.style.opacity = parseFloat(1.0/this._hideSpeed*this._times);
        }

        this._times++;
    } catch(ex){}
	
    if(this._times>this._limiter) {
        this._opacity_to = null;
        // this._targetEl.style.display = '';
        if(typeof(this._onComplete)=='function') this._onComplete.call();      
        return;
    } else {
        this._opacity_to = setTimeout(this._opacityChangeUp.bind(this), 100);
    }
}

function getCookie( name ){ 
	var nameOfCookie = name + "="; 
	var x = 0; 
	while ( x <= document.cookie.length ){ 
		var y = (x+nameOfCookie.length); 
		if ( document.cookie.substring( x, y ) == nameOfCookie ) { 
			if ( (endOfCookie=document.cookie.indexOf( ";", y )) == -1 ) 
				endOfCookie = document.cookie.length; 

			return unescape( document.cookie.substring( y, endOfCookie ) ); 
		} 
		x = document.cookie.indexOf( " ", x ) + 1; 
		if ( x == 0 ) 
			break; 
	} 
	return ""; 
}

function setCookie( name, value, expiredays ) {
  var endDate = new Date();
  endDate.setDate( endDate.getDate()+ expiredays );
  document.cookie = name + "=" + escape( value ) + "; path=/; expires=" + endDate.toGMTString() + ";"
}

/* prevent memory leaks in IE */
try{ Event.observe(window, 'unload', Event.unloadCache, false); }catch(ex){}


/* 알라딘에 종속적 기능들 */
var topbox_1 = null;
var topbox_2 = null;
var toolbarToggleButton = null;
var marginVal = 0;
var g_marginStart = 30;

function toggleToolbar(){
    topbox_1 = $('topbox_1');
    topbox_2 = $('topbox_2');
    toolbarToggleButton = $('toolbarToggleButton');
    
    isVisibleTopBox = Element.visible(topbox_1);

    var type = 1;
	var parm = document.location.toString();
	if (parm.indexOf('?t2')>=0) type=2;

    if(isVisibleTopBox) {
        // 없애기
        if(type==1) {
            var onComplete = function(){
                topbox_1.style.display = 'none';
                topbox_2.style.display = 'none';
                toolbarToggleButton.src = 'http://image.aladdin.co.kr/img/blog2/button/topbar_open.gif';
                toolbarToggleButton.alt = '툴바보이기';
                toolbarToggleButton.title = '툴바보이기';
                setCookie('toolbarVisible', 'f', 300);
            };
            
            new OpacityMsg('topbox_1', 1100, 300, onComplete).hide();
            new OpacityMsg('topbox_2', 1200, 0).hide();
        } else {
            marginVal = 0;
            setTimeout(toggleToolbar_sliding_hide, 1);
        }
    } else {
        if(type==1) {
            var onComplete = function(){
                toolbarToggleButton.src = 'http://image.aladdin.co.kr/img/blog2/button/topbar_close.gif';
                toolbarToggleButton.alt = '툴바감추기';
                toolbarToggleButton.title = '툴바감추기';
                setCookie('toolbarVisible', 't', 300);          
            };        
            new OpacityMsg('topbox_1', 1100, 0, onComplete).show();
            new OpacityMsg('topbox_2', 1200, 300).show();
        } else {
            topbox_1.style.display = '';
            topbox_2.style.display = '';           
            marginVal = -1 * g_marginStart;
            setTimeout(toggleToolbar_sliding_show, 1);
        }
    }
}

function toggleToolbar_sliding_hide(){
    if(marginVal<(-1* g_marginStart)) {
        topbox_1.style.display = 'none';
        topbox_2.style.display = 'none';
        toolbarToggleButton.src = 'http://image.aladdin.co.kr/img/blog2/button/topbar_close.gif';
        toolbarToggleButton.alt = '툴바보이기';
        toolbarToggleButton.title = '툴바보이기';
        return;
    }
    topbox_1.style.marginTop = marginVal+'px';
    topbox_2.style.marginTop = marginVal+'px';
    marginVal--;
    
    setTimeout(toggleToolbar_sliding_hide, 1);
}

function toggleToolbar_sliding_show(){
    if(marginVal>0) {
        toolbarToggleButton.src = 'http://image.aladdin.co.kr/img/blog2/button/topbar_open.gif';
        toolbarToggleButton.alt = '툴바감추기';
        toolbarToggleButton.title = '툴바감추기';        
        return;
    }
    topbox_1.style.marginTop = marginVal+'px';
    topbox_2.style.marginTop = marginVal+'px';
    marginVal++;

    setTimeout(toggleToolbar_sliding_show, 1);
}



function ForceError(msg, url, lno){
	var parm = document.location.toString();
	if (parm.indexOf('?debug')>=0) alert('주소:'+url+'\n라인:'+lno+'\n에러메시지:'+msg);
	//if(console && console.log) console.log('주소:'+url+'\n라인:'+lno+'\n에러메시지:'+msg);
	return true;
}

window.onerror = ForceError;

          

/* 부모의 Iframe 사이즈를 조정할때 사용함 */
function fReSize(iframeID) {
  try {
    var objFrame = parent.document.getElementsByName(iframeID)[0]; //부모창의 iframe 이름 받아오는것
    var objBody = document.body; 
        
    ifrmHeight = objBody.scrollHeight + (objBody.offsetHeight - objBody.clientHeight); 
    if (ifrmHeight > 0) {
     objFrame.style.height = ifrmHeight; 
   }
 } catch(e) {
   //fReSize();
 }
}

// Select Box에서 선택하면 자동으로 페이지 이동되게
function goURLBySelectBox(selectBox, prefix) {
    if(!selectBox) return;
    var index = selectBox.selectedIndex;
    if (index < 0) return;
    var selectedObj = selectBox.options[index];
    var value = selectedObj.value;
    if (!value && !('value' in opt))
        value = opt.text;

    location.href = prefix + value;    
} 

// SELECT BOX에서 value를 기준으로 select하게 만든다.
function selectByValue(selectOid, val){
	var o = $(selectOid);
	if(o){
		for(var i=0; i<o.length; i++){
			if(o[i].value==val){
				o[i].selected = true;
				return;
			}
		}
	}
}

// ie 북마크 추가
function bookmark(title,url){ 
    if(window.sidebar){ // 파폭
       window.sidebar.addPanel(title, url, "");
    }else if(window.opera && window.print){ // 오페라
          var obj = document.createElement('a');
          obj.setAttribute('href',url);
          obj.setAttribute('title',title);
          obj.setAttribute('rel','sidebar');
          obj.click();
    }else if(document.all){ // 익스
       window.external.AddFavorite(url, title);
    }else{
        alert('죄송합니다. 사용하시는 브라우저는 북마크 기능이 지원되지 않습니다.');
    }
}



