var VC, vc;
+function($){
//    var _releaseDate = '2009年3月31日';
    var d = document;
    VC = function (){};
    VC._test = false;
    VC._hards = _vc_hard;
    VC._hard_num = _vc_hard.length-1;
    VC._anchor = false;
    VC.prototype.searchByHard = function(hard){
        var len = jsonStrings.length, movies=[];
        for (var i=0; i<len; i++) {
            if (jsonStrings[i].hard != hard) continue;
            movies.push(jsonStrings[i]);
        }
        return movies;
    };
    
    VC.prototype.loadPage = function(hard){
        //set current image
        var id, obj;
        $.each($('.anchor'), function(){
            obj = $(this);
            id = obj.attr('id').replace(/anchor_/, '');
            if (!id) return;
            if (id == hard) obj.attr('src', 'images/anchor_btn_' + hard + '_on.jpg');
            else obj.attr('src', 'images/anchor_btn_' + id + '.jpg');
        });

        $('#movies').html("<div id='TB_loadmovies'><img src='"+imgLoader.src+"' /></div>");
        
        
        if (!hard) {
            $('#vctext').html(_releaseDate+'までに配信しているタイトルをランダムで5本ずつ表示しています。');
            $('.vc_top_btn').hide();
            
            VC._test ? hard = 'test' : hard = 'index'; 
            $('.movielink').unbind('click', VC.clickMovie);
            $('#movies').load('./' + hard + '.html #movies', function(){
                VC.makeHash(null, null, '#');

        		$('#TB_loadmovies').remove();
                VC.init();
            });
            return;
        };
        
        
        $('#vctext').html(_releaseDate+'までに配信しているタイトルを公開しています。');
        $('.vc_top_btn').show();
        $('.movielink').unbind('click', VC.clickMovie);
        $('#movies').load('./' + hard + '.html #movies', function(){
    		$('TB_loadmovies').remove();
            $('.movielink').click(VC.clickMovie);

//            if (navigator.userAgent.toLowerCase().indexOf('safari') > -1) {
//                location.hash="hard=" + hard;
//            } else {
//                location.hash="#hard=" + hard;
//            }
            VC.makeHash(hard);
            
            
            //$('.moviethumb').lazyload({bg:true});
        });
    };
    

    VC.prototype.getById = function(id){
        var len = jsonStrings.length;
        for (var i=0; i<len; i++) {
            if (jsonStrings[i].id == id) return jsonStrings[i];
        }
    };


    VC.prototype.pickUpAtRandom = function(hard, num){
        var movies=[], _movies, id;
        num = num || 5;
        movies = this.searchByHard(hard);
        if (movies.length > num) {
            _movies = [], ids = [];
            while (_movies.length < num) {
                id = Math.floor(Math.random() * movies.length);
                _movies.push(movies[id]);
                movies.splice(id, 1);
            }
            movies = _movies;
            //console.log(_movies)
        }
        return movies;
    };
    
    VC.prototype.display = function(id, movies){
        if (!$(id).size()) return;
        var html = '',
        imgFormat = '<table cellspacing="0" cellpadding="0" class="movieitem%s">    <tbody><tr>      <td class="moviethumb" style="background:url(/images/ajax_loader.gif) no-repeat center center"><img src="../images/common/spacer.gif" id="img_%s" rel="%s" alt="%s" class="movielink" width="148" height="111" border="0" /></td>      </tr>    <tr>      <td class="movieblow"></td>      </tr>    <tr>      <td class="movietxt"><div><span class="movietext movielink" rel="%s" alt="%s">%s</span></div></td>      </tr>  </tbody></table>';
//        imgFormat = '<table cellspacing="0" cellpadding="0" class="movieitem%s">    <tbody><tr>      <td class="moviethumb" style="background:url(%s) no-repeat center center"><img src="../images/common/spacer.gif" id="img_%s" rel="%s" alt="%s" class="movielink" width="148" height="111" border="0" /></td>      </tr>    <tr>      <td class="movieblow"></td>      </tr>    <tr>      <td class="movietxt"><div><span class="movietext movielink" rel="%s" alt="%s">%s</span></div></td>      </tr>  </tbody></table>';
        
        var style = 'left', imgs={};
        $.each(movies, function(key){
            html += sprintf(imgFormat, style, /*this.img,*/ this.id, this.id,  
            this.title.replace(/\n*<[^>]+>\n*/g, ''), this.id, 
            this.title.replace(/\n*<[^>]+>\n*/g, ''), this.title);
            style = '';
            imgs[this.id] = this.img;
        });
        $(id).html(html);

        
        // load images
        setTimeout(function() {
        $.each(imgs, function(key) {
            var image = new Image();
            image.src = this;
//            alert(image.complete);
            if (image.complete) {
                $('#img_'+key).parent().css('background', 'url('+ this +') no-repeat center center');
            } else {
                $(image).load(function() {
                    $('#img_'+key).parent().css('background', 'url('+ this.src +') no-repeat center center');
                });
            
            }
        });
        }, 100);
        
    };

    /**
     * @var id 'FC_001'
     */
    VC.prototype.play = function(e, id){
        var title, obj;
        if ((!e && !id) || id=='undefined') return;
        if (!id) id = $(e.target).attr('rel');
        if (!id) return;
        if (e) {
            title = $(e.target).attr('alt');
        } else if ( $('#img_' + id).size()){
            title = $('#img_' + id).attr('alt');
        } else {
            // permalink
            obj = this.getById(id);
            if (!obj)  return;
            
            title = obj.title;
            
            this.loadPage(VC._hards[obj.hard]);
        }
        tb_show(title.replace(/<[^>]+>/g, ''), '../flvplayer/' + id + '/index.html?width=320&height=470', null, id);
        
    };
    
    VC.prototype.readyToPlay = function(id) {
        var self = this;
        if (navigator.userAgent.toLowerCase().indexOf('msie') >= 0) {
            if (d.readyState != 'complete') {
                setTimeout(function(){self.readyToPlay.call(self, id);}, 1500);
                return;
            }
            self.play.call(self, null, id);
        } else {
            setTimeout(function(){self.play.call(self, null, id);}, 500);
        }
    };
    
    
    function sprintf(){
    	var format = Array.prototype.shift.apply(arguments);
    	var args   = arguments;
    	var i=0;
    	return format.replace(/%s/g, function(){
    		return args[i++];
	    });
    }
    
    

}(jQuery);


/**
 * jsonstrings in necessary. notice that it was loaded completely.
 */
VC.init = function() {
	imgLoader = new Image();// preload image
	imgLoader.src = tb_pathToImage;

    vc = new VC;
    var movies;

    if (!VC._anchor) {
       $('.anchor').click(VC.clickAnchor);
    }


    // permalink
    if (location.hash.match(/movie=([^&]+)/)) {
        var id = RegExp.$1;
        vc.readyToPlay(id);
    } else if(location.hash.match(/hard=([^&]+)/)){
        var id = RegExp.$1;
        vc.loadPage(id);
        return;
    }


//    alert([vc.searchByHard(1), vc.searchByHard(2), vc.searchByHard(3),vc.searchByHard(4),vc.searchByHard(5),vc.searchByHard(6), vc.searchByHard(7),vc.searchByHard(8)]);
    for (var i=1; i<=VC._hard_num; i++) {
        movies = vc.pickUpAtRandom(i);
        
        // draw
        //console.log(movies)
        vc.display('#movies_' + i, movies);
    }

    
    $('.movielink').click(VC.clickMovie);

   $('.vc_top_btn').hide();
}


VC.clickMovie = function(e){
    vc.play.call(vc, e);
    return false;
};

VC.clickAnchor = function(e){
    var hard = $(e.target).attr('rel');
    
    vc.loadPage.call(vc, hard);
    return false;
};

VC.makeHash = function(hard, soft, hash){
    var hashs=[];
    hash = hash || location.hash;
    hash = hash.replace(/movie=[^\&]+/, '').replace(/#/, '').replace(/\&$/, '');
    if (hash.indexOf('=') > -1) {
        hashs.push(hash);
    }
    if (hard) {
        hashs = [];
        hashs.push('hard=' + hard);
    }
    if (soft) {
        hashs.push('movie=' + soft);
    }
    
    if (!hashs.length) hashs = ['list'];
    
    hash = hashs.join('&');
    
    //for permalink	
    if (navigator.userAgent.toLowerCase().indexOf('safari') > -1) {
        location.hash= hash;
    } else {
        location.hash="#" + hash;
    }
    
    
    
    
};

function tb_remove() {
    //for permalink	
    VC.makeHash();
   
//    if (navigator.userAgent.toLowerCase().indexOf('safari') > -1) {
//        location.hash="list";
//    } else {
//        location.hash="#list";
//    }

    var swf = document.getElementById('swfcontent');
    if (swf) {
        swf.innerHTML = '';
    }

 	$("#TB_imageOff").unbind("click");
	$("#TB_closeWindowButton").unbind("click");

    // ie redraw images... cause below line
	if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
	    $('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();
	} else {
    	$("#TB_window").fadeOut("fast",function(){$('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();});
    }
	$("#TB_load").remove();
	
	
	if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
    	// ie redraw images... cause below line
//		$("body","html").css({height: "auto", width: "auto"});
		$("html").css("overflow","");
	}
	document.onkeydown = "";
	document.onkeyup = "";
	
	return false;
}


function tb_show(caption, url, imageGroup, id) {//function called when the user clicks on a thickbox link

//    	try {
		if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
    		// ie redraw images... cause below line
//			$("body","html").css({height: "100%", width: "100%"});

			$("html").css("overflow","hidden");
			if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
				$("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click(tb_remove);
			}
		}else{//all others
			if(document.getElementById("TB_overlay") === null){
				$("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click(tb_remove);
			}
		}
		
		
		if(tb_detectMacXFF()){
			$("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash
		}else{
			$("#TB_overlay").addClass("TB_overlayBG");//use background and opacity
		}
		
		if(caption===null){caption="";}
		$("body").append("<div id='TB_load'><img src='/images/circle_animation.gif' /></div>");//add loader to the page
		$('#TB_load').show();//show loader
		
		var baseURL;
	   if(url.indexOf("?")!==-1){ //ff there is a query string involved
			baseURL = url.substr(0, url.indexOf("?"));
	   }else{ 
	   		baseURL = url;
	   }
	   
	   var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
	   var urlType = baseURL.toLowerCase().match(urlString);

		var queryString = url.replace(/^[^\?]+\??/,'');
		var params = tb_parseQuery( queryString );

		TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL
		TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
		ajaxContentW = TB_WIDTH - 30;
		ajaxContentH = TB_HEIGHT - 45;
		
		if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window		
				urlNoQuery = url.split('TB_');
				$("#TB_iframeContent").remove();
				if(params['modal'] != "true"){//iframe no modal
					$("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a></div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' ></iframe>");
				}else{//iframe modal
				$("#TB_overlay").unbind();
					$("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>");
				}
		}else{// not an iframe, ajax
				if($("#TB_window").css("display") != "block"){
					if(params['modal'] != "true"){//ajax no modal
					$("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>close</a></div>"+caption+"</div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>");
					}else{//ajax modal
					$("#TB_overlay").unbind();
					$("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>");	
					}
				}else{//this means the window is already up, we are just loading new content via ajax
					$("#TB_ajaxContent")[0].style.width = ajaxContentW +"px";
					$("#TB_ajaxContent")[0].style.height = ajaxContentH +"px";
					$("#TB_ajaxContent")[0].scrollTop = 0;
					$("#TB_ajaxWindowTitle").html(caption);
				}
		}

		$("#TB_closeWindowButton").click(tb_remove);
		
			if(url.indexOf('TB_inline') != -1){	
				$("#TB_ajaxContent").append($('#' + params['inlineId']).children());
				$("#TB_window").unload(function () {
					$('#' + params['inlineId']).append( $("#TB_ajaxContent").children() ); // move elements back when you're finished
				});
				tb_position();
				$("#TB_load").remove();
				$("#TB_window").css({display:"block"}); 
			}else if(url.indexOf('TB_iframe') != -1){
				tb_position();
				if($.browser.safari){//safari needs help because it will not fire iframe onload
					$("#TB_load").remove();
					$("#TB_window").css({display:"block"});
				}
			}else{
			    var hash = location.hash;

				$("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
					tb_position();
					$("#TB_load").remove();
					tb_init("#TB_ajaxContent a.thickbox");
					$("#TB_window").css({display:"block"});
					
					
					// additional
                    var movieDomain = 'http://' + location.href.split('/')[2] + '/';
                    var flvfile = $('#filename').val();

                    var cc = location.href.split('/')[3];
                    if (cc == 'jp' && (location.href.indexOf('wii.com') != -1 || location.href.indexOf('210.172.37') != -1)) {
                    	flvfile = 'rtmp://fms.wii.com/wii/_definst_/' + flvfile;
                    } else {
                    	flvfile = movieDomain + cc + '/movies/flv/' + flvfile;
                    }
					
					
                    $("#noflash").show();
                    var so = new SWFObject("/swf/flvplayer_inside.swf", "flvplayer", 320, 280, "7", "#666666");
                    so.addVariable('flv', flvfile);
                    so.addVariable('totalTime', $('#total_time').val());

                    // title would bloken here by ie
                    var _title = document.title;
                    so.write("swfcontent");
                    
                    document.title = _title;

                    var varName = $('#_name').val();
                    if (typeof varName != "string") {
                        varName = 'movie';
                    }
                    
                    // hmmmmm
                    if ((jQuery.browser.msie && jQuery.browser.version < 7 ) ||
                        (jQuery.browser.msie && jQuery.browser.version == 7 &&
                    $('#TB_ajaxWindowTitle').height() < 32)){
                        $('#TB_ajaxContent').css('position', 'relative');
                        $('#TB_ajaxContent').css('top', '-12px');
                    }

//                    if (navigator.userAgent.toLowerCase().indexOf('safari') > -1) {
//                        location.hash = varName + '=' + id;
//                    } else {
//                        location.hash = "#" + varName + "=" + id;
//                    }

					VC.makeHash(null, id, hash)
					
				});
			}

		if(!params['modal']){
			document.onkeyup = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tb_remove();
				}	
			};
		}
		
		
//    	} catch(e) {
		//nothing here
//    	}
}

