/**
 * 샵쪽에서 사용할 공통 JS모음
 */

/**
 * 이벤트팝업창 뛰우기
 * 실제팝업, 레이어팝업창을 띄우는 역활을 한다
 * @param event_id : 이벤트의 DB PK값
 * @param option : 팝업창의 옵션사항들 JSON형식임
 * @return void
 */
function popupWindow(event_id, option) {
    // 팝업창 또는 DIV, 쿠키값으로 사용할 값을 구한다
    var w_id = getPopupId(event_id);

    // 쿠키가 셋팅되어 있으면 팝업창을 띄우지 않음
    if (Cookies.get(w_id) == 1) {
        return false;
    }

    // 이벤트 내용을 보여줄 URL 정의
    var event_url = '/event.html?event_id=' + event_id;

    // 레이어팝업 여부를 확인하여 팝업창울 띄운다
    if (option.size_width < 260) {
        option.size_width = 260;
    }
    if (option.layer_yn == 'N') {
        var w_option = 'width=' + option.size_width + ', height=' + option.size_height + ', left=' + option.left_location + ', top=' + option.top_location + ', resizable=no, scrollbars=yes, status=no';
        window.open(event_url, w_id, w_option);
    } else {
        var layer_window = new Element('div', {id:w_id}).setStyle({backgroundColor:'#FFF', height:option.size_height + 'px', width:option.size_width + 'px', position:'absolute', top:option.top_location + 'px', left:option.left_location + 'px'}).update();
        $('body').appendChild(layer_window);
        new Ajax.Updater(layer_window, event_url, {asynchronous:false, method:'get'});
    }
}

/**
 * 떠있는 이벤트 팝업창을 닫는다
 * 팝업창 다시 보기 구분에 따라서 쿠키를 셋팅하고 창을 닫거나, 레이어(DIV)를 숨긴다
 * @param event_id : 이벤트 아이디
 * @param option : 이벤트 정보 JSON형식
 * @return void
 */
function closeEvent(event_id, option) {
    // 쿠키를 셋팅해서.. 다시 열리지 않게 한다
    if (option.option_type == '01' && $('close_check').checked) {
        Cookies.set(getPopupId(event_id), '1', 1);
    } else if (option.option_type == '02' && $('close_check').checked) {
        Cookies.set(getPopupId(event_id), '1', 365);
    }

    // 레이어팝업창 여부를 확인하여 팝업창이면 창닫기, 레이어면 해당 DIV를 삭제를 시킨다
    if (option.layer_yn == 'N') {
        window.close();
    } else {
        $(getPopupId(event_id)).remove();
    }
}

/**
 * 이벤트 팝업창 관련 window_name 및 div 의 id로 쓸 값을 구한다
 */
function getPopupId(event_id) {
    return 'event_' + event_id;
}

/**
  * 달력의 날짜를 조정하는 함수
  * to 날자를 오늘로 기준하여 몇일전을 from에다 넣는 함수
  */
function changeDate(term, option) {
    var from_obj = $(option.from);
    var to_obj = $(option.to);
    var sp = '/';
    
    if (term == 'all') {
        from_obj.value = '';
        to_obj.value = '';
        return;
    }
            
    var now = new Date();
    var c_year = now.getFullYear();
    var c_month = now.getMonth() + 1;
    var c_day = now.getDate();
    var f_date = new Date(c_year, c_month, c_day - term);
    var f_year = f_date.getFullYear();
    var f_month = f_date.getMonth();
    var f_day = f_date.getDate();
    to_obj.value = c_year + sp + c_month.toPaddedString(2) + sp + c_day.toPaddedString(2);
    from_obj.value = f_year + sp + f_month.toPaddedString(2) + sp + f_day.toPaddedString(2);
    return;
}


/**
 * 쿠키 관련 함수
 * prototype이 필요한 함수
 * Cookies.set('name', 'value', 1);
 * Cookies.get('name');
 * Cookies.remove('name');
 */
var Cookies = {
    set:function(n, v, d) {
        var g = "";
        if (d != undefined) {
            var f = new Date();
            f.setTime(f.getTime()+(d*24*60*60*1000));
            g = "; expires=" + f.toGMTString();
        };
        document.cookie = escape(n) + "=" + escape(v || '') + g;
    },

    get:function(n) {
        var a = n+"=";
        var r = null;
        document.cookie.split(';').each(function(s) {
            while(s.charAt(0) == ' ') {
                s = s.substring(1, s.length);
            }
            if(s.indexOf(a) == 0) {
                r=s.substring(a.length, s.length);
            }
        });
        return r;
    },

    remove:function(n) {
        this.set(n, '', -1);
        return this.get(n) || true;
    }
}

/**
 * 로그인팝업창을 띄움
 * 만일 이 로그인창이 보안서버로 떠야 할경우 어떻게 할지??
 */
function loginWindow(url, next_url) {
    window.open(url, 'login_window', 'width=450, height=420, scrollbars=yes');
}

/**
 * 아이디찾기 팝업창
 */
function findIdWindow(url, next_url, close) {
    window.open(url, 'findid_window', 'width=450, height=420, scrollbars=yes');
    if (close == true) {
        window.close();
    }
}

/**
 * 비밀번호 팝업창
 */
function findPasswordWindow(url, next_url, close) {
    window.open(url, 'findpasswd_window', 'width=450, height=420, scrollbars=yes');
    if (close == true) {
        window.close();
    }
}



function MS_Flash(fid,src,wid,hei,fvs,wmd) { 
    this.fPrint = ''; 
    this.Id = document.getElementById(fid); 
    this.Src = src; 
    this.Width = wid; 
    this.Height = hei; 
    this.FlashVars = ( typeof fvs != 'undefined')? fvs :''; 
    this.Wmod = ( typeof wmd != 'undefined')? wmd :''; 
    if(isObject(Id)) { 
        fPrint = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0"'; 
        fPrint += ' width="'+Width+'"'; 
        fPrint += ' height="'+Height+'">'; 
        fPrint += '<param name="movie" value="'+Src+'">'; 
        fPrint += '<param name="quality" value="high">'; 
        fPrint += '<param name="AllowScriptAccess" value="always" />';
        fPrint += (FlashVars != null) ? '<param name="FlashVars" value="'+FlashVars+'">' : ''; 
        fPrint += (Wmod != null) ? '<param name="wmode" value="'+Wmod+'">' : ''; 
        fPrint += '<embed'; 
        fPrint += ' src="'+Src+'"'; 
        fPrint += (FlashVars != null) ? ' FlashVars="'+FlashVars+'"' : ''; 
        fPrint += (Wmod != null) ? ' wmode="'+Wmod+'"' : ''; 
        fPrint += ' quality="high"'; 
        fPrint += ' pluginspage="http://www.macromedia.com/go/getflashplayer"'; 
        fPrint += ' type="application/x-shockwave-flash"'; 
        fPrint += ' width="'+Width+'"'; 
        fPrint += ' height="'+Height+'"'; 
        fPrint += ' AllowScriptAccess="always"></embed>'; 
        fPrint += '</object>'; 
        Id.innerHTML = fPrint; 
    } 
} 

function isObject(a) {
    return (a && typeof a == 'object');
}

function MS_Embed() 
{ 
    var obj = new String; 
    var parameter = new String; 
    var embed = new String; 
    var html = new String; 
    var allParameter = new String; 
    var clsid = new String; 
    var codebase = new String; 
    var pluginspace = new String; 
    var embedType = new String; 
    var src = new String; 
    var width = new String; 
    var height = new String; 


    this.init = function( s ,w , h, getType, wmode ) { 
        getType = (getType != undefined)? getType :'flash'; 
        wmode = (wmode != undefined)? wmode :'opaque'; 
        if ( getType == "flash") 
        { 

            clsid = "D27CDB6E-AE6D-11cf-96B8-444553540000";        
            codebase = "http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0"; 
            pluginspage = "http://www.macromedia.com/go/getflashplayer"; 
            embedType = "application/x-shockwave-flash"; 
        } 
        /* type 추가 
           else if ( ) 
           { 
           } 
         */ 

        parameter += "<param name='movie' value='"+ s + "'>\n";  
        parameter += "<param name='quality' value='high'>\n";    
        parameter += "<param name='AllowScriptAccess' value='always' />\n";    
        parameter += "<param name='wmode' value='"+ wmode +"' />\n";    

        src = s; 
        width = w; 
        height = h; 
    } 

    this.parameter = function( parm , value ) {      
        parameter += "<param name='"+parm +"' value='"+ value + "'>\n";        
        allParameter += " "+parm + "='"+ value+"'"; 
    }  

    this.show = function() { 
        if ( clsid ) 
        { 
            obj = "<object classid=\"clsid:"+ clsid +"\" codebase=\""+ codebase +"\" width='"+ width +"' height='"+ height +"'>\n"; 
        } 

        embed = "<embed src='" + src + "' pluginspage='"+ pluginspage + "' type='"+ embedType + "' width='"+ width + "' height='"+ height +"'"+ allParameter +" AllowScriptAccess='always'></embed>\n"; 

        if ( obj ) 
        { 
            embed += "</object>\n"; 
        } 

        html = obj + parameter + embed; 

        document.write( html );  
    } 

} 

function activemovie(str, wid, hei) {
    document.write(" <object src='"+str+"' width='"+wid+"' height='"+hei+"'></object>")
}

var selected_obj = null;
function choice_color(obj, path, event) {
    selected_obj = obj;
    var color = obj.value;
    if (color.length == 0) {
        color = "FFFFFF";
    } else {
        color = color.substring(1);
    }
    MS_Flash('color_picker',path + '/makeshop_picker.swf?mc_color=' + color,260,400,'','Transparent');
    var dim = Element.cumulativeOffset(obj);
    with ($('color_picker_div').style) {
        left = (dim[0] + obj.offsetWidth)  + 'px';
        top = dim[1]  + 'px';
    }
    $("color_picker_div").toggle();
    
}
function ValidateColor(string) {                // return valid color code
  string = string || '';
  string = string + "";
  string = string.toUpperCase();
  chars = '0123456789ABCDEF';
  out   = '';

  for (i=0; i<string.length; i++) {             // remove invalid color chars
    schar = string.charAt(i);
    if (chars.indexOf(schar) != -1) { out += schar; }
  }

  if (out.length != 6) { return null; }            // check length
  return out;
}
function Set(color){ // select color
    selected_obj.value = '#' + color;
    $("color_picker_div").toggle();
    $(selected_obj).focus();
}

/**
 * 회원가입시에 사용되는 주소찾기 팝업창 띄우기 함수
 */
function findZipcode() {
    window.open('/zipcode.html', 'zipcode_window', 'width=450, height=400');
}

// parseUri 1.2.2
// (c) Steven Levithan <stevenlevithan.com>
// MIT License
function parseUri (str) {
    var o   = parseUri.options,
        m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
        uri = {},
        i   = 14;

    while (i--) uri[o.key[i]] = m[i] || "";

    uri[o.q.name] = {};
    uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
        if ($1) uri[o.q.name][$1] = $2;
    });

    return uri;
};
parseUri.options = {
    strictMode: false,
    key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
    q:   {
        name:   "queryKey",
        parser: /(?:^|&)([^&=]*)=?([^&]*)/g
    },
    parser: {
        strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
        loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
    }
};
