var viddl = new Object();

viddl = function () {
	this.documentReady();
}

viddl.prototype = {
    
	documentReady: function(){
		
		this.loading = false;
		this.video_num = 1;
		this.search_num = 1;
		this.now_url = "";
		this.url_list = [];
		this.limited_time = 3;
		this.last_time = util.getTimestump(-this.limited_time-1);
		this.timer = "";
	},
	onSubmitURL: function (url) {
		
		
		if (!this.checkLoading()) {
			return false;
		}
		if (!this.checkURL(url)) {
			return false;
		}
		if (!this.checkTimestump(url)) {
			return false;
		}
		
		/**/
		this.nowLoading(true);
		this.getUnknownVideo(url);
	},
	onClickDownload: function (type, id, num) {
		
		if (!this.checkLoading()) {
			return false;
		}
		if (!this.checkTimestump(type)) {
			return false;
		}
		/**/
		this.nowLoadingPage(true, num);
		this.getVideo(type, id, num);
	},
	getUnknownVideo : function (url) {
		
		this.now_url = url;
		
		if (url.match('yourfilehost\.com')) {
			//var host = this.getRandomHost();
		}
			var host = location.host;
			/* このURLに直接アクセスしないてください。*/
			var path = 'http://' + host + '/getUnknownVideo.php';
			var param = '?url=' + escape(url) + '&callback={callback}';
			/* このURLに直接アクセスしないてください。*/
			$.getJSONP(path + param, function(obj) {
	            clearTimeout(vid.timer);
				vid.onLoadGetUnknownVideo(obj);
	        });
			this.clearUrlForm();
			
			this.timer = setTimeout(function() {
				vid.nowLoading(false);
				$.jsonp.clear();
				alert("タイムアウトしました。");
			}, 60000);
		
	},
	getVideo : function (type, id, num) {
		
		if (type == 'Yourfilehost') {
			//var host = this.getRandomHost();
			
		}
			var host = location.host;
			/* このURLに直接アクセスしないてください。*/
			var path = 'http://' + host + '/getVideo.php';
			var param = '?type=' + type + '&video_id=' + escape(id) + '&num=' + num + '&referer=' + escape(this.now_url) + '&callback={callback}';
			/* このURLに直接アクセスしないてください。*/
			$.getJSONP(path + param, function(obj) {
				clearTimeout(vid.timer);
				vid.onLoadGetVideo(obj);
	        });
			
			this.timer = setTimeout(function() {
				vid.nowLoadingPage(false, num);
				$.jsonp.clear();
				alert("タイムアウトしました。");
			}, 60000);
		
		/**/
	},
	onLoadGetUnknownVideo : function (obj) {
		
		if (obj["status"] == "source") {
			this.addVideoList(obj);
		} else if (obj["status"] == "page") {
			this.addPageList(obj);
		} else if (obj["status"] == "error") {
			this.addErrorList(obj);
		}
	},
	onLoadGetVideo : function (obj) {
		
		if (obj["status"] == "update") {
			this.updateVideoList(obj);
		} else if (obj["status"] == "error") {
			this.addErrorList2(obj);
		}
	},
	checkLoading : function () {
		
		if (this.loading == true) {
			alert("しばらくお待ちください。");
			return false;
		}
		return true;
	},
	checkURL : function (url) {
		
		url = util.trim(url);
		if (!url) {
			alert("URLを入力してください。");
			return false;
		}
		if (url.length > 1024) {
			alert("URLは1024文字以内で入力してください。");
			return false;
		}
		if (!util.isUrl(url)) {
			alert("URLを入力してください。");
			return false;
		}
		var suffix = ['\\.jpg$', '\\.zip$', '\\.js$'];
		for (var val in suffix) {
			if (url.match(suffix[val])) {
				alert('無効な拡張子です。' + suffix[val]);
				return false;
			} 
		}
		/**/
		return true;
	},
	checkTimestump : function (url) {
		
		if (url.match('yourfilehost\.com') || url == 'Yourfilehost') {
			var now = util.getTimestump();
			var sa = parseInt(now) - parseInt(this.last_time);
			if (sa <= this.limited_time) {
				alert((this.limited_time-sa)+"秒お待ちください。");
				return false;
			}
		}
		return true;
	},
	clearUrlForm : function () {
		$('#url')[0].value = '';
	},
	
	addErrorList : function (obj) {
		
		var html = "";
		var error_msg  = obj["msg"];
		var url  = obj["url"];
		
		
		//html += url + '<br>';
		html += '<p class="search-result" id="search-result' + this.search_num + '">検索結果：' + '<a href=\"' + this.now_url + '\" target=\"_blank\">' + this.now_url + '</a> <a href="javascript:vid.closeSearchResult(' + this.search_num + ',0,0)" class="linkblack">[この検索結果を閉じる]</a></p>';
		html += '<p id="search-error' + this.search_num + '"><span style="color:red;font-weight:bold;">Error</span> : ' + error_msg + '</p>';
		$('#video')[0].innerHTML += html;
		this.search_num++;
		this.nowLoading(false);
	},
	addErrorList2 : function (obj) {
		var html = "";
		var error_msg  = obj["msg"];
		var url  = obj["url"];
		var num = obj["num"];
		
		html += '<p id="search-error' + this.search_num + '"><span style="color:red;font-weight:bold;">Error</span> : ' + error_msg + '</p>';
		
		this.nowLoadingPage(false, num);
		$('#video'+num)[0].innerHTML = html;
		
	},
	addVideoList : function (obj) {
		
		var url   = unescape(obj["url"]);
		var type  = obj["type"];
		var title = obj["title"];
		var image = unescape(obj["image"]);
		var msg   = obj["msg"];
		var video_id = obj["video_id"];
		var ext = obj["ext"];
		var extra = obj["extra"];
		
		if (this.isRenameTitle(type)) {
			save_title = type + "_" + video_id;
		} else {
			save_title = title;
		}
		if (!image || image == "noimage") {
			image = "/img/noimage.gif";
		}
		save_title = this.escapeSaveTitle(save_title);
		save_title = this.addExt(type, save_title, ext);
		
		this.addUrlList(this.video_num, url);
		
		var html = "";
		html += '<p class="search-result" id="search-result' + this.search_num + '">検索結果：' + '<a href=\"' + this.now_url + '\" target=\"_blank\">' + this.now_url + '</a> <a href="javascript:vid.closeSearchResult(' + this.search_num + ',' + this.video_num + ',' + this.video_num + ')" class="linkblack">[この検索結果を閉じる]</a></p>';
		
		html += '<div id="video' + this.video_num + '">';
		html += '<span class=\'search-title\'>' + title + '<span> <a href="javascript:vid.closeVideo('+this.video_num+');"  class="linkblack">[閉じる]</a><br>';
		html += '保存ファイル名：<input type="text" value="'+ save_title +'" id="filename'+this.video_num+'" onClick="util.focusText(\'filename'+this.video_num+'\')" style="width:300px;"><br>';
		
		html += '<img src=\"' + image + '\" width="100" height="75" class="search-img">';
		
		//html += ads.list[0].title;
		if (type == "Yourfilehost") {
			
			html += '<iframe src=\"' + unescape(url) + '\" style="height:100px; width:300px;"></iframe><br>';
			html += '上の文字列を下のフォームにコピーペーストしてからダウンロードボタンを押してください。<br>';
			html += '<input type=\"text\" id="yourfilename'+this.video_num+'" style="width:300px;"/><input type=\"submit\" value=\"ダウンロード\" onclick=\"vid.downloadYFH('+this.video_num+');;\">';
			
		} else if (type == "Megavideo" || type == "Megaporn") {
			
			html += '<iframe src=\"' + unescape(url) + '\" style="height:100px; width:300px;"></iframe><br>';
			html += '上の文字列を下のフォームにコピーペーストしてからダウンロードボタンを押してください。<br>';
			html += '<textarea id="megavideo'+this.video_num+'" style="width:300px;"/><\/textarea><input type=\"submit\" value=\"ダウンロード\" onclick=\"vid.downloadMV('+this.video_num+');;\">';

        } else if (type == "Metacafe") {
            html += '<a href=\"' + url + '\"><img src="/img/icon/video_download.gif"></a>';
		} else {
			
            html += '<a href=\"' + unescape(url) + '\"><img src="/img/icon/video_download.gif"></a>';
			
			
		}
		
		
		//html += '<a id="embed-btn' + this.video_num + '" href="javascript:vid.spinEmbedVideo(\'' + type + '\',\'' + embed_id + '\',\'' + this.video_num + '\');"><img src="/img/icon/play.gif" width="75" height="26"></a><div id="embed-player' + this.video_num + '"></div>';
		
		if (msg) html += '<p id="search-msg' + this.search_num + '"><span style="color:blue;font-weight:bold;">Note</span> : ' + msg + '</p>';
		if (extra) html += extra;
		
		html += '<div id="loader' + this.video_num + '"></div>';
		html += '<br>';
		html += '</div>';
		
		
		//html += this.getVideoTagHtml(type, id);
		$('#video')[0].innerHTML += html;
		this.nowLoading(false);
		this.video_num++;
		this.search_num++;
		
		
		//urchinTracker('/search/'+type+'/');
	},
	addPageList : function (obj) {
		
		var count = obj.data.length;
		
		
		var html = "";
		html += '<p class="search-result" id="search-result' + this.search_num + '">検索結果：' + '<a href=\"' + this.now_url + '\" target=\"_blank\">' + this.now_url + '</a> <a href="javascript:vid.closeSearchResult(' + this.search_num + ',' + this.video_num + ',' + (this.video_num + count - 1) + ')" class="linkblack">[この検索結果を閉じる]</a></p>';

		for (var i = 0; i < count; i++) {
			var data = obj.data[i];
			var video_id = data['video_id'];
			var type = data['type'];
			
			if (i == 0) {
				var tmp_id = video_id;
				var tmp_type = type;
				var tmp_num = this.video_num;
			}
			
			html += '<div id="video' + this.video_num + '" style="padding-bottom:3px;">';
			html += type + ':'+ unescape(video_id) + ' ';
			html += '<a href="#" onclick="vid.onClickDownload(\'' + type + '\',\'' + unescape(video_id) + '\',\'' + this.video_num + '\');return false;"><img src="/img/icon/video_search.gif"></a>' + ' ';
			
			//html += '<br>';
			html += '<div id="loader' + this.video_num + '"></div>';
			html += '</div>';
			this.video_num++;
		}
		
		$('#video')[0].innerHTML += html;
		this.nowLoading(false);
		this.search_num++;
		this.last_time = util.getTimestump(-this.limited_time-1);
		if (tmp_id && tmp_type && tmp_num) {
			vid.onClickDownload(tmp_type, tmp_id, tmp_num);
		}
		
	},
	updateVideoList : function (obj) {
		
		var html = "";
		var msg   = obj["msg"];
		var num   = obj["num"];
		var type  = obj["type"];
		var title = obj["title"];
		var video_id = obj["video_id"];
		var url   = unescape(obj["url"]);
		var image = unescape(obj["image"]);
		var ext = obj["ext"];
		
		if (this.isRenameTitle(type)) {
			save_title = type + "_" + video_id;
		} else {
			save_title = title;
		}
		if (!image || image == "noimage") {
			image = "/img/noimage.gif";
		}
		save_title = this.escapeSaveTitle(save_title);
		save_title = this.addExt(type, save_title, ext);
		
		/**/
		this.addUrlList(num, url);
		
		if (title != "delete") {
			html += title + ' <a href="javascript:vid.closeVideo('+num+');" class="linkblack">[閉じる]</a><br>';
			html += '保存ファイル名：<input type="text" value="'+ save_title +'" id="filename'+num+'" onClick="util.focusText(\'filename'+num+'\')" style="width:300px;"><br>';
			
			html += '<img src=\"' + image + '\" width="100" height="75" class="search-img"> ';
			
			if (type == "Yourfilehost") {
				
				html += '<iframe src=\"' + unescape(url) + '\" style="height:100px; width:300px;"></iframe><br>';
				html += '上の文字列を下のフォームにコピーペーストしてからダウンロードボタンを押してください。<br>';
				html += '<input type=\"text\" id="yourfilename'+num+'" style="width:300px;"/><input type=\"submit\" value=\"ダウンロード\" onclick=\"vid.downloadYFH('+num+');;\">';
				
			} else if (type == "Megavideo" || type == "Megaporn") {
			
				html += '<iframe src=\"' + unescape(url) + '\" style="height:100px; width:300px;"></iframe><br>';
				html += '上の文字列を下のフォームにコピーペーストしてからダウンロードボタンを押してください。<br>';
				html += '<textarea id="megavideo'+num+'" style="width:300px;"/><\/textarea><input type=\"submit\" value=\"ダウンロード\" onclick=\"vid.downloadMV('+num+');;\">';

            } else if (type == "Metacafe") {
                html += '<a href=\"' + url + '\"><img src="/img/icon/video_download.gif"></a>';

			} else {
				
                html += '<a href=\"' + unescape(url) + '\"><img src="/img/icon/video_download.gif"></a>';
				
				
			}
			
			//html += '<a id="embed-btn' + num + '" href="javascript:vid.spinEmbedVideo(\'' + type + '\',\'' + embed_id + '\',\'' + num + '\');"><img src="/img/icon/play.gif" width="75" height="26"></a><div id="embed-player' + num + '"></div>';
			
			if (msg) html += '<p id="search-msg' + this.search_num + '"><span style="color:blue;font-weight:bold;">Note</span> : ' + msg + '</p>';
			
			html += '<br>';
			html += '</div>';
		} else {
			html += type + ' <a href="' + this.getVideoUrl(type, video_id) + '" target=\"_blank\">' + video_id + '</a>';
			html += ' : ファイルが見つかりません。<br>';
			html += '<img src=\"' + image + '\" width="130" height="97"><br>';
			html += '<br>';
		}
		
			
		
		this.nowLoadingPage(false, num);
		$('#video'+num)[0].innerHTML = html;
		
		
		//urchinTracker('/search/'+type+'/');
	},
	
	
	clearDiv : function(div_id) {
		$('#'+div_id)[0].style.display = 'none';
		$('#'+div_id)[0].style.height = '0px';
		$('#'+div_id)[0].innerHTML = '';
	},
	escapeSaveTitle : function(str) {
		str = str.replace(":", " ");
		str = str.replace("\"", "");
		str = str.replace("/", " ");
		str = str.replace("  ", " ");
		return str;
	},
	addExt: function(type, str, ext) {
		if (type == "Stage6") {
			str = str + ".divx";
		} else if (type == "Yourfilehost") {
			
		} else if (type == "Shooshtime") {
			str = str + ".wmv";
		} else {
			if (ext) {
				str = str + "." + ext;
			} else {
				str = str + ".flv";
			}
		}
		return str;
	},
	addUrlList : function(video_num, url) {
		if (video_num && url) {
			this.url_list[video_num] = url;
			var list = "";
			for (var $i = 1; $i <= this.url_list.length; $i++) {
				if (this.url_list[$i]) {
					list += this.url_list[$i] + "\n";
				}
			}
			//$('url-list').innerHTML = list;
			$('#url-list2')[0].value = list;
		}
	},
	deleteUrlList : function(start, end) {
		for (var $i = start; $i <= end; $i++) {
			this.url_list[$i] = "";
		}
		var list = "";
		for (var $i = 1; $i <= this.url_list.length; $i++) {
			if (this.url_list[$i]) {
				list += this.url_list[$i] + "\n";
			}
		}
		//$('url-list').innerHTML = list;
		$('#url-list2')[0].value = list;
	},
	spinUrlList : function() {
		var btn = $('#url-list-btn');
		var list = $('#url-list-box');
		if (list[0].style.display  == 'block') {
			btn[0].innerHTML = 'URLリストを開く';
			list[0].style.display = 'none';
		} else {
			btn[0].innerHTML = 'URLリストを閉じる';
			list[0].style.display = 'block';
		}
	},
	closeSearchResult : function(div, start, end) {
		if (start > 0 && end > 0) {
			for (var $i = start; $i <= end; $i++) {
				this.clearDiv('video' + $i);
			}
			this.deleteUrlList(start, end);
		}
		this.clearDiv('search-result'+div);
		this.clearDiv('search-error'+div);
		this.clearDiv('search-msg'+div);
	},
	closeVideo : function(num) {
		this.clearDiv('video' + num);
		this.deleteUrlList(num, num);
	},
	isRenameTitle : function(type) {
		var types = ['Mncast','Mgoon','Daum','Tagstory','Aura','Tudou','Mofile','Tvix','Freechal','Uume'];
		for (var i in types) {
			if (type == types[i]) {
				return true;
			}
		}
		return false;
		//return (type == 'Mncast' || type == 'Mgoon' || type == 'Daum' || type == 'Tagstory' || type == 'Aura' || type == 'Tudou' || type == 'Mofile' || type == 'Tvix' || type == 'Freechal' || type == 'Uume');
	},
	nowLoading : function (bool) {
		if (bool) {
			this.loading = true;
			$('#loader')[0].innerHTML = this.getLoaderHtml();
			$('#url_submit')[0].disabled = true;
		} else {
			this.loading = false;
			$('#loader')[0].innerHTML = "";
			$('#url_submit')[0].disabled = false;
			
			this.last_time = util.getTimestump();
		}
	},
	nowLoadingPage : function (bool, num) {
		if (bool) {
			this.loading = true;
			$('#loader'+num)[0].innerHTML = this.getLoaderHtml();
			$('#url_submit')[0].disabled = true;
		} else {
			this.loading = false;
			$('#loader'+num)[0].innerHTML = "";
			$('#url_submit')[0].disabled = false;
			
			this.last_time = util.getTimestump();
		}
	},
	getLoaderHtml : function () {
		return '<img src=\"/img/ajax-loader.gif\">';
	},
	getRandomHost : function () {
		var host = "";
		var hosts = ["img.vid-dl.net","your1.80code.com","your2.vid-dl.net","your3.vid-dl.net","your5.vid-dl.net"];
		var nMin = 0;
		var nMax = 4;
		var nRandomInt = Math.floor(Math.random()*(nMax-nMin+1))+nMin;
		//host = "10.0.1.2:1015";
		//host = "www.vid-dl.net";
		host = hosts[nRandomInt];
		return host;
	},
	downloadYFH : function(num) {
		//alert($('#yourfilename'+num)[0].value);
		//return;
		var str = $('#yourfilename'+num)[0].value;
		if (str == "") {
			return;
		}
		var keys = str.split("&");
		var param = [];
		for(var i in keys) {
			var key = keys[i];
			var key = key.split("=");
			param[key[0]] = unescape(key[1]);
		}
		if (param["video_id"]) {
			//alert(param["video_id"]);
			location.href = param["video_id"];
		}
	},
	downloadMV : function(num) {
		//alert($('#megavideo'+num)[0].value);
		//return;
		var str = $('#megavideo'+num)[0].value;
		if (str == "") {
			return;
		}
		
		var host = location.host;
		/* このURLに直接アクセスしないてください。*/
		var path = 'http://' + host + '/getVideo.php';
		var param = '?type=Megavideo2&video_id=' + escape(str) + '&num=' + num + '&callback={callback}';
		/* このURLに直接アクセスしないてください。*/
		//alert(path + param);
		$.getJSONP(path + param, function(obj) {
			//alert(unescape(obj["url"]));
			//location.href = obj["url"];
			var html = '<a href=\"'+ unescape(obj["url"]) + '\"><img src="/img/icon/video_download.gif"><\/a>';
			if (obj["msg"]) html += '<p><span style="color:blue;font-weight:bold;">Note</span> : ' + obj["msg"] + '</p>';
			$('#video'+num).append(html);
        });
		$('#megavideo'+num)[0].value = "";
	},
	downloadYT : function(num,video_id,fmt) {
		//alert($('#youtube'+num)[0].value);
		//return;
		var str = $('#youtube'+num)[0].value;
		if (str == "") {
			return;
		}
		var keys = str.split("&");
		var param = [];
		for(var i in keys) {
			var key = keys[i];
			var key = key.split("=");
			param[key[0]] = unescape(key[1]);
			param[key[0]] = param[key[0]].replace("%3D", "=");
		}
		if (param["token"]) {
			//alert(param["token"]);
			//location.href = param["video_id"];
			location.href = "http://www.youtube.com/get_video?video_id="+param["video_id"]+"&t="+param["token"]+"&el=embedded&ps=&fmt="+fmt;
		}
	},
	test : function (str) {
		alert("test:"+str);
	}
    
}

var util = new Object();
util = {
	trim : function(argValue) {
		return String(argValue).replace(/^[ 　]*/gim, "").replace(/[ 　]*$/gim, "");
	},
	isUrl : function(argvalue) {
		if (argvalue.indexOf("ttp://") == -1)
			return false;
		else if (argvalue == "http://")
			return false;
		else if (argvalue.indexOf("http://") > 0)
			return false;
		
		argvalue = argvalue.substring(7, argvalue.length);
		if (argvalue.indexOf(".") == -1)
			return false;
		else if (argvalue.indexOf(".") == 0)
			return false;
		else if (argvalue.charAt(argvalue.length - 1) == ".")
			return false;
		if (argvalue.indexOf("/") != -1) {
			argvalue = argvalue.substring(0, argvalue.indexOf("/"));
			if (argvalue.charAt(argvalue.length - 1) == ".")
				return false;
			}
		
			if (argvalue.indexOf(":") != -1) {
			if (argvalue.indexOf(":") == (argvalue.length - 1))
				return false;
			else if (argvalue.charAt(argvalue.indexOf(":") + 1) == ".")
				return false;
			argvalue = argvalue.substring(0, argvalue.indexOf(":"));
			if (argvalue.charAt(argvalue.length - 1) == ".")
				return false;
		}
		return true;
	},
	focusText : function(div_id) {
		var text = document.getElementById(div_id).value;
		var copy_id = document.getElementById(div_id);
		copy_id.focus();
		copy_id.select();
		if(document.all && navigator.userAgent.match(/windows/i) && text){
			copy_obj = document.getElementById(div_id).createTextRange();
			copy_obj.execCommand('Copy');
		}
	},
	getTimestump : function(x) {
		if (!x) x = 0;
		var t = new Date().getTime() + (x*1000) + "a";
		return t.substr(0, 10);
	}
	
}



  // For jQuery.js
  if(window.jQuery != undefined){
    if(navigator.appVersion.indexOf("KHTML") > -1 ){ // for safari
      var _httpData=window.jQuery.httpData;
      window.jQuery.httpData=function(r, type){
        alert(1);
		try{
          var ct = r.getResponseHeader("content-type");
          var data = !type && ct && ct.indexOf("xml") >= 0;
          data = type == "xml" || data ? r.responseXML : func01(r.responseText);

          // If the type is "script", eval it in global context
          if ( type == "script" )
          jQuery.globalEval( data );

          // Get the JavaScript object, if JSON is used.
          if ( type == "json" )
          eval( "data = " + data );

          // evaluate scripts within html
          if ( type == "html" )
          jQuery("<div>").html(data).evalScripts();

          return data;
        }catch(e){
          return _httpData.apply(this. arguments);
        }
      };
    }
  }

vid = new viddl();


