// JavaScript Document

/* Core class */

Core={
	disp: null,
	loadSign: null,
	uri: "",
	href: "",
	hash: "",
	self: this,
	twitter_area_id: '#stream',
	nav_area_id:'#nav_area',
	nav:null,
	nav_src:'/blog/blog/menu',
	nav_map: {
		'':'.news',
		'pages/index/' 			: '.index',
		'blog/blog/news/' 				: '.news',
		'blog/blog/vision/' 			: '.vision',
		'blog/blog/profile/' 			: '.profile',
		'blog/blog/business/' 			: '.business',
		'blog/blog/global_network/'	: '.global_network',
		'blog/blog/wikitekina/' 		: '.wikitekina',
		'sample/contact/' 			: '.contact',
		'blog/blog/access_map/'		: '.access_map',
		'blog/blog/recruit/'			: '.recruit',
		'sample/blog/' 				: '.blog',
		'blog/blog/privacy_policy/' 	: '.privacy_policy'
	},
	os_client: null,
	call_stack: 0,
	constructor:null,
	
init:function(disp,loadSign){
	this.disp=disp;
	this.loadSign=loadSign;
	
},


pageInit: function(target){
	this.enableMouseOver(target);
	this.enableSmoothScroll(target);
	this.enableHyperLink(target);
	this.enableStreamArea(target);
},


enableMouseOver :  function (target) {
	target=(target == undefined)? jQuery("#contents_wrapper") : target;
    target.find("img[src*='_off']").each(function(){
        Core.preLoad(jQuery(this).attr('src').replace(/_off(\.[a-z]+)$/,'_on$1'));
        jQuery(this).hover(
            function(){
				if(!jQuery(this).hasClass('focus')){
					jQuery(this).attr('src',jQuery(this).attr('src').replace(/_on(\.[a-z]+)$/, '_off$1'));
					jQuery(this).attr('src',jQuery(this).attr('src').replace(/_off(\.[a-z]+)$/, '_on$1'));
				}
            },
            function(){
				if(!jQuery(this).hasClass('focus')){
                	jQuery(this).attr('src',jQuery(this).attr('src').replace(/_on(\.[a-z]+)$/, '_off$1'));
				}
            }
        );
    });
},

enableSmoothScroll: function(target){
    target=(target == undefined)? jQuery("#contents_wrapper") : target;
    target.find("a[href^='#'][href!='#!']").click(function(){
            var Hash = jQuery(this.hash);
            if(Hash.length==0) Hash=jQuery("*[name='"+this.hash.replace("#","")+"']");
            var HashOffset = jQuery(Hash).offset().top;
            var dist=Math.abs(jQuery(this).offset().top-HashOffset);
            jQuery("html,body").animate({
                scrollTop: HashOffset
            }, dist/7);
            return false;
    });
},

enableHyperLink: function(target){
	target=(target == undefined)? jQuery("#contents_wrapper") : target;
	target.find("a[href]").each(function(){
		var href=jQuery(this).attr("href");

		if(href.indexOf(location.hostname)==-1 && href.search(/http.*:\/\//)!=-1){
			jQuery(this).click(function(){
				_gaq.push(['_trackPageview',jQuery(this).attr("href")]);
			});
		}else if(jQuery(this).attr("href").search(/#[^!].+/) == -1){
			var regexp01=new RegExp("http.*:\/\/"+location.hostname+"\/index\.html");
			var regexp02=new RegExp("http.*:\/\/"+location.hostname+"\/");
			
			var _path=location.href.replace(/#!.*|index.htm.*/,"");
			
			var _hash=jQuery(this).attr("href").replace(regexp01,'').replace(regexp02,'').replace(/.*blog\/(.+)/,'#!/blog/blog/$1');
			
			jQuery(this)
			.attr("href",_path+_hash)
			.click(function(){
				_gaq.push(['_trackPageview',jQuery(this).attr("href")]);
				//Core.linkTo(_hash);
			});
		}
	});	
},

enableStreamArea: function(target){
	var _tw_stream_area=target.find(this.twitter_area_id);
	
	
	if(_tw_stream_area.length>0 && _tw_stream_area.find(".inner").text().search(/\W+/)!=-1){
		this.os_client=new OnySysClient("GET",_tw_stream_area,"xml");
		_tw_stream_area.hover(
			function(){
				jQuery(this).stop().animate({
					right: 0
				},1000);
			},
			function(){
				jQuery(this).stop().animate({
					right: jQuery(this).find(".inner").width()*-1			
				},1000);
			}
		);
		setTimeout(function(){
			_tw_stream_area.animate({
					right:_tw_stream_area.find(".inner").width()*-1
			},1000);
		},5000);
	}else{
		_tw_stream_area.empty();
	}
},

initiallizeNavArea: function(){
	this.nav=jQuery(this.nav_area_id);
	var self=this;
	jQuery.ajax({
			type: 'GET',
			url: self.nav_src,
			success: function(xml){
				Core.constructNavArea(xml);
			},
			dataType: "html"
	});
},

constructNavArea: function(source){
	
	source=source.replace(/\r|\n/g,"");
	var xml=jQuery(source);
	
	var html_txt=source.match(/<ul id="menu_main">.+<\/ul>/);
	
	this.nav.append(html_txt[0]);
	this.enableMouseOver(this.nav);
	this.enableSmoothScroll(this.nav);
	this.enableHyperLink(this.nav);
	//this.updateNavArea();
},

updateNavArea: function(){
	if(this.nav==null){
		 this.initiallizeNavArea();
	}else{
		this.nav.find('* > ul').slideUp("fast");
		this.nav.find('.focus').each(function(){
			jQuery(this).attr("src",jQuery(this).attr("src").replace(/_on(\.[a-z]+)$/, '_off$1'));
			jQuery(this).removeClass('focus');
		});
		
		this.nav.find(this.nav_map[this.href.replace(/(.+\/)[^\/]+/,"$1")]+' > ul').each(function(){jQuery(this).slideDown();});
		this.nav.find(this.nav_map[this.href.replace(/(.+\/)[^\/]+/,"$1")]+' > a > img').each(function(){
					jQuery(this)
					.attr("src",jQuery(this).attr("src").replace(/_off(\.[a-z]+)$/, '_on$1'))
					.addClass('focus');
				});
		/*
		for(var key in this.nav_map){
			if(this.href.replace(/(.+\/)[^\/]+/,"$1").search(key)!=-1){
				this.nav.find(this.nav_map[key]+' > ul').each(function(){jQuery(this).slideDown();});
				this.nav.find(this.nav_map[key]+' > a > img').each(function(){
					jQuery(this)
					.addClass('focus')
					.attr("src",jQuery(this).attr("src").replace(/_off(\.[a-z]+)$/, '_on$1'));
				});
			}
		}
		*/
	}
},

linkTo: function(uri){
	var self=this;
	if(self.disp.filter("#stream").length > 0){
		self.disp.filter("#stream").css({filter:''}).fadeOut(1000,function(){
			self.disp.filter("#stream").css('filter','');
		});
	}
	self.disp.css({filter:''}).hide();
	self.loadSign.show();
	Core.loadPage("GET", uri, "xml");
	self.disp.css('filter','');
	
},

loadPage: function(type, uri, data_type){
	if(Core.uri==uri) return;
		Core.disp.empty();
		Core.uri=uri;
		Core.href=( uri.search(/#!.+/)!=-1 ) ? uri.replace(/#!\/(.+)#?/,'$1') : "top.xml";
		Core.hash=uri.match(/#[^#]+$/);
		
		var self=this;
		
		jQuery.ajax({
			type: "GET",
			url: self.href,
			success: Core.constructPageModule,
			dataType: "html"
		});
		
		
		//jQuery.get(self.href,Core.constructPageModule);
},

constructPageModule: function(source){
	var self=Core;
	if(self.constructor!=null){
		if(self.constructor.scriptTags!=null) self.constructor.scriptTags.remove();
		if(self.constructor.scriptTags!=null) self.constructor.styleTags.remove();
	}
	
	source=source.replace(/\r|\n/g,"");//replace(/([^<])(\/+)([^>])/g,"$1\\\$2$3");
	var xml=jQuery(source);
	var html_txt=source.match(/<div id="contener"[^>]*?>.+<\/div>/);
	
	
	self.disp.empty();

	/*var html_txt=xml.filter("#contener,#stream");//.get(0).innerHTML;
	if(html_txt==undefined){
		html_txt=xml.filter("#contener").get(0).xml;
		html_txt=html_txt.replace(/<body.+?>|<\/body>/,"");
	}
	*/
	
	var scriptTags=xml.filter("script[src]");
	var styleTags=xml.filter("link[type*='text/css'],style");
	
	self.constructor=new PageConstructor(scriptTags,styleTags,html_txt[0],self);
	
	self.constructor.construct();
},


preLoad :  function (url) {
  jQuery('<img />')
    .hide()
    .attr('src', url)
    .appendTo(document.body)
    .load(function () { jQuery(this).remove(); })
    .error(function () { jQuery(this).remove(); });
}

};


/* Twitter Client class*/

OnySysClient=function(type, targetTag, data_type){
	this.initiallize(type, targetTag, data_type);
}

OnySysClient.prototype={
	targetTag:null,
	parseXML:function(xml){
		var txt_html="<ul>\n";
		jQuery(xml).find("status").each(function () {
			var xmlTagProf= {
				user: "from-user",
				text: "ctext",
				thumb: "profile-image-url",
				client: "source",
				statusid: "status-id"
			};
			for(var key in xmlTagProf){
				xmlTagProf[key]=jQuery(this).find(xmlTagProf[key]).text();
			}
			txt_html+="<li><img src=\""+xmlTagProf['thumb']+"\" class=\"thumb\"/>"+
				"<a href=\"http://twitter.com/"+xmlTagProf['user']+"\" target=\"_blank\" class=\"user\">"+xmlTagProf['user']+"</a>"+
				"<span class=\"text\">"+xmlTagProf['text'].replace(/(http:\/\/[\S]+)/,"<a href=\"$1\" terget=\"_blant\">$1</a>")+"</span>"+
				"<a href=\"http://twitter.com/"+xmlTagProf['user']+"\" onclick=\"javascript:_gaq.push(['_trackPageview','/tweet/"+xmlTagProf['user']+"/"+xmlTagProf['statusid']+".html']);\" class=\"check\">チェック</a>"+
				"</li>\n";	
		});
		txt_html+="</ul>\n";
		
		return txt_html;
	},
	initiallize: function(type, targetTag, data_type){
		_self=this;
		_self.targetTag=targetTag.find(".inner");
		
		var query=targetTag.text();
		var id=(query.search(/@([\w]+)?/) !=-1) ? query.replace(/@([\w]+)?/,"%40$1"):"-/";
		var hash=(query.search(/#([\w]+)?/) !=-1) ? query.replace(/#([\w]+)?/,"%23$1"): "";
		
		jQuery.ajax({
			type: type,
			url: "/rails/tweets/user_timeline/"+id+hash+".xml?limit=20",
			dataType: data_type,
			success: function(xml){
				_self.targetTag.empty();
				var html=_self.parseXML(xml);
				_self.targetTag.append(html);
			}
		});
	}
}

/* PageConstructor class */

var PageConstructor=function(scriptTags,styleTags,html_text,core_obj){
		this.init(scriptTags,styleTags,html_text,core_obj);
}

PageConstructor.prototype={
	core_obj:null,
	scriptTags:null,
	styleTags:null,
	script_loading:0,
	html_txt:"",
	init:function(scriptTags,styleTags,html_text,core_obj){
		this.core_obj=core_obj;
		this.scriptTags=scriptTags;
		this.styleTags=styleTags;
		this.script_loading=scriptTags.length;
		this.html_txt=html_text;
	},
	
	construct: function(){
		var self=this;
		
		if(self.script_loading>0){
			/*self.styleTags.appendTo(jQuery("head"));
			for(var i=0;i<self.script_loading;i++){
				var callback=function(){return};
				if(i==self.script_loading-1){
					callback=self.develop();
				}
				jQuery.getScript(jQuery(this.styleTags[i]).attr("src"),callback);
			}*/
		/*
		if(self.script_loading>0){
			self.scriptTags.each(function(){
				jQuery.getScript(jQuery(this).attr("src"), function(){
					self.script_loading--;
					if(self.script_loading<=0){
						self.develop();
					}
				})
			});*/self.develop();
		}else{
			self.develop();
		}
		
	},
	
	develop: function(){
		this.core_obj.disp.append(this.html_txt);
		this.core_obj.pageInit(this.core_obj.disp);
		this.core_obj.updateNavArea();
		/*
		xml.filter("script:not(:empty)").each(function(){
			jQuery(jQuery(this).text());
		});
		*/
		
		this.core_obj.loadSign.hide();
		if(this.core_obj.disp.filter("#stream").text() != ""){
			this.core_obj.disp.filter("#stream").css({filter:''}).fadeIn(2000,function(){
				jQuery(this).filter("#stream").css('filter','');
			});
		}else{
			this.core_obj.disp.filter("#stream").hide();
		}
		this.core_obj.disp.css({filter:''}).fadeIn(2000, function(){
			jQuery(this).css('filter','');
		});
	}
}





/*   initiallize     */
jQuery(document).ready(function(){
	Core.init(jQuery("#center #display"),jQuery("#center #loading"));
	Core.pageInit(jQuery("body"));
	Core.initiallizeNavArea();
	
	jQuery(window).hashchange(function() {
		var uri=location.hash;
		if(location.href.search(/\/#!/)!=-1){
			uri=location.href.replace(/.+\/(#!.+)/,"$1");
		}else{
			uri="#!/pages/index/index.html";
		}
    	Core.linkTo(uri);
	});
	
	var hashchangecall=function(){
			if(jQuery(Core.nav_area_id+' > ul').length>0){
				jQuery(window).hashchange();
			}else{
				setTimeout(hashchangecall,500);
			}
	};

	
	setTimeout(hashchangecall,500); 
	 
});



/* global network hover */

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
