/* 
 This file was generated by Dashcode.  
 You may edit this file to customize your widget or web page 
 according to the license.txt file included in the project.
 */

var topStories = parseInt(attributes.topStories);       // The number of stories featured in the top section

//
// Function: load()
// Called by HTML body element's onload event when the web application is ready to start
//
function load()
{
	initComment();
    rssLoad();
    dashcode.setupParts();
    
    var feedName = document.getElementById("feedName");
	feedName.innerText = document.title;
    
    var todaysDate = document.getElementById("todaysDate");
	if (tyb_attributes.dateFormat == "jp") {
		todaysDate.innerText = createDateStr(new Date(), "jp", false);
	} else {
		todaysDate.innerText = createDateStr(new Date(), "en", false).toUpperCase();
	}
}


// This object implements the dataSource methods for the list.
var headlineList = {
    
    // The List calls this method to find out how many rows should be in the list.
numberOfRows: function() {
    if (feedResults == null)
        return 0;           // Return 0 if there are no results to load 
    else
        if (feedResults.length > topStories)
            return topStories;          // Else return the number of headlined items (default: 3)
        else
            return feedResults.length;
},
    
    // The List calls this method once for every row.
prepareRow: function(rowElement, rowIndex, templateElements) {
    // The List calls this dataSource method for every row.  templateElements contains references to all elements inside the template that have an id. We use it to fill in the text of the rowTitle element.
    if (templateElements.headlineTitle) {
        templateElements.headlineTitle.innerText = extractText(feedResults[rowIndex].title);
    }
    
    if (templateElements.headlineDate) {
        templateElements.headlineDate.innerText = createDateStr(feedResults[rowIndex].date, tyb_attributes.dateFormat, true);
    }

    if (templateElements.headlineDescription) {
        templateElements.headlineDescription.innerText = extractText(feedResults[rowIndex].description);
    }
    
    // We also assign an onclick handler that will cause the browser to go to the detail page.
    var self = this;
    var handler = function() {
        detailController.setRepresentedObject(rowIndex);
        document.getElementById("StackLayout").object.setCurrentView("articlePage", false, true);
    };
    rowElement.onclick = handler;
	
    var exButton = document.getElementById("exButton");
	if (tyb_attributes.exButtonLink.length != 0) {
		exButton.style.display = 'block';
		exButton.object.onclick = onclickExButton;
		exButton.object.setText(tyb_attributes.exButtonLabel);
	} else {
		exButton.style.display = 'none';
	}

	setTimeout(function(){window.scrollTo(0, 1);}, 100);
}
};


// This object implements the dataSource methods for the list.
var secondHeadlineList = {
    
    // The List calls this method to find out how many rows should be in the list.
numberOfRows: function() {
    if (feedResults == null)
        return 0;                       // Return 0 if there are no results to load 
    else
        if (feedResults.length > topStories)
            return (feedResults.length-topStories);         // Else return the number of headlined items (default: 3)
        else
            return 0;
},
    
    // The List calls this method once for every row.
prepareRow: function(rowElement, rowIndex, templateElements) {
    // templateElements contains references to all elements that have an id in the template row.
    // Ex: set the value of an element with id="label".
    var tempRow = rowIndex + topStories;
    if (templateElements.secondHeadlineTitle) {
        templateElements.secondHeadlineTitle.innerText = extractText(feedResults[tempRow].title);
    }
    
    if (templateElements.secondHeadlineDate) {
        templateElements.secondHeadlineDate.innerText = createDateStr(feedResults[tempRow].date, tyb_attributes.dateFormat, true);
    }
    
    // We also assign an onclick handler that will cause the browser to go to the detail page.
    var self = this;
    var handler = function() {
        detailController.setRepresentedObject(tempRow);
        document.getElementById("StackLayout").object.setCurrentView("articlePage", false, true);
    };
    rowElement.onclick = handler;
}
};

var detailController = {
    // This object acts as a controller for the detail UI.
    
setRepresentedObject: function(representedObject) {
    // To start, the represented object of our detail controller is simply a string, the title of the list row that the user chose.  You may want to make the represented object any kind of object when you customize the template.
    this._representedObject = representedObject;
    
    // When the represented object is set, this controller also updates the DOM for the detail page appropriately.  As you customize the design for the detail page, you will want to extend this code to make sure that the correct information is populated into the detail UI.
    var title = document.getElementById('articleTitle');
    title.innerText = extractText( feedResults[this._representedObject].title );
    var article = document.getElementById('articleDescription');
    article.innerHTML = extractHTML( feedResults[this._representedObject].description );
    var date = document.getElementById('articleDate');
    date.innerText = createDateStr(feedResults[this._representedObject].date, tyb_attributes.dateFormat, true);

    var self = this;
    var moreLink = document.getElementById('readMore');
    moreLink.object.onclick = function() {
        window.location = feedResults[self._representedObject].link;
    };
    var backLink = document.getElementById('backToHeadlines');
    backLink.object.onclick = articlePageBackHandler;
	
    var articleBack = document.getElementById("articleBack");
	articleBack.object.onclick = articlePageBackHandler;
	
    var footer = document.getElementById("footer");
	footer.style.display = 'none';

	var commentCount = feedResults[this._representedObject].commentCount;
	var commentLink = document.getElementById('commentBtn');
	
	if (commentCount != null && tyb_attributes.displayComment) {
		commentLink.object.setText("コメント（" + commentCount.toString() + "）");	// setText()じゃないとボタンが変になる
		commentLink.object.setEnabled(true);
		
	} else {
		commentLink.style.display = 'none';
	}

	commentLink.object.onclick = function() {
		commentController.setRepresentedObject(self._representedObject);
		document.getElementById("StackLayout").object.setCurrentView("commentPage", false, true);
	};
}
};

function articlePageBackHandler()
{
    var footer = document.getElementById("footer");
	footer.style.display = 'block';

	document.getElementById("StackLayout").object.setCurrentView("frontPage", true);
}


var commentController = {
    // This object acts as a controller for the detail UI.
    
setRepresentedObject: function(representedObject) {
    // To start, the represented object of our detail controller is simply a string, the title of the list row that the user chose.  You may want to make the represented object any kind of object when you customize the template.
    this._representedObject = representedObject;

// make comment
	var commentStr = "";
	var commentCount = feedResults[this._representedObject].commentCount;
	
	var comment = document.getElementById('commentBody');
	if (commentCount != null) {
		var commentID = feedResults[this._representedObject].commentID;
		var commentAuthor = feedResults[this._representedObject].commentAuthor;
		var commentDate = feedResults[this._representedObject].commentDate;
		var commentBody = feedResults[this._representedObject].commentBody;
		
		for (var i = 0; i < commentCount; i++) {
			if (i > 0) {
				commentStr = commentStr + "<hr />";
			}
			commentStr = commentStr + "<p><span class=\"commeName\">" + commentAuthor[i] + "</span><br>";
			commentStr = commentStr + "<span class=\"commeDate\">" + createDateStr(commentDate[i], tyb_attributes.dateFormat, true) + "</span></p>";
			commentStr = commentStr + commentBody[i].innerText;
		}
		if (commentStr.length > 0) {
			comment.innerHTML = commentStr;
		} else {
			comment.innerHTML = "コメントがありません";
		}
		
	} else {
		comment.innerHTML = "コメントがありません";
	}

// back button handler
    var backLink = document.getElementById('backToArticle');
    backLink.object.onclick = commentPageBackHandler;

    var commentBack = document.getElementById("commentBack");
	commentBack.object.onclick = commentPageBackHandler;
	
	var indicator = document.getElementById('activityIndicator');
	indicator.style.display = 'none';

	var commeSubmit = document.getElementById('commeSubmit');
	if (tyb_attributes.submitComment) {
// initialize form
		var bakeCookie = document.getElementById('comment-bake-cookie');
		bakeCookie.checked = true;

		var commentForm = document.getElementById('comments-form');
		commentForm.entry_id.value = feedResults[this._representedObject].entryID;

		var cookieData;
		cookieData = getCookie("commentAuthor")
		if (cookieData) {
			document.getElementById('comment-author').value = cookieData;
		}
		cookieData = getCookie("commentEMail")
		if (cookieData) {
			document.getElementById('comment-email').value = cookieData;
		}
		cookieData = getCookie("commentURL")
		if (cookieData) {
			document.getElementById('comment-url').value = cookieData;
		}

// comment button handler
		commeSubmit.object.onclick = function() {
			if (document.getElementById('comment-text').value.length == 0){
				alert("コメントを投稿できませんでした。コメントを記入してください。");
				return;
			}

			if ((tyb_attributes.requireEMail && document.getElementById('comment-email').value.length == 0)
				|| (document.getElementById('comment-author').value.length == 0)) {
				alert("コメントを投稿できませんでした。名前とメールアドレスを記入してください。");
				return;
			}
			
			document.getElementById('commeSubmit').object.setEnabled(false);
			document.getElementById('backToArticle').object.setEnabled(false);

			var indicator = document.getElementById('activityIndicator');
			indicator.style.display = 'block';
			indicator.object.startAnimation();
			
			setiRSSCookie(document.comments_form);
			commentPost(document.comments_form, representedObject);
		};
		
	} else {
		var commentFormBox = document.getElementById('formBox');
		commentFormBox.style.display = 'none';
		commeSubmit.style.display = 'none';
	}
}
};

function commentPageBackHandler()
{
	document.getElementById("StackLayout").object.setCurrentView("articlePage", true);
}

//
// クッキー処理関数 
//
function setiRSSCookie(f)
{
	var exp = new Date();
	exp.setTime(exp.getTime() + 1000 * 60 * 60 * 24 * 30);	// 30days

	var temp = "commentAuthor=" + escape(f.author.value) + "; expires=" + exp.toGMTString();
	document.cookie = temp;
	temp = "commentEMail=" + escape(f.email.value) + "; expires=" + exp.toGMTString();
	document.cookie = temp;
	temp = "commentURL=" + escape(f.url.value) + "; expires=" + exp.toGMTString();
	document.cookie = temp;
}

function setCookie(key, val)
{
	var temp = key + "=" + escape(val) + ";";
	document.cookie = temp;
}

function getCookie(key)
{
	var temp = document.cookie + ";";
	var pos = temp.indexOf(key, 0);
	if (pos != -1) {
		temp = temp.substring(pos, temp.length);
		var st=temp.indexOf("=", 0) + 1;
		var ed = temp.indexOf(";", st);
		return (unescape(temp.substring(st, ed)));
	}
	return ("");
}

function delCookie(key)
{
	var name_c = key + "=";
	var timeday = new Date();
	timeday.setYear(timeday.getYear() - 1);
	var temp = name_c + ";expires=" + timeday.toGMTString();
	document.cookie = temp;
}


function onclickBlogName(event)
{
	if (tyb_attributes.MyBlogURL.length != 0) {
		window.location = tyb_attributes.MyBlogURL;
//		window.open(tyb_attributes.MyBlogURL);
	}
}


function onclickExButton(event)
{
	if (tyb_attributes.exButtonNewWindow) {
		if (tyb_attributes.exButtonLink.length != 0) {
//			window.open(tyb_attributes.exButtonLink);
			window.open(tyb_attributes.exButtonLink, '_new');
		}
	} else {
		if (tyb_attributes.exButtonLink.length != 0) {
			window.location = tyb_attributes.exButtonLink;
		}
	}
}
