﻿/**** Ajax 관련 함수 시작 ****/
var ajax = {};
ajax.xhr = {};

ajax.xhr.Request = function(url, params, callback, method, seq) {
    this.url = url;
    this.params = params;
    this.callback = callback;
    this.method = method;
    this.send();
    this.seq = seq
}
ajax.xhr.Request.prototype = {
    getXMLHttpRequest: function() {
        if (window.ActiveXObject) {
            try {
                return new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    return new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e1) { return null; }
            }
        } else if (window.XMLHttpRequest) {
            return new XMLHttpRequest();
        } else {
            return null;
        }
    },
    send: function() {
        this.req = this.getXMLHttpRequest();

        var httpMethod = this.method ? this.method : 'GET';
        if (httpMethod != 'GET' && httpMethod != 'POST') {
            httpMethod = 'GET';            
        }
        var httpParams = (this.params == null || this.params == '') ?
		                 "TimeStamp=" + new Date().getTime() : this.params + "&TimeStamp=" + new Date().getTime();

        var httpUrl = this.url;
        if (httpMethod == 'GET' && httpParams != null) {
            httpUrl = httpUrl + "?" + httpParams;
        }
        this.req.open(httpMethod, httpUrl, true);
        this.req.setRequestHeader(
			'Content-Type', 'application/x-www-form-urlencoded');
        var request = this;
        this.req.onreadystatechange = function() {
            request.onStateChange.call(request);
        }
        this.req.send(httpMethod == 'POST' ? httpParams : null);

    },
    onStateChange: function() {
        this.callback(this.req, this.seq);
    }
}
/**** Ajax 관련 함수 끝 ****/

/**** 문자열 공백 제거 ****/
String.prototype.trim = function() {
       return this.replace(/^\s+|\s+$/g,"");   
}

/**** 비로그인 & 로그인 박스 포커싱 ****/
function IsNotLoginBoard() {
    alert('로그인을 하셔야 게시물을 작성할 수 있습니다.');
    try {
        document.getElementById("txtUserID").focus();
    } catch (err) {
        return false;
    }
    return false;
}

function IsNotLoginComment() {
    alert('꼬릿글 작성을 위해 먼저 로그인을 해 주세요.');
    try {
        document.getElementById("txtUserID").focus();
    } catch (err) {
        return false;
    }
    return false;
}

function IsNotPAgreeBoard() {
    alert('게시물 작성을 위해 먼저 부모님의 동의가 필요합니다.\r\n로그인 박스의 동의센터 바로 가기 버튼을 눌러주세요.');
    return false;
}

function IsNotPAgreeVote() {
    alert('투표를 위해 먼저 부모님의 동의가 필요합니다.\r\n로그인 박스의 동의센터 바로 가기 버튼을 눌러주세요.');
    return false;
}

function IsNotPAgreeComment() {
    alert('꼬릿글 작성을 위해 먼저 부모님의 동의가 필요합니다.\r\n로그인 박스의 동의센터 바로 가기 버튼을 눌러주세요.');
    return false;
}

/**** 문자열 공백 제거 ****/
//var xx = "  포인트 : 30,000 결제 성공  ";
//alert(xx);
//alert("<" + xx.trim() + ">");
//alert("<" + xx.trim("포인트:,") + ">");
//alert("<" + xx.ltrim("포인트: ") + ">");
//alert("<" + xx.rtrim("결제성공 ") + ">"); 

String.prototype.trim = function(chars) {
    if (chars) {
        var str = "[" + chars + "\\s]+";
        return this.replace(new RegExp(str, "g"), "");
    }
    return this.replace(/^\s+|\s+$/g, "");
}
String.prototype.ltrim = function(chars) {
    if (chars) {
        var str = "^[" + chars + "\\s]+";
        return this.replace(new RegExp(str, "g"), "");
    }
    return this.replace(/^\s+/, "");
}
String.prototype.rtrim = function(chars) {
    if (chars) {
        var str = "[" + chars + "\\s]+$";
        return this.replace(new RegExp(str, "g"), "");
    }
    return this.replace(/\s+$/, "");
}   

/**** 한글 바이트 체크 하기 ****/
String.prototype.bytes = function() {
    var str = this;
    return str.replace(/[^\x00-\x7F]/g, "xx").replace(/([<\x0D])/g, function($0, $1) { return ($1 == "<") ? "&lt;" : "<br>" + $1; }).length;
}

String.prototype.cut = function(len, tail) {
    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) + tail;
    }
    return str;
}

// 쿠키 설정
function SetCookie( name, value, expiredays )
{
	var todayDate = new Date();
	todayDate.setHours( todayDate.getHours() + expiredays );
	document.cookie = name + "=" + escape( value ) + "; path=/; expires=" + todayDate.toGMTString() + ";"
}

// 쿠키 불러오기
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));
}

function copyClipboard(str) {
    if (document.selection) {
        bResult = window.clipboardData.setData("Text", str);
        if (bResult) alert('클립보드에 저장되었습니다.');
    } else {
        str = encodeforFlash(str);
        var flashcopier = 'flashcopier';
        if (!document.getElementById(flashcopier)) {
            var divholder = document.createElement('div');
            divholder.id = flashcopier;
            document.body.appendChild(divholder);
        }
        document.getElementById(flashcopier).innerHTML = '';
        var divinfo = '<embed src="_clipboard.swf" FlashVars="clipboard=' + str + '" width="1" height="1" type="application/x-shockwave-flash"></embed>';
        document.getElementById(flashcopier).innerHTML = divinfo;
        alert('클립보드에 저장되었습니다.');
    }
}

function encodeforFlash(str) {
    var SAFECHARS = "0123456789" +
                  "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
                  "abcdefghijklmnopqrstuvwxyz" +
                  "-_.!~*'()";

    var HEX = "0123456789ABCDEF";

    var plaintext = str;
    var encoded = "";
    for (var i = 0; i < plaintext.length; i++) {
        var ch = plaintext.charAt(i);
        if (ch == " ") {
            encoded += "+";
        } else if (SAFECHARS.indexOf(ch) != -1) {
            encoded += ch;
        } else {
            var charCode = ch.charCodeAt(0);
            if (charCode > 255) {
                encoded += ch;
            } else {
                encoded += "%";
                encoded += HEX.charAt((charCode >> 4) & 0xF);
                encoded += HEX.charAt(charCode & 0xF);
            }
        }
    }
    return encoded;
}; 


/**** 메뉴 링크 ****/
function flash_link(link_value)
{
	switch( link_value.toString() )
	{
	    case "10": location.href = "/Main/HomeMain.aspx";                   // 홈
	        break;
	    case "50": RunGameStart();                                                // 게임시작버튼
	        break;
	    case "60": location.href = "/Download/Download.aspx";              // 게임 다운로드
	        break;
	    case "70": location.href = "/Guide/Default.aspx";                       // 게임 가이드
            break;

        case "100":
        case "110": location.href = "/News/NewsList.aspx";                    // 새소식
            break;
        case "120": location.href = "/News/Event/EventList.aspx";             // 이벤트
            break;

        case "200":
        case "210":
            location.href = "/Ranking/RankingMemberStyle.aspx";            // 클랜 랭킹            
            break;
        case "220":
            location.href = "/Ranking/HallofFame.aspx";                        // 명예의 전당
            break;

        case "300":
        case "310":
            location.href = "/Clan/Default.aspx";                                     // 클랜 메인
            break;
        case "320":
            location.href = "/Clan/ClanSearch.aspx";                                // 클랜전 상황실
            break;
        case "330":
            location.href = "/Clan/ClanBoard/ClanBoardList.aspx";                 // 클랜 게시판
            break;
        case "340":
            location.href = "/Clan/MakeClan/MakeClan.aspx";                     // 클랜 개설
            break;            

        case "400":
        case "410": location.href = "/Community/FreeBoard/FreeBoardList.aspx";          // 자유게시판 
            break;
        case "420": location.href = "/Community/ScreenShot/ScreenShotList.aspx";     // 동영상/스크린샷
            break;
        case "430": location.href = "/Community/GMBoard/GMBoardList.aspx";        // GM통신소
            break;
        case "440": location.href = "/Community/Poll/PollList.aspx";                                 // 설문조사
            break;
        case "450": location.href = "/Community/QuakerStory/QuakerStory.aspx";            // 퀘이크스토리
            break;

        case "500": location.href = "/Guide/Default.aspx";                                                              // 가이드 메인
            break;
        case "510": window.open("/NewbieGuide/GuideMain.aspx", 'nguide', 'width=900,height=650');          // 초보자 가이드
            break;
        case "520": window.open("/Guide/Feature/GuideSynopsis.aspx", "feature", "width=900,height=650");    // 게임 가이드
            break;       

        case "600":
        case "610": location.href = "/Support/Faq/FaqList.aspx";       // 자주묻는질문
            break;
        case "620": location.href = "/Support/Inquiry/InquiryWrite.aspx";            //  1:1문의
            break;
        case "630": location.href = "/Support/Policy/Policy.aspx";       // 운영정책
            break;

        case "700":
        case "710": location.href = "/ItemShop/ShopList.aspx";       // 아이템샵
            break;
        case "720": location.href = "/ItemShop/MyItemBox.aspx";    // 보관함
            break;
        case "800":
        case "810": location.href = "/Download/Download.aspx";    // 다운로드
            break;
        case "820": location.href = "/Download/Media.aspx";         // 멀티미디어 
            break;
        case "1000": location.href = "/Download/Media.aspx";   // 메인 동영상
            break;

		default : alert(link_value);		
	}
}

function RunGameStart() {
    var isLogin = GetCookie("FPSCamp");
    if (isLogin == "" || isLogin == null) {
        alert('로그인 후 이용 가능합니다.');
        document.getElementById("txtUserID").focus();
        return false;
    }
    else 
    {    
        frames['ifrmGame'].location.href = "/Main/GameOn/GameStart.aspx";
    }
}
