jQuery.noConflict();

var SI = {
	reqJS: new Array(
	'/shared/javascript/jquery.suggest.js',
	'/shared/javascript/css_browser_selector.js'
	),
	loadJS: function(jsURL) {
		document.write('<script type="text/javascript" src="'+jsURL+'"></script>');
	},

	addRollovers: function(target){
		if(!target) traget = '.imgover';
		var aPreLoad = new Array();
		var aImages = jQuery(target);
	
		for (var i = 0; i < aImages.length; i++) {
			var object = aImages[i];
			var src = object.getAttribute('src');
			
			var ftype = src.substring(src.lastIndexOf('.'), src.length);
			var oversrc = src.replace(ftype, "_over" + ftype);
			
			object.setAttribute('osrc', src);
			object.setAttribute('hsrc', oversrc);
			
			aPreLoad[i] = new Image();
			aPreLoad[i].src = oversrc;
			
			object.onmouseover = function() {
				this.setAttribute('src', this.getAttribute('hsrc'));
			};
			object.onmouseout = function() {
				this.setAttribute('src', this.getAttribute('osrc'));
			};
		};
	},
	
	alignHeight: function(){
		var baseHeight = 0;
		var targetID;
		var targets = jQuery('#topics .topics .pickup p');
		if(targets){
			jQuery.each(targets, function(){
				if(baseHeight <= jQuery(this).height()){
						baseHeight = jQuery(this).height();
						targetID = jQuery(this);
				};
			});
			jQuery.each(targets, function(){
				if(targetID != jQuery(this)){
						jQuery(this).height(baseHeight);
				};
			});
		};
	},

	createElementLink : function(){
		jQuery('div[link], li[link]').bind('mouseup', function(){
			window.location = jQuery(this).attr('link');
		});
	},

	enableWindow : function(){
		jQuery.fn.colorbox.init();
		if(navigator.userAgent.indexOf('MSIE')<0){
			jQuery().bind('cbox_open', function(){
					 jQuery(window).bind('scroll',jQuery.fn.colorbox.position);
			});
			jQuery().bind('cbox_close', function(){
					 jQuery(window).unbind('scroll',jQuery.fn.colorbox.position);
			});
		};
		
		jQuery('.openRegist').colorbox({
			width:"660px",
			height:"310px",
			iframe:true
		});
		jQuery('.openLogin').colorbox({
			width:"330px",
			height:"220px",
			iframe:true
		});
		jQuery('.openReminder').colorbox({
			width:'330px',
			height:'220px',
			iframe:true
		});
	},
	
	checkWindow : function(){
		if(!window.location.hash) return false;
		if(!SI.sslurl) SI.sslurl = '';
		var windowhash = window.location.hash;
		if(windowhash.match('#registration')){
			jQuery.fn.colorbox({
				href: SI.sslurl + "/registration",
				width:"660px", height:"310px", iframe:true, open:true} );
		};
		if(windowhash.match('#login')){
			jQuery.fn.colorbox({
				href: SI.sslurl + "/login",
				width:"330px", height:"220px", iframe:true, open:true} );
		};
		if(windowhash.match('#reminder')){
			jQuery.fn.colorbox({
				href: SI.sslurl + "/password/renew",
				width:"330px", height:"220px", iframe:true, open:true} );
		};
		if(windowhash.match('#complete')){
			jQuery.fn.colorbox({
				href: SI.sslurl + "/registration/ok",
				width:"330px", height:"220px", iframe:true, open:true} );
		};
	},
	
	enableTargetBlank : function(){
		jQuery('.articleBody a').attr('target','_blank');
	},
	
	errorMessage : 'エラーが発生しました。\n既に追加・削除されているか、\n正しく処理できなかった可能性があります。',
	ajaxErrorMessage : '連続クリックは禁止しています。',
	tempElement : [],
	ajaxFlag : false,
	
	clickFollow : function(event) {
		event.preventDefault();
		if(!SI.ajaxFlag){
			SI.ajaxFlag = true;
			var selectedFlag = false;
			var inputData = jQuery('#' + event.data.targetType).attr('sendValue');
			var reqData = jQuery('#' + event.data.targetType).val();
			if (reqData == inputData ) selectedFlag = true;
			var reqKind = 1;
			if(event.data.targetType == 'followBrand') reqKind = 2;
			jQuery.ajax({
				dataType: 'json', cache: false,
				data: {q: reqData, kind: reqKind}, url: '/mypage/ac_list',
				success: function (getData) {
					SI.ajaxFlag = false;
					var getArray = [];
					for(var i = 0; i < getData.array.length; i++){
						for(var j = 0; j < getData.array[i].data.length; j++){
							getArray.push(getData.array[i].data[j]);
						}
					}
					if( getArray.length ){
						if ( selectedFlag ){
							var hasError = false;
							for(var i = 0; i < getArray.length; i++){
								if( getArray[i][jQuery('#' + event.data.targetType).attr('sortType')] == inputData ){
									if( reqKind == '2' ){
										SI.clickFollowCreate(getArray[i].id, 'corporate');
									}else{
										SI.clickFollowCreate(getArray[i].id, 'contributor');
									};
									hasError = false;
									break;
								} else {
									hasError = true;
								};
							};
							if ( hasError ) jQuery('#' + event.data.targetType).trigger('error');
							return false;
						} else {
							if( getArray.length == 1 ) {
								if( reqKind == '2' ){
									SI.clickFollowCreate(getArray[0].id, 'corporate');
								}else{
									SI.clickFollowCreate(getArray[0].id, 'contributor');
								};
								return false;
							} else if ( getArray.length == 2 ) {
								if( getArray[0].id == getArray[1].id ){
									if( reqKind == '2' ){
										SI.clickFollowCreate(getArray[0].id, 'corporate');
									}else{
										SI.clickFollowCreate(getArray[0].id, 'contributor');
									};
								} else {
									jQuery('#' + event.data.targetType).trigger('error');
									return false;
								};
							} else {
								jQuery('#' + event.data.targetType).trigger('error');
								return false;
							};
						};
					}	else {
						jQuery('#' + event.data.targetType).trigger('error');
						return false;
					};
				}
			})
		
		} else {
			alert(SI.ajaxErrorMessage);
		};
	},
	
	clickFollowCreate : function(getID, type) {
		if(!SI.ajaxFlag){
			SI.ajaxFlag = true;
			var tempUrl = '/follow/' + type + '/' + getID;
			jQuery.ajax({
				dataType: 'json', cache: false, url: tempUrl,
				success: function (getData) {
					if (getData.status == 'ok'){
						if (type == 'contributor'){
							var article;
							if (getData.data.narticles == 1){ article = '1 article'; } else if (getData.data.narticles == 0) { article = 'no article'; } else { article = getData.data.narticles + ' articles'; };
							var follower;
							if (getData.data.nfollowers >= 2){ follower = getData.data.nfollowers + ' followers'; } else { follower = '1 follower'; };
							
							var html = '<div class="authorTable" style="display:none;" link="/contributor/' + getID + '">';
							html += '<div class="top"></div><div class="tableBox"><table width="612" border="0" cellspacing="0" cellpadding="0"><tr><td class="authorName"><p><span>';
							html += '<img src="' + getData.data.image_path + '" alt="アイコン" width="16" height="16" /></span>';
							html += '<a href="/contributor/' + getID + '">' + getData.data.name;
							html += '</a></p></td><td class="authorFollow">';
							html += '<a class="clickUnfollow" href="/unfollow/contributor/' + getID + '"><img src="/shared/images/system/btn_profile_follow_minus.gif" alt="" width="15" height="15" /></a>';
							html += '</td></tr><tr><td class="authorDescription">';
							html += getData.data.blogname + '<br />';
							html += '<a href="' + getData.data.blogurl + '" target="_blank">' + getData.data.blogurl + '</a>';
							html += '</td><td class="authorArticles">' + article + '<br />' + follower + '</td></tr></table></div><div class="bottom"></div></div>';
							
							jQuery('#' + type).prepend(html);
							jQuery('#' + type + ' div[link]').eq(0).slideDown();
							jQuery('#' + type + ' div[link] .clickUnfollow').bind('click',SI.clickUnfollow).bind('mouseup',function(event){event.stopPropagation();});
							
							jQuery('#followAuthor').val('').attr('sendValue', '').attr('sortType', '');
							
						} else {
							var html = '<div class="brandTable" style="display:none;" link="/corporate/' + getID + '">'
							html += '<div class="top"></div><div class="tableBox"><table width="612" border="0" cellspacing="0" cellpadding="0"><tr>'
							html += '<td class="brandName"><a href="/corporate/' + getID + '">' + getData.data.name + '</a></td>'
							html += '<td class="brandFollow">'
							html += '<a class="clickUnfollow" href="/unfollow/corporate/' + getID + '"><img src="/shared/images/system/btn_profile_follow_minus.gif" alt="" width="15" height="15" /></a>'
							html += '</td></tr><tr><td class="brandDescription">'
							html += getData.data.market;
							if (getData.data.market_code != ''){
								html +=  ': ' + getData.data.market_code;
							}
							html += '</td>'
							html += '<td class="brandArticles"></td></tr></table></div><div class="bottom"></div></div>'
							
							jQuery('#' + type).prepend(html);
							jQuery('#' + type + ' div[link]').eq(0).slideDown();
							jQuery('#' + type + ' div[link] .clickUnfollow').bind('click',SI.clickUnfollow).bind('mouseup',function(event){event.stopPropagation();});
							
							jQuery('#followBrand').val('').attr('sendValue', '').attr('sortType', '');
						};
					} else {
						alert(SI.errorMessage);
					};
					SI.ajaxFlag = false;
				}
			});
		} else {
			alert(SI.ajaxErrorMessage);
		};
	},
	
	clickUnfollow : function(event){
		event.preventDefault();
		if(!SI.ajaxFlag){
			SI.tempElement = jQuery(this);
			var tempUrl = SI.tempElement.attr('href');
			SI.ajaxFlag = true;
			jQuery.ajax({
				dataType: 'json', cache: false, url: tempUrl,
				success: function (data) {
					if (data.status == 'ok'){
						SI.tempElement.closest('div[link]').slideUp();
					} else {
						alert(SI.errorMessage);
					};
					SI.ajaxFlag = false;
				}
			});
		} else {
			alert(SI.ajaxErrorMessage);
		};
	},
	
	setUnfollow : function(){
		jQuery('.clickUnfollow').bind('click',SI.clickUnfollow);
		jQuery('.clickUnfollow').bind('mouseup',function(event){event.stopPropagation();});
	},
	
	clickTextFollow : function(event){
		event.preventDefault();
		if(!SI.ajaxFlag){
			SI.tempElement = jQuery(this);
			var tempUrl = SI.tempElement.attr('href');
			SI.ajaxFlag = true;
			jQuery.ajax({
				dataType: 'json', cache: false, url: tempUrl,
				success: function (data) {
					if (data.status == 'ok'){
						if ( SI.tempElement.hasClass('minus') ){
							SI.tempElement.addClass('plus').removeClass('minus');
							SI.tempElement.attr('href', SI.tempElement.attr('href').replace('/unfollow/', '/follow/'));
							SI.tempElement.text(SI.tempElement.text().replace('フォローからはずす', 'フォローする'));
						} else {
							SI.tempElement.addClass('minus').removeClass('plus');
							SI.tempElement.attr('href', SI.tempElement.attr('href').replace('/follow/', '/unfollow/'));
							SI.tempElement.text(SI.tempElement.text().replace('フォローする', 'フォローからはずす'));
						};
						SI.tempElement = [];
					} else {
						alert(SI.errorMessage);
					};
					SI.ajaxFlag = false;
				}
			});
		} else {
			alert(SI.ajaxErrorMessage);
		};
	},
	
	setClickTextFollow : function() {
		jQuery('.clickTextFollow').bind('click',SI.clickTextFollow);
	},
	
	clickImageFollow : function(event){
		event.preventDefault();
		if(!SI.ajaxFlag){
			SI.tempElement = jQuery(this);
			var tempUrl = SI.tempElement.attr('href');
			SI.ajaxFlag = true;
			jQuery.ajax({
				dataType: 'json', cache: false, url: tempUrl,
				success: function (data) {
					if (data.status == 'ok'){
						if ( SI.tempElement.attr('href').match('/contributor/') ){
							var target = 'Contributor';
						}else{
							var target = 'Corporate';
						}
						if ( SI.tempElement.attr('href').match('/unfollow/') ){
							var recentStatus = 'follow', newStatus = 'unfollow';
							var recentAlt = 'フォローする', newAlt = 'フォロー中';
						}else{
							var recentStatus = 'unfollow', newStatus = 'follow';
							var recentAlt = 'フォロー中', newAlt = 'フォローする';
						}
						SI.tempElement.attr('href', SI.tempElement.attr('href').replace(newStatus, recentStatus));
						SI.tempElement.html('<img src="/shared/images/system/btn_'+recentStatus+target+'.gif" alt="'+recentAlt+'" width="106" height="19" />');
						SI.tempElement.closest('.article').find('.individual').removeClass(recentStatus+target).addClass(newStatus+target);
						jQuery('.information .current').removeClass(recentStatus).addClass(newStatus);
						SI.tempElement = [];
					} else {
						alert(SI.errorMessage);
					};
					SI.ajaxFlag = false;
				}
			});
		} else {
			alert(SI.ajaxErrorMessage);
		};
	},
	
	setClickImageFollow : function() {
		jQuery('.clickImageFollow').bind('click',SI.clickImageFollow);
	},
	
	setArticleQuote : function() {
		var obj = jQuery('.entry.article .articleBody blockquote');
		obj.before('<div class="quote_top"></div>');
		obj.after('<div class="quote_bottom"></div>');
	},
	
	transparentIcon : function(){
		jQuery('.ie6 .author span, .ie6 ul.authorRanking span.author').each(function(){
			jQuery(this).css('filter','progid:DXImageTransform.Microsoft.AlphaImageLoader(src=' + jQuery(this).find("img").attr('src') + ',SizingMethod=scale)').css('width','16px').css('height','16px');
			jQuery(this).find("img").css("display","none");
  	});
	},

	/*
	init
	*/
	init: function() {
		if(navigator.userAgent.indexOf('AppleWebKit/') < 0 || navigator.userAgent.indexOf('Mobile/') < 0){
			this.reqJS.push('/shared/javascript/jquery.colorbox.js');
		}
		jQuery.each(this.reqJS, function() {
			SI.loadJS(this);
		});
		
		/*DOM Ready Event*/
		jQuery(document).ready(function(){
			SI.alignHeight();
			if(navigator.userAgent.indexOf('AppleWebKit/') < 0 || navigator.userAgent.indexOf('Mobile/') < 0){
				SI.enableWindow();
				SI.checkWindow();
				SI.createElementLink();
			}
			SI.enableTargetBlank();
			SI.setUnfollow();
			SI.setClickTextFollow();
			SI.setClickImageFollow();
			SI.setArticleQuote();
			if(navigator.userAgent.indexOf('MSIE 6')>0) SI.transparentIcon();
			jQuery('.profileEdit #password, .profileEdit #password_c').val('');
		});
	}

};

SI.init();