/// コンテンツ詳細画面

/// <reference path="../common/js/avweb.js" />

/// <reference path="../common/js/screenLock.js" />

/// <reference path="../common/js/common.js" />

/// <reference path="../common/js/i18n.js" />

/// <reference path="../common/js/jquery-1.8.1.min.js" />

/// <reference path="../common/js/jquery-ui-1.8.23.custom.min.js" />

/// <reference path="../common/js/jquery.toastmessage.js" />

/// <reference path="../common/js/pageViewer.js" />

/// <reference path="init.js" />

/// <reference path="home.js" />

var displayData = {
    contentID: "",
    contentTitle: "",
    contentDetail: "",
    contentThumbnail: "",
    deliveryDate: (new Date()),
    pages: []
};

// Init function of page
$(document).ready(function () {
    //alert(ClientData.contentInfo_contentId());
    //if (!avwCheckLogin(ScreenIds.Login)) return;

    //openContentDetail();

    

});

// Show content detail
function openContentDetail() {

    displayData = {
        contentID: "",
        contentTitle: "",
        contentDetail: "",
        contentThumbnail: "",
        deliveryDate: (new Date()),
        pages: []
    };

    // Clear childs
    $('#book_list').html('');

    // Clear display info
    $("#imgContentThumbnail").css('padding-top', "60px");
    $("#imgContentThumbnail").attr('src', "img/data_loading.gif");
    resetLoadingImageSize();
    
    $("#txtContentTitle").text('');
    $("#txtPubDt2_Dsp").text('');
    $("#txtContentDetail").text('');

    $("#contentDetailClose").click(contentDetailClose_Click);

    //$("#contentdetail_dspBack").click(contentdetail_dspBack_Click);
    $("#contentdetail_dspRead").click(contentdetail_dspRead_Click);

    lockLayout();
    $("#contentDetail").css('z-index', 101);
    $("#sectionContentDetail").show();
    $("#contentDetail").show();
    $("#contentDetail").center();
    if ($("#contentDetail").height() > $(window).height()){
		$("#contentDetail").css('top', '0');
	}

    // Get contentid, thumbnail from list screen
    displayData.contentID = ClientData.contentInfo_contentId();
    displayData.contentThumbnail = ClientData.contentInfo_contentThumbnail();
    
    // Get content detail
    avwCmsApi(ClientData.userInfo_accountPath(), "webGetContent", "GET", { contentId: displayData.contentID, sid: ClientData.userInfo_sid(), getType: 1 },
                function (data) {
                    // Get content detail
                    displayData.contentTitle = data.contentData.contentName;
                    displayData.contentDetail = data.contentData.contentDetail;
                    displayData.deliveryDate = convertToDate(data.contentData.deliveryStartDate);

                    // Get pages
                    avwCmsApiSync(ClientData.userInfo_accountPath(), "webContentPage", "GET", { contentId: ClientData.contentInfo_contentId(), sid: ClientData.userInfo_sid(), thumbnailFlg: 1, pageNos: '1,2,3,4,5,6'},
                                function (data) {
                                    
                                    // Get pages
                                    for (var nIndex = 0; nIndex < data.pages.length; nIndex++) {
                                        if (nIndex < 6) {
                                            displayData.pages.push({ pageNo: data.pages[nIndex].pageNo, pageText: data.pages[nIndex].pageText, pageThumbnail: ("data:image/jpeg;base64," + data.pages[nIndex].pageThumbnail) });
                                        }
                                    }
                                    // Show to screen
                                    ShowContent(displayData.contentID, truncate(displayData.contentTitle, 20), displayData.contentDetail, ClientData.contentInfo_contentThumbnail(), displayData.deliveryDate, displayData.pages);                                                           		                               
                                },
                                null
                    );

                },
                null
    );
};

// Close content detail
function contentDetailClose_Click(e) {
    e.preventDefault();
    unlockLayout();
    $("#contentDetail").hide();
    $("#sectionContentDetail").hide();
};
/*
----------------------------------------------------------------------------
Event groups [start]
----------------------------------------------------------------------------
*/

function contentdetail_dspRead_Click(e) {
    e.preventDefault();
	var outputId = ClientData.contentInfo_contentId();
	var date = new Date();
	var month = date.getMonth()+1;
	var day = date.getDate();
	var outputDate = formatNormalDate(day, month, date.getFullYear());
	var contentIdArray = [];
	var checkflag = false;
	
	//Store Content id that user has read
	if(ClientData.ReadingContentIds().length > 0){
		contentIdArray = ClientData.ReadingContentIds();
		
		for(var nIndex = 0; nIndex < contentIdArray.length; nIndex++){
			if(contentIdArray[nIndex].contentid == outputId){
				checkflag = true;
				if(contentIdArray[nIndex].viewdate == '' || contentIdArray[nIndex].viewdate == null || contentIdArray[nIndex].viewdate == 'undefined'){
					contentIdArray[nIndex].viewdate = outputDate;
					contentIdArray[nIndex].originviewdate = date;
				}
				break;
			}
			else{
				checkflag = false;
			}			
		}
		
		if(!checkflag){
			contentIdArray.push({contentid: outputId, viewdate: outputDate, originviewdate: date});
		}
	}
	else{
		contentIdArray.push({contentid: outputId, viewdate: outputDate, originviewdate: date});
	}
	
	//Renew ReadingContentID
	var newArray = [];
	ClientData.ReadingContentIds(newArray);
	
	//Set data for readingcontentid
	ClientData.ReadingContentIds(contentIdArray);
	
	//Set ResouceVersion for content
	setResourceVersionData(outputId);
	
	//Set MetaVersion for content
	setMetaVersionData(outputId);

	// Redirect to screen: contentview     
	//$('body,html').animate({ scrollTop: 0 }, 0);
	ClientData.IsRefresh(false);
	
	avwScreenMove(ScreenIds.ContentView);
};

// Show detail content
function ShowContent(contentID, contentTitle, contentDetail, contentThumbnail, deliveryDate, pages) {
    $("#txtPubDt2_Dsp").text(deliveryDate.jpDateString() + " " + deliveryDate.jpShortTimeString());
    $("#txtContentDetail").text(contentDetail);
    $("#txtContentTitle").text(contentTitle);
    
    $("#imgContentThumbnail").attr("src", contentThumbnail);
    var imgTemp = new Image();

    imgTemp.onload = function () {

        //resize Image
        if (imgTemp.width > imgTemp.height) {

            $("#imgContentThumbnail").attr('height', '');
            $("#imgContentThumbnail").removeAttr('height');
            $("#imgContentThumbnail").attr('width', '120');
            var realHeight = (120 * imgTemp.height) / imgTemp.width;
            $("#imgContentThumbnail").css('padding-top', (145 - realHeight)/2 + "px");
        }
        else {
            $("#imgContentThumbnail").attr('width', '');
            $("#imgContentThumbnail").removeAttr('width');
            $("#imgContentThumbnail").attr('height', '120');

            $("#imgContentThumbnail").css('padding-top', "12px");
        }

    };
    	
    imgTemp.src = contentThumbnail;
    
    //resizeThumbnailContentDetail(contentThumbnail, 120, 160);
    // Show pages
    for (var nIndex = 0; nIndex < pages.length; nIndex++) {
        //insertRow(imgSample, pages[nIndex].pageText, pages[nIndex].pageNo);
        insertRow(pages[nIndex].pageThumbnail, truncate(getLines(pages[nIndex].pageText, 3), 55), pages[nIndex].pageNo);
    }
};


function insertRow(pageThumbnail, pageText, pageNo) {
    var newRow = "";
    newRow += "<ul>";
    newRow += '<li class="list_img"><img src="' + pageThumbnail + '" alt="" width="90" /></li>';
    newRow += '<li class="list_title"><label>' + htmlEncode(pageText) + '</label></li>';
    newRow += '<li class="page"><label id="Label2" class="lang" lang="txtPage">' + i18nText('txtPage') + '</label>' + pageNo + '</li>';
    newRow += "</ul>";

    $('#book_list').append(newRow);
    i18nReplaceText();
    
    //Resize Image
    var imgTemp = new Image();
    
    imgTemp.onload = function(){
    		
    	if(imgTemp.width > imgTemp.height) {
    			
    		$("li.list_img img").attr('height', '');
    		$("li.list_img img").removeAttr('height');
    		$("li.list_img img").attr('width', '90');
    	}
    	else {
    		$("li.list_img img").attr('width', '');
    		$("li.list_img img").removeAttr('width');
    		$("li.list_img img").attr('height', '90');
    	}
	};
    	
    imgTemp.src = pageThumbnail;
};

function insertRow1(pageThumbnail, pageText, pageNo) {
    var newRow = "";
    newRow += "<tr>";
    newRow += "<td id='left'>";
    newRow += '<img src="' + pageThumbnail;
    newRow += '" id="imgPageThumbnail" alt="" width="50" height="50"/>';
    newRow += "</td>";
    newRow += "<td>";
    newRow += '<div><label id="Label1">' + pageText + '</label></div>';
    newRow += '<div><label id="Label2" class="lang" lang="txtPage">ページ:</label><label id="Label3">' + pageNo + '</label></div>';
    newRow += "</td>";
    newRow += "</tr>";

    $('#contentdetail_grid tr:last').after(newRow);
    //changeLanguage(ClientData.userInfo_language());
    i18nReplaceText();
    
};

//set resource version data
function setResourceVersionData(conId){	
	var tempResourceArr;
	var tempResource;
	//check if insert new or edit
	var flag = false;
	
	if(ClientData.ResourceVersion().length <= 0 || ClientData.ResourceVersion() == null || ClientData.ResourceVersion() == 'undefined'){
		tempResourceArr = [];
	}
	else{
		tempResourceArr = ClientData.ResourceVersion();
	}
		
	for(var i = 0; i < resourceVersionArr.length; i++){
		if(resourceVersionArr[i].contentid == conId){
			tempResource = resourceVersionArr[i].resourceversion;
			break;
		}
	}
	
	if(tempResourceArr.length > 0){
		for(var j = 0; j < tempResourceArr.length; j++){
			if(tempResourceArr[j].contentid == conId){
				tempResourceArr[j].resourceversion = tempResource;			
				flag = true;
				break;
			}
			else{
				flag = false;
			}
		}
		
		if(!flag){
			tempResourceArr.push({contentid: conId, resourceversion: tempResource});
		}
		
	}else{
		tempResourceArr.push({contentid: conId, resourceversion: tempResource});
	}
			
	ClientData.ResourceVersion(tempResourceArr);
};

//set meta Version Data
function setMetaVersionData(conId){
	
	var tempMetaArr;
	var tempMeta;
	//check if insert new or edit
	var flag = false;
	
	if(ClientData.MetaVersion().length <= 0 || ClientData.MetaVersion() == null || ClientData.MetaVersion() == 'undefined'){
		tempMetaArr = [];
	}
	else{
		tempMetaArr = ClientData.MetaVersion();
	}
		
	for(var i = 0; i < metaVersionArr.length; i++){
		if(metaVersionArr[i].contentid == conId){
			tempMeta = metaVersionArr[i].metaversion;
			break;
		}
	}
	
	if(tempMetaArr.length > 0){
		for(var j = 0; j < tempMetaArr.length; j++){
			if(tempMetaArr[j].contentid == conId){
				tempMetaArr[j].metaversion = tempMeta;			
				flag = true;
				break;
			}
			else{
				flag = false;
			}
		}
		
		if(!flag){
			tempMetaArr.push({contentid: conId, metaversion: tempMeta});
		}
		
	}else{
		tempMetaArr.push({contentid: conId, metaversion: tempMeta});
	}
			
	ClientData.MetaVersion(tempMetaArr);
};

function formatNormalDate(day, month, year) {
    var outputDate = year + '/' + (('' + month).length < 2 ? '0' : '') + month + '/' + (('' + day).length < 2 ? '0' : '') + day;

    return outputDate;
};

//function contentdetail_dspBack_Click() {
    //parent.history.back();
    //$(this).parent().parent().parent().parent().parent().parent().parent().hide();
    //$(this).parent().parent().parent().parent().parent().parent().parent().dialog('close');
    
//}

/*
----------------------------------------------------------------------------
Event groups [ end ]
----------------------------------------------------------------------------
*/



/*
----------------------------------------------------------------------------
Setting dialog [start]
----------------------------------------------------------------------------
*/
$(function () {
     
});


/*
----------------------------------------------------------------------------
Setting dialog [ end ]
----------------------------------------------------------------------------
*/
function truncate(strInput, length){
    if (strInput.length <= length)
    {
        return strInput;
    }
    else
    {
        return strInput.substring(0, length) + "...";
    }
};

function resetLoadingImageSize(){
	$("#imgContentThumbnail").attr('height','25px');
	$("#imgContentThumbnail").attr('width','25px');
};