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

var resourceIdDetail="";

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


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

    //openContentDetail();


});

// Show content detail
function openContentDetail() {
	if(!isPdfContent(ClientData.contentInfo_contentType())){
//		$("#book_data").css('border-right','0');
//		$("#book_data").css('float','none');
//		$("#book_data").css('background-color','white');
//		$("#book_data").css('margin-left','auto');
//		$("#book_data").css('margin-right', 'auto');

		$('#sectionContentDetail').removeClass().addClass('sectiondetailnopdf');
	}else
	{
//		$("#book_data").css('border-right','2px solid #CCC');
//		$("#book_data").css('float','left');
//		$("#book_data").css('background-color', '#f7f7f7');

		$('#sectionContentDetail').removeClass().addClass('sectiondetail');
	}
	
    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);

    COMMON.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) {
                	
                	 var contentType = ClientData.contentInfo_contentType();
        			
        			 // Get content detail
                     displayData.contentTitle = data.contentData.contentName;
                     displayData.contentDetail = data.contentData.contentDetail;
                     displayData.deliveryDate = COMMON.convertToDate(data.contentData.deliveryStartDate);
                                       
                    //Start Function : No.12 -- Editor : Viet Nguyen -- Date : 08/01/2013 -- Summary : Create new function to return content type of content.                   
			        
				    if(!isPdfContent(contentType)){				    				    	 	
				        ShowContentNotPDF(displayData.contentTitle,displayData.contentDetail,displayData.contentThumbnail,displayData.deliveryDate);
				    }else{				    	 
	                    // 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, COMMON.truncate(displayData.contentTitle, 20), displayData.contentDetail, ClientData.contentInfo_contentThumbnail(), displayData.deliveryDate, displayData.pages);                                                           		                               
	                                },
	                                null
	                    );
                   }
                   
                   //End Function : No.12 -- Editor : Viet Nguyen -- Date : 08/01/2013 -- Summary : Create new function to return content type of content.

                },
                null
    );
  
};

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

function contentdetail_dspRead_Click(e) {
    e.preventDefault();
    var outputId = ClientData.contentInfo_contentId();

    checkLimitContent(outputId,
        function () {
            contentdetail_dspRead_Click_callback(outputId);
        },
        function(){
        },
        1
    );
};

function contentdetail_dspRead_Click_callback(outputId) {

    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);

    if (ClientData.contentInfo_contentType() == COMMON.ContentTypeKeys.Type_Others) {
        // Get content detail
        HEADER.downloadResourceById(ClientData.contentInfo_contentId());
    }
    else if(ClientData.contentInfo_contentType() == COMMON.ContentTypeKeys.Type_Link){
        // Get content detail
        HEADER.viewLinkContentById(ClientData.contentInfo_contentId());
    }
    else {
        avwScreenMove(COMMON.ScreenIds.ContentView);
    }
};

//Start Function : No.12 -- Editor : Viet Nguyen -- Date : 08/01/2013 -- Summary : Create new function to return content type of content.

///* get url */
//function getURL(apiName) {
//    var sysSettings = avwSysSetting();
//    var url = sysSettings.apiResourceDlUrl;
//    url = AVWEB.format(url, ClientData.userInfo_accountPath()) + '/' + apiName;
//    return url;
//};

//Check content type is pdf content
function isPdfContent(contentType){
    if(!(contentType == COMMON.ContentTypeKeys.Type_PDF)){
        return false; 
    }
    else{
        return true;
    }
};


function ShowContentNotPDF(contentTitle, contentDetail, contentThumbnail, deliveryDate) {	
    $("#txtPubDt2_Dsp").text(deliveryDate.jpDateString() + " " + deliveryDate.jpShortTimeString());
    $("#txtContentDetail").text(contentDetail);
    $("#txtContentTitle").text(contentTitle);
    
    var tempContentType = ClientData.contentInfo_contentType();
    
    if(contentThumbnail == '' || contentThumbnail == null || contentThumbnail == 'undefined'){
        if(!isPdfContent(tempContentType)){
            var src = HEADER.getThumbnailForOtherType(contentType);
            if( src != '' ){
                contentThumbnail = src;
            }
        }
    }else{
        contentThumbnail = contentThumbnail;
    }
   
    var imgTemp = new Image();
    $("#imgContentThumbnail").attr("src", contentThumbnail);
    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;
};

//End Function : No.12 -- Editor : Viet Nguyen -- Date : 08/01/2013 -- Summary : Create new function to return content type of content.

// 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, COMMON.truncate(COMMON.getLines(pages[nIndex].pageText, 3), 45), pages[nIndex].pageNo); //55
    }
};


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"><a href="#">' + COMMON.htmlEncode(pageText) + '</a></li>';
    newRow += '<li class="page"><label id="Label2" class="lang" lang="txtPage">' + I18N.i18nText('txtPage') + '</label>' + pageNo + '</li>';
    newRow += "</ul>";

    $('#book_list').append(newRow);
    I18N.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());
    I18N.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');
};
