var uploadLoginId;
var uploadLoginPass;
var uploadComment;
var fileList        = new Array();
var fileIndex       = 0;
var uploadComplete  = 0;
var uploadMode      = 0;
var strUploadingImg = '<span class="uploading"><img src="/img/loading.gif"></span>';
var strUploadedImg  = '<span class="uploaded"><img src="/img/loaded.gif"></span>';
var strDeleteImg    = '<span class="delete"><img src="/img/dust.gif"></span>';
function thisMovie(str) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
	return window[str];
    } else {
	return document[str];
    }
}
function escapeHTML(str) {
    return str.replace(/[&\"<>]/g, function(c) {
    return {
      "&": "&amp;",
      '"': "&quot;",
      "<": "&lt;",
      ">": "&gt;"
    }[c];
  });
}
function tabChange(n)
{
    uploadMode = n;
    if (uploadComplete == 0){
	clearTabClass();
	setTabClass();
	initUploadForm();
    }
}
function clearTabClass()
{
    $('#movie_tab').removeClass('on');
    $('#image_tab').removeClass('on');
    $('#tweet_tab').removeClass('on');
    $('#capture_tab').removeClass('on');
    $('#movie_tab').removeClass('off');
    $('#image_tab').removeClass('off');
    $('#tweet_tab').removeClass('off');
    $('#capture_tab').removeClass('off');
}
function setTabClass()
{
    switch(uploadMode){
    case 0:
	$('#movie_tab').addClass('on');
	break;
    case 1:
	$('#image_tab').addClass('on');
	break;
    case 2:
	$('#tweet_tab').addClass('on');
	break;
    case 3:
	$('#capture_tab').addClass('on');
	break;
    default:
	$('#movie_tab').addClass('on');
	break;	
    }
}
function initUploadForm()
{
    for(key in fileList){
	callCancel(fileList[key]);
    }
    clearString($('#comment'));
    $('#comment').val('つぶやきをどうぞ');
    clearString($('#text_comment'));
    $('#text_comment').val('つぶやきをどうぞ');
    clearString($('#title'));
    $('#title').val('タイトルをどうぞ');
    clearString($('#tid'));
    $('#tid').val('twitterユーザー名');
    clearString($('#pass'));
    $('#pass').val('・・・・・・・');
    clearString($('#text_tid'));
    $('#text_tid').val('twitterユーザー名');
    clearString($('#text_pass'));
    $('#text_pass').val('・・・・・・・');
    $('div#authMessage').remove();
    var denyFlg = $('#uploadDeny').attr('denyFlg');
    switch(uploadMode){
    case 0:
	$('#fileUploadBox').css('margin', '0px');
	$('#textUploadBox').hide();
	$('#videoCaptureBox').hide();
    if (!denyFlg){
	    thisMovie("FileUploader").callTabChange(setting.BOI03,setting.BOI04,setting.BOI05,uploadMode);
    }
	break;
    case 1:
	$('#fileUploadBox').css('margin', '0px');
	$('#textUploadBox').hide();
	$('#videoCaptureBox').hide();
    if (!denyFlg){
	    thisMovie("FileUploader").callTabChange(setting.BOI13,setting.BOI14,setting.BOI15,uploadMode);
    }
	break;
    case 2:
	$('#fileUploadBox').css('margin', '0px');
	$('#fileUploadBox').css('margin-left', '-9999px');
	$('#videoCaptureBox').hide();
    if (denyFlg){
	    $('#fileUploadBox').css('margin-bottom', '-20px');
    } else {
	    $('#fileUploadBox').css('margin-bottom', '-180px');
    }
	$('#textUploadBox').show();
	break;
    case 3:
	$('#fileUploadBox').css('margin', '0px');
	$('#fileUploadBox').css('margin-left', '-9999px');
    if (denyFlg){
	    $('#fileUploadBox').css('margin-bottom', '-20px');
    } else {
	    $('#fileUploadBox').css('margin-bottom', '-180px');
    }
    $('#textUploadBox').hide();
    $('#videoCaptureBox').show();
    $('#captureTweet').attr("disabled", "disabled");
    break;
    }
}
function selectedFileAddViewHundler(str,size)
{
    fileIndex++;
    var id    = 'filename'+fileIndex;
    var strDivStart  = '<div id="' + id + '" class="filename">';
    var strDivEnd    = '</div>';
    $('#fileList').append(strDivStart + escapeHTML(str) + strUploadingImg + strUploadedImg + strDeleteImg + strDivEnd);
    $('#fileList').show();
    $("#fileList div#" + id +" span.delete").click(function() {
						       callCancel(str);
						    });
    fileList[fileIndex] = str;
    disableTab();
    $('#FileUploader + div.alert').remove();
}
function callCancel(str)
{
    var count = 0;
    for (var key in fileList) {
	if (fileList[key] == str){
	    delete fileList[key];
	    $('#fileList div#filename'+key).remove();
	    thisMovie("FileUploader").callDelete(str);
	}
	if (fileList.hasOwnProperty(key)) count++;
    }
    if (count == 0){
	enableTab();
    }
    $('#FileUploader + div.alert').remove();
}
function enableTab()
{
    $('#movie_tab').replaceWith('<li id="movie_tab"><a title="動画を投稿" href="javascript:tabChange(0);">動画を投稿</a></li>');
    $('#image_tab').replaceWith('<li id="image_tab"><a title="画像を投稿" href="javascript:tabChange(1);">画像を投稿</a></li>');
    $('#tweet_tab').replaceWith('<li id="tweet_tab"><a title="つぶやきを投稿" href="javascript:tabChange(2);">つぶやきを投稿</a></li>');
    $('#capture_tab').replaceWith('<li id="capture_tab" class="last" ><a title="Webカメラから投稿" href="javascript:tabChange(3);">Webカメラから投稿</a></li>');
    setTabClass();
}
function disableTab()
{
    switch(uploadMode){
    case 0:
	disableImageTab();
	disableTweetTab();
    disableCaptureTab();
	break;
    case 1:
	disableMovieTab();
	disableTweetTab();
    disableCaptureTab();
	break;
    case 2:
	break;
    case 3:
	disableMovieTab();
    disableImageTab();
	disableTweetTab();
    disableCaptureTab();
    break;
    }
}
function disableMovieTab()
{
    $('#movie_tab').replaceWith('<li id="movie_tab">動画を投稿</li>');
    $('#movie_tab').removeClass('on');
    $('#movie_tab').addClass('off');
}
function disableImageTab()
{
    $('#image_tab').replaceWith('<li id="image_tab">画像を投稿</li>');
    $('#image_tab').removeClass('on');
    $('#image_tab').addClass('off');
}
function disableTweetTab()
{
    $('#tweet_tab').replaceWith('<li id="tweet_tab">つぶやきを投稿</li>');
    $('#tweet_tab').removeClass('on');
    $('#tweet_tab').addClass('off');
}
function disableCaptureTab()
{
    $('#capture_tab').replaceWith('<li id="capture_tab" class="last">Webカメラから投稿</li>');
    $('#capture_tab').removeClass('on');
    $('#capture_tab').addClass('off');
}

function fileOpenHundler(str)
{
    $('#fileUploadForm').hide();
    for (var key in fileList) {
	if (fileList[key] == str){
	    $('#fileList div#filename'+key+' span.uploading').show();
	    $('#fileList div#filename'+key+' span.delete').hide();
	}
    }
}
function fileCompleteHundler(str)
{
    var id = str.replace('.', '\\.');
    for (var key in fileList) {
	if (fileList[key] == str){
	    $('#fileList div#filename'+key+' span.uploading').hide();
	    $('#fileList div#filename'+key+' span.uploaded').show();
	}
    }
}
function allCompleteHundler()
{
	
    if ($('#tid').val() && $('#pass').val()){
		$.ajax({
				url : "http://"+DOMAIN+"/upload/login/",
					type : "post",
					data : ({ login_id: $('#tid').val(), password: $('#pass').val() }),
					success: function(request) {
					var myJSONobj = eval( "(" + request + ")" );
					if(myJSONobj.data.auth=="true"){
						$.ajax({
								url : "http://"+DOMAIN+"/login_state/user/",
									type : "get",
									success: function(request) {
									var objUser = eval( "(" + request + ")" );
									if (objUser.data != false){
										addUserInfo(objUser);
										addFileUploadResult();
									}
								}
							});
					}else{
						loginError();
					}
				}
			});
    } else {
		addFileUploadResult();
    }
    
    uploadComplete = 1;
}
function addUserInfo(objUser)
{
    var strId         = '<input type="hidden" value="'+uploadLoginId+'" id="t_login_id" name="data[t_login_id]"/>';
    var strProfImg    = "<a title='"+ objUser.data.Member.name + "さんのtwitterへ' target='_blank' href='"+ setting.twitter_url + "/" + objUser.data.Member.login_id + "/'><img src='"+ objUser.data.Member.profile_image_url+"' alt='"+ objUser.data.Member.name  +"'さんのtwitterへ ></a>";
    var strWelcomMsg  = "  ようこそ <a title='"+ objUser.data.Member.name  +"さんのtwitterへ' target='_blank' href='" + setting.twitter_url + "/" + objUser.data.Member.login_id  +"/'>"+ objUser.data.Member.name +"</a> さん";
    var strMypageLink = "  <a class='button' href='/contents/lists/'>マイページ</a>";
    var strLogoutLink = "  <a class='button' href='/members/logout/'>ログアウト</a>";
    $('#loginFormArea').empty();
    $('#loginFormArea').html(strProfImg + strWelcomMsg + strMypageLink + strLogoutLink);
}
function addFileUploadResult()
{
	$('#result').html('<a href="/contents/lists/" class="button">コンテンツ一覧へ</a>');
	$("#result a").mouseover(function(){
				     $(this).removeClass("button");
				     $(this).addClass("button_on");
				 });
	$("#result a").mouseout(function(){
				    $(this).removeClass("button_on");
				    $(this).addClass("button");
				});
}
function callTweet()
{
    var blnError = false;
    uploadLoginId = null;
    if ($('#tid').val()){
		uploadLoginId = $('#tid').val();
    }
    uploadLoginPass = null;
    if ($('#pass').val()){
		uploadLoginPass = $('#pass').val();
    }
    uploadComment = null;
    if ($('#comment').val()){
		uploadComment = $('#comment').val();
		if (uploadComment.length > setting.comment_max_length){
			$('#comment + div.alert').remove();
			$('#comment').after('<div class="alert">つぶやきは'+setting.comment_max_length+'文字以内でご入力ください</div>');
			blnError = true;
		}
    }
    var title = null;
    if ($('#title').val()){
		title = $('#title').val();
		if (title.length > setting.title_max_length){
			$('#title + div.alert').remove();
			$('#title').after('<div class="alert">タイトルは'+setting.title_max_length+'文字以内でご入力ください</div>');
			blnError = true;
		}
    }
    if (!blnError){
		var x = thisMovie("FileUploader").callTweet(uploadLoginId,uploadLoginPass,uploadComment,title);
		if (x == 0){
			$('#FileUploader + div.alert').remove();
			$('#FileUploader').after('<div class="alert">アップロードするファイルをご指定ください</div>');
			fileErrorStyle();
		}
    }
}

function callPreCaptureTweet()
{
   $('#captureTweet').removeAttr("disabled");
}
function callInitCaptureTweet()
{
   $('#captureTweet').attr("disabled","disabled");
}

function callUploadCaptureTweet()
{
   $('#capture_tid').remove();
   $('#capture_pass').remove();
   $('#capture_title').remove();
   $('#capture_comment').remove();
   $('#captureTweet').remove();
   disableTab();
}

function callCmpleteCaptureTweet()
{
	$('#captureResult').html('<a href="/contents/lists/" class="button">コンテンツ一覧へ</a>');
	$("#captureResult a").mouseover(function(){
				     $(this).removeClass("button");
				     $(this).addClass("button_on");
				 });
	$("#captureResult a").mouseout(function(){
				    $(this).removeClass("button_on");
				    $(this).addClass("button");
				});
}

function callCaptureTweet()
{
    var blnError = false;
    uploadLoginId = null;
    if ($('#capture_tid').val()){
		uploadLoginId = $('#capture_tid').val();
    }
    uploadLoginPass = null;
    if ($('#capture_pass').val()){
		uploadLoginPass = $('#capture_pass').val();
    }
    uploadComment = null;
    if ($('#capture_comment').val()){
		uploadComment = $('#capture_comment').val();
		if (uploadComment.length > setting.comment_max_length){
			$('#capture_comment + div.alert').remove();
			$('#capture_comment').after('<div class="alert">つぶやきは'+setting.comment_max_length+'文字以内でご入力ください</div>');
			blnError = true;
		}
    }
    var title = null;
    if ($('#capture_title').val()){
		title = $('#capture_title').val();
		if (title.length > setting.title_max_length){
			$('#capture_title + div.alert').remove();
			$('#capture_title').after('<div class="alert">タイトルは'+setting.title_max_length+'文字以内でご入力ください</div>');
			blnError = true;
		}
    }
    if (!blnError){
		var x = thisMovie("VideoCapture").callTweet(uploadLoginId,uploadLoginPass,uploadComment,title);
		if (x == 0){
			$('#VideoCapture + div.alert').remove();
			$('#VideoCapture').after('<div class="alert">アップロードするファイルをご指定ください</div>');
			fileErrorStyle();
		}
    }
}
function callTextTweet()
{
    var blnError = false;
    uploadLoginId = null;
    if ($('#text_tid').val()){
		uploadLoginId = $('#text_tid').val();
    } else {
		uploadLoginId = $('#t_login_id').val();
    }
    uploadLoginPass = null;
    if ($('#text_pass').val()){
		uploadLoginPass = $('#text_pass').val();
    }
    uploadComment = '';
    if ($('#text_comment').val()){
		uploadComment = $('#text_comment').val();
		if (uploadComment.length > setting.comment_max_length){
			$('#text_comment + div.alert').remove();
			$('#text_comment').after('<div class="alert">つぶやきは'+setting.comment_max_length+'文字以内でご入力ください</div>');
			blnError = true;
		}
    }
	
    if (!blnError){
	if ($('#text_tid').val() && $('#text_pass').val()){
	    $.ajax({
		    url : "http://"+DOMAIN+"/upload/login/",
			type : "post",
			data : ({ login_id: uploadLoginId, password: uploadLoginPass }),
			success: function(request) {
			var myJSONobj = eval( "(" + request + ")" );
			if(myJSONobj.data.auth=="true") {
			    $.ajax({
				    url : "http://"+DOMAIN+"/login_state/user/",
					type : "get",
					success: function(request) {
					var objUser = eval( "(" + request + ")" );
					if (objUser.data != false){
					    addUserInfo(objUser);
					}
				    }
				});
			    textUpload();
			    uploadComplete = 1;
			}else{
			    loginError();
			}
		    }
		});
	} else {
	    if (uploadLoginId){
		textUpload();
		uploadComplete = 1;
	    } else {
		loginError();
	    }
	}
    }
}
function textUpload()
{
    disableMovieTab();
    disableImageTab();
    $.ajax({
	    url : "http://"+DOMAIN+"/twitter/tweet/",
		type : "post",
		data : ({ comment: uploadComment }),
		beforeSend : function(){
		textUploadStart();
	    },
		success : function(request){
		var res = eval( "(" + request + ")" );
		textUploadSuccess(res);
	    },
		complete : function() {
		textUploadComplete();
	    }
	});
}
function textUploadStart()
{
    $('#textUploadForm').remove();
    $('#textList').append('<div class="filename">'+ escapeHTML(uploadComment) + strUploadingImg + strUploadedImg + '</div>');
    $('#textList').show();
    $('#textList div span.uploading').show();
}
function textUploadSuccess(res)
{
    if (res){
	$('#text_result').html('<a href="'+ setting.twitter_url + '/' + uploadLoginId + '" class="button" target="_blank">twitterへ</a>');
	$("#text_result a").mouseover(function(){
					  $(this).removeClass("button");
					  $(this).addClass("button_on");
				      });
	$("#text_result a").mouseout(function(){
					 $(this).removeClass("button_on");
					 $(this).addClass("button");
				     });
	$('#textList').before('<div id="textTweetCompleteText">投稿完了</div>');
	$('#textTweetCompleteText').css('color', '#000000');
	$('#textTweetCompleteText').css('margin', '0px 0px 10px 82px');
	$('#textTweetCompleteText').css('font-size', '20px');
    } else {
	$('#textList').before('<div id="textTweetCompleteText">投稿失敗</div>');
	$('#textTweetCompleteText').css('color', '#000000');
	$('#textTweetCompleteText').css('margin', '0px 0px 10px 82px');
	$('#textTweetCompleteText').css('font-size', '20px');
	$('#text_result').text('お手数ですがもう一度投稿お願いします');
    }
}
function textUploadComplete()
{
    $('#textList div span.uploading').hide();
    $('#textList div span.uploaded').show();
    $('#videoCaptureBox').hide();
}
function fileErrorStyle()
{
    $('#FileUploader + div.alert').css('marginLeft', '14px');
}
function fileNumberError(n)
{
    $('#Fileuploader').After('<div class="alert">一度に選択できるファイル数は'+n+'ファイルまでです</div>');
    fileErrorStyle();
}
function fileNameError()
{
    $('#FileUploader').after('<div class="alert">ご指定のファイルは既に選択されています</div>');
    fileErrorStyle();
}
function fileSizeError(n)
{
    $('#FileUploader').after('<div class="alert">アップロードできるファイルのサイズは' + n/1000000 + 'MB以内です</div>');
    fileErrorStyle();
}
function loginError(str)
{
    $('div#authMessage').remove();
    switch(uploadMode){
    case 0:
    case 1:
	$('#pass').after('<div id="authMessage">正しいユーザー名とパスワードを入力してください</div>');
	break;
    case 2:
	$('#text_pass').after('<div id="authMessage">正しいユーザー名とパスワードを入力してください</div>');
	break;
    }
}
//#debug JS
function errorCheck(str){
	
	debugObj += " / from flash : "+str+" / ";
	
}
var debugObj="";
