/*================================================================================*
 * name   : common.js
 * access : public
 *================================================================================*/
/*** function list ***/
/*
 Request :
  * Ajax						Ajax

 Util :

 Browser :

 DOMControler :

 Control :
  * ArrayShuffle				配列の順をシャッフル
  * QueryTime					乱数生成
  * EscTag						エスケープ処理
  * ImageResize					画像リサイズ用 imgタグにonloadを配置して読み込ませている 画像ﾘｻｲｽﾞ onload、非table式フォトアルバムの画像のリサイズ
  * ResizeImage					画像ﾘｻｲｽﾞ image
  * NaviNext					naviNextﾏｳｽ追従

 Library :
  * TabChanger

 */
/*** function list end ***/

function common() {}
common.prototype = {

/** Constant **/
	Constant : {
		XHR_PATH			: function() { return "http://stat100.ameba.jp/blog/xml/mk_data/official/"; },
		AMEBLO				: function() { return "http://ameblo.jp/"; },
		OFCL				: function() { return "http://stat100.ameba.jp/ofcl/"; },
		OFFICIALBLOG_FACE	: function() { return "http://stat.ameba.jp/blog/img/ameba/officialblog/face/"; },
		IMGRESIZSE			: function() { return "http://official.stat.ameba.jp/imageResize"; },
		IMGRESIZSELIST		: function() { return "http://official.stat.ameba.jp/imageResizeList"; },
		ICON_IMG			: function() { return "http://stat.ameba.jp/common_style/img/common/icon/"; },
		JQUERY_VER			: function() { var jQueryVer = jQuery.fn.jquery, jQueryVer = jQueryVer.slice(0,3); jQueryVer = Math.abs(Number(jQueryVer)); return jQueryVer; }
	},

/** Request **/
	Request : {
/*--------------------------------------------------------------------------------*
 * name     : Ajax
 * function : ajax
 * argument : prm
 *--------------------------------------------------------------------------------*/
		Ajax : function(prm) {

			var that = new common();

			if(that.Util.ErrorReduce(prm ,"not Ajax Object")){
				var objPrm = prm, def;

				if (objPrm.Timeout === undefined) { objPrm.Timeout = 10000; }

				def = $.ajax({
					url      : objPrm.Url,
					type     : objPrm.Type,
					dataType : objPrm.DataType,
					timeout  : objPrm.Timeout,
					error    : objPrm.Error,
					success  : objPrm.Success
				});
				return def;
			}
		},

		AjaxVer1_7 : function(prm) {

			var that = new common();

			if(that.Util.ErrorReduce(prm ,"not Ajax Object")){
				var objPrm = prm, d, xhrData;

				if (objPrm.Timeout === undefined) { objPrm.Timeout = 10000; }

				d = $.ajax({
					url      : objPrm.Url,
					type     : objPrm.Type,
					dataType : objPrm.DataType,
					timeout  : objPrm.Timeout
				}).then(function(data){
					xhrData = data;
				});

				return d;
			}
		},

		Pipes : function(defObj, callbackFunc){
			var xhr2 = defObj.pipe(callbackFunc)
			return xhr2;
		},
/*--------------------------------------------------------------------------------*
 * name     : GetJson
 * function : タイマーを使い指定時間内にコールバック関数が呼び出されなければ失敗と判断し、引数で指定されたerror関数をコールする。
 * argument : prm
 *--------------------------------------------------------------------------------*/
		GetJson : function(prm) {

			$.getJSON(
				prm.Url,
				prm.Data,
				prm.Callback.ProtoFunc
			);
		}
	},	//--Request end


/** Browser **/
	Browser : {
		//ブラウザチェックのモジュールはここに設置する
		Ua: function(){

			var that = new common()
			  , bBrowser = {}
			  , ua = window.navigator.userAgent
			  , vasion = ua.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || []
			  , testEl = document.createElement('div');

			bBrowser.safari = (/Safari/gi).test(window.navigator.appVersion);
			bBrowser.webkit = /webkit/i.test(ua);
			bBrowser.chrome = /Chrome/i.test(ua);
			bBrowser.firefox = /FireFox/i.test(ua);
			bBrowser.opera = /opera/i.test(ua);
			bBrowser.msie = /msie/i.test(ua) && !bBrowser.opera;
			bBrowser.mozzila = /mozzila/i.test(ua) && !/(compatible|webkit|)/.test(ua);
			bBrowser.android = /android/i.test(ua);
			bBrowser.iphone = /iphone/gi.test(window.navigator.platform);

			bBrowser.is3dSupported = !that.Util.IsNothing(testEl.style.WebkitPerspective);
			bBrowser.isCSSTransformSupported = ( !that.Util.IsNothing(testEl.style.WebkitTransform) || !that.Util.IsNothing(testEl.style.MozTransform) || !that.Util.IsNothing(testEl.style.transformProperty) );

			return bBrowser;
		}


	},	//--Browser end

/** Control **/
	Control : {
/*--------------------------------------------------------------------------------*
 * name     : UrlParth
 * function : ページのドメイン、ファイルパス、パラメーターを取得
 * argument :
 *--------------------------------------------------------------------------------*/
		Locations : function() {
			var domainName = location.hostname
			  , path = location.pathname || ""
			  , param = location.search || ""
			  , hashParam = location.hash || ""
			  , fullPath = location.href;

			return { Host : domainName, Path : path, Param : param, Hash : hashParam, FullPath : fullPath };
		},

/*--------------------------------------------------------------------------------*
 * name     : ArrayShuffle
 * function : 配列の順をシャッフル
 * argument : list
 *--------------------------------------------------------------------------------*/
		ArrayShuffle : function(list) {
			var i = list.length;
			while (--i) {
				var j = Math.floor(Math.random() * (i + 1));
				if (i === j) continue;
				var k = list[i];
				list[i] = list[j];
				list[j] = k;
			}
			return list;
		},

/*--------------------------------------------------------------------------------*
 * name     : QueryTime
 * function : 乱数生成
 * argument : -
 *--------------------------------------------------------------------------------*/
		QueryTimer : function() {
			var quot = "",
				d = new Date();
			return quot + d.getFullYear() + quot + (d.getMonth() + 1) + quot + d.getDate() + quot + d.getHours() + quot + d.getMinutes();
		},

/*--------------------------------------------------------------------------------*
 * name     : EscTag
 * function : エスケープ処理
 * argument : string
 *--------------------------------------------------------------------------------*/
		EscTag : function(string) {
			var re = new RegExp('[&<>\"\']','g'),
			escTable = {
				'&' : '&amp;',
				'<' : '&lt;',
				'>' : '&gt;',
				'"' : '&quot;',
				"'" : '&#39;'
			}
			//console.log(string);
			return string.replace(re,function(match){
				return escTable[match];
			});
		},

/*--------------------------------------------------------------------------------*
 * name     : Replace 3Reader
 * function : 三点リーダー置き換え
 * argument : string, n
 *--------------------------------------------------------------------------------*/
		ReplaceToReader : function(string,n) {
			var max_len = n, threeReader = "...", txtNode;
			var thatStr  = string;
			var str_len = thatStr.length;
			var sliceTxt;

			if(max_len < str_len){
				var sliceTxt = thatStr.slice(0,max_len);
				thatStr = sliceTxt+threeReader;
			}
			return thatStr;
		},


/*--------------------------------------------------------------------------------*
 * name     : blogimage
 * function : 画像リサイズ用 imgタグにonloadを配置して読み込ませている 画像ﾘｻｲｽﾞ onload、非table式
 *          : フォトアルバムの画像のリサイズ
 *--------------------------------------------------------------------------------*/
		ImageResize : function(imgObj, maxHeightWidth) {
			var imageHeight = imgObj.height
			  , imageWidth  = imgObj.width
			  , ratio = 1;

			if (imageHeight <= imageWidth) {
				if(imageWidth > maxHeightWidth){
					ratio = maxHeightWidth / imageWidth;
				}
				minPadding();
			} else {
				if(imageHeight > maxHeightWidth) {
					ratio = maxHeightWidth / imageHeight;
					minPadding();
				} else {
					minPadding();
				}
			}

			function minPadding() {
				var minImgLeft = Math.abs(Math.round((maxHeightWidth - (imageWidth * ratio)) / 2)) + "px"
				var minImgTop = Math.abs(Math.round((maxHeightWidth - (imageHeight * ratio)) / 2)) + "px";
				imgObj.style.paddingTop = minImgTop;
				imgObj.style.paddingLeft = minImgLeft;
			}
			imgObj.style.height = Math.abs(Math.round(imageHeight * ratio)) + "px";
			imgObj.style.width  = Math.abs(Math.round(imageWidth  * ratio)) + "px";
			if(imgObj.style.display === "none"){
				imgObj.style.display = "block";
			}
		},
/*--------------------------------------------------------------------------------*
 * name     : ImageResizeOnReady
 * function : 画像リサイズ用 非onload式 imgタグにclass="resizeImg"とdata-size="最大値"をセットして使用する
 *          : フォトアルバムの画像のリサイズ
 *--------------------------------------------------------------------------------*/
		ImageResizeOnReady : function(imgObj, w, h, maxSize, callback){
			var imageHeight = h
			  , imageWidth  = w
			  , ratio = 1
			  , maxHeightWidth = maxSize;

			if (imageHeight <= imageWidth) {
				if(imageWidth > maxHeightWidth){
					ratio = maxHeightWidth / imageWidth;
				}
				minPadding();
			} else {
				if(imageHeight > maxHeightWidth) {
					ratio = maxHeightWidth / imageHeight;
					minPadding();
				} else {
					minPadding();
				}
			}

			function minPadding() {
				var minImgLeft = Math.abs(Math.round((maxHeightWidth - (imageWidth * ratio)) / 2)) + "px"
				var minImgTop = Math.abs(Math.round((maxHeightWidth - (imageHeight * ratio)) / 2)) + "px";
				imgObj.style.paddingTop = minImgTop;
				imgObj.style.paddingLeft = minImgLeft;
			}
			imgObj.style.height = Math.abs(Math.round(imageHeight * ratio)) + "px";
			imgObj.style.width  = Math.abs(Math.round(imageWidth  * ratio)) + "px";

			callback(imgObj);
		},
/*--------------------------------------------------------------------------------*
 * name     : ResizeImage
 * function : 画像ﾘｻｲｽﾞ image
 *--------------------------------------------------------------------------------*/
		ResizeImage : function() {
			if (document.getElementById("imageMain")) {

				$('#imageArea').css({
					background : "none"
				});

				var mainImageWidth = $("#imageMain").width();

				if (450 < mainImageWidth) {
					$("#imageMain").width(450);
				}

				$("#imageMain").css({
					position: "static",
					visibility: "visible"
				});
			}
		},

/*--------------------------------------------------------------------------------*
 * name     : ProtectImage
 * function : 画像ﾘｻｲｽﾞ image
 *--------------------------------------------------------------------------------*/
		ProtectImage : function() {

			/* 右クリック禁止処理 */
			var oncontextmenuOffByTagName = function (tagName) {
				var target = null;

				if (document.all) {
					target = document.all.tags(tagName);
				} else if(document.getElementsByTagName) {
					target = document.getElementsByTagName(tagName);
				}
				var i = 0;
				var length = 0;

				if (target) {
					length = target.length;
					for (i=0; i<length; i++) {
						target[i].oncontextmenu = function(){return false;};
					}
				}
			}

			/* 画像保護処理 */
			  , imgProtect = function(a){

				var that = new common()
				  , aObj = a;

				/* イベントリスナー登録関数 */

				that.Event.Native.addEvent(a, 'click', onclickOffByA);

				/* user_imagesディレクトリの画像は保護 */
				var onclickOffByA = function() {
					var link = aObj.href || '';

					if (link.indexOf('/user_images/') > -1) {
						aObj.href = '#';
					}
				}


			}
			/* Onload */
			  , protectImageLoad = function() {

				var tagName = 'a'
				  , target = null;

				if (document.all) {
					target = document.all.tags(tagName);
				} else if(document.getElementsByTagName) {
					target = document.getElementsByTagName(tagName);
				}

				for (i=0; i<target.length; i++) {
					imgProtect(target[i]);
				}

				oncontextmenuOffByTagName('img');
			}

			protectImageLoad();


		},

/*--------------------------------------------------------------------------------*
 * name     : NaviNext
 * function : naviNextﾏｳｽ追従
 *--------------------------------------------------------------------------------*/
		NaviNext : function (){

			if (document.getElementById("imageLink")) {

				$("body").append('<div style="display:none;" id="naviNext"><img src="http://stat.ameba.jp/blog/img/user/navi_nextimage.gif" alt="" /></div>');

				$("#imageLink").hover(function(){

					$(this).mousemove(function(e){

						$('#naviNext').css({
							top: e.pageY - 26 + "px",
							left: e.pageX - 5 + "px"
						});
					});

					$("#naviNext").css("display", "block");

				}, function(){
					$("#naviNext").css("display", "none");
				});
			}
		}
	},	//--Control end

/** DOMControler **/
	DOMControler : {
		//Dom操作のモジュールはここに設置する
	},	//--DOMControler end


/** Event **/
	Event : {
/*--------------------------------------------------------------------------------*
 * name     : Event
 * function : イベント用ライブラリ
 *--------------------------------------------------------------------------------*/
		Jquery : {

			addBindEvent : function(eventObject, eventName, eventHandler){

				var that = new common();

				if(that.Constant.JQUERY_VER() > 1.6){
					return $(eventObject).on(eventName, eventHandler);
				}else{
					return $(eventObject).bind(eventName, eventHandler);
				}
			},

			addLiveEvent : function(eventObject, eventName, futureSlector, eventHandler){
				var that = new common();

				if(that.Constant.JQUERY_VER() > 1.6){
					return $(document).on(eventName, futureSlector,	eventHandler);
				}else{
					return $(eventObject).live(eventName, eventHandler);
				}
			},

			addDelegateEvent : function(eventObject, eventName, futureSlector, eventHandler){
				var that = new common();

				if(that.Constant.JQUERY_VER() > 1.6){
					return $(eventObject).on(eventName, futureSlector,	eventHandler);
				}else{
					return $(eventObject).live(futureSlector, eventName, eventHandler);
				}
			},

			removeBindEvent : function(eventObject, eventName){
				var that = new common();

				if(that.Constant.JQUERY_VER() > 1.6){
					return $(eventObject).off(eventName);
				}else{
					return $(eventObject).unbind(eventName);
				}
			},

			removeLiveEvent : function(eventObject, eventName, futureSlector){
				var that = new common();

				if(that.Constant.JQUERY_VER() > 1.6){
					return $(document).off(eventName, futureSlector);
				}else{
					return $(eventObject).die(eventName);
				}
			},

			removeDelegateEvent : function(eventObject, eventName, futureSlector){
				var that = new common();

				if(that.Constant.JQUERY_VER() > 1.6){
					return $(document).off(eventName, futureSlector);
				}else{
					return $(eventObject).undelegate(futureSlector, eventName);
				}
			}
		},

		Native : {

			addEvent : function(eventObject, eventName, eventHandler){
				var that = new common()
				  , ua = that.Browser.Ua();
				/*
				if(!ua.msie){
					return eventObject.addEventListener(eventName,  eventHandler, false);
				}else{
					return window.attachEvent("on" + eventName,  eventHandler);
				}
				*/
			}

		}

	},	//--Event end

/** Library **/
	Library : {
/*--------------------------------------------------------------------------------*
 * name     : TabChanger
 * function : タブ切り替え用ライブラリ
 *--------------------------------------------------------------------------------*/
		TabChanger : {
			Error : function(objName, index) {
				var self = this
				  , objName_ = objName;

				if (objName_ === self.identified[index].flag) {
					var contentId = "#"+self.identified[index].flag
					  , errorContent = '<p class="error">情報の取得に失敗しました、再読み込みをして表示をお待ちください。</p>';
					$(contentId).html(errorContent);
				}
			},

			//長い文字列に3点リーダー付ける
			ReplaceToReader : function(string) {
				var max_len = 6
				  , threeReader = "..."
				  , txtNode
				  , self  = string
				  , self_len = self.length
				  , sliceTxt;

				if (max_len < self_len) {
					var sliceTxt = self.slice(0, max_len);
					self = sliceTxt + threeReader;
				}
				return self;
			},

			//ClickHandler
			ClickHandler : function(c) {
				var self = this
				  , num;
				//console.log(self.tabUI);
				$(self.tabUI).bind('click', function(e) {
					if ($(this).attr("class") != "active") {
						e.preventDefault();
					}
					num = self.tabUI.index(this);
					clearInterval(self.timeoutID);
					if (self.count != 0) { self.count = num; }
					self.Interval();
					self.TabSwitcher(num);
				});
			},

			//SetTimeOut
			Interval : function() {
				var self = this;
				self.timeoutID = setInterval(function() {
					if (self.count > 2) { self.count = -1; }
					self.count++;
					self.TabSwitcher(self.count);
				}, self.interval);
			},

			//Tabswitcher
			TabSwitcher : function(n) {
				var self = this
				  , className = "active";

				self.tabUI.removeAttr("class");
				self.tabUI.eq(n).addClass(className);

				self.rnkContent.hide();
				self.rnkContent.eq(n).fadeIn();
			}
		}	//--TabChanger end
	},	//--Library end

/** Util **/
	Util : {
		//Isメソッドなどのチェック用モジュールはここに設置する
		ErrorReduce : function(o, msg){
			if(this.IsNothing(o)){
				try{
					throw msg;
				}catch(e){
					//console.error(e);
					return false;
				}
			}else{
				return true;
			}
		},

		IsObject : function(o){
			return o instanceof Object;

		},

		IsNothing : function(o){
			if(o === undefined || o === null){
				return true;
			}else{
				return false;
			}
		},

		IsNumber : function(val){
			return typeof val === 'number' && isFinite(val);
		}

	}//--Util end

}	//--Common end


