// ////////////////////////////////////////////////////////////////////////////
// Symbian Foundation Example Code
//
// This software is in the public domain. No copyright is claimed, and you 
// may use it for any purpose without license from the Symbian Foundation.
// No warranty for any purpose is expressed or implied by the authors or
// the Symbian Foundation. 
// ////////////////////////////////////////////////////////////////////////////

var bugzillaTableStyle = "bugzilla";
var mypackage;
var open_reader;
var proposed_reader;
var features_reader;
var newtext ="New Bugs";
var proposedtext ="Proposed Fixes";
var featurestext = "My Feature Backlog";
var forum_reader;
var open_presenter;
var features_presenter;
var proposed_presenter;
var mybuilds;
var mercurial_reader = null;

// Bugzilla access 

function BugzillaSearchPanel(parent) {
	
	//ListView.prototype.init.call(this, null, null);	

	// add the banner and 'title bar' - avoids the caption bug
	this.openButton = new NavigationButton (1,"right.gif", newtext);
	this.ProposedButton = new NavigationButton (1,"right.gif", proposedtext);
	this.featuresButton = new NavigationButton (1,"right.gif", featurestext);
	this.BuildButton = new NavigationButton (1,"right.gif", "Package Build Results");
	this.MercurialButton = new NavigationButton (1,"right.gif", "Latest Changes in Hg");
	this.ForumButton = new NavigationButton (1,"right.gif", "My Discussion Forum");
	
		
	var self = this;
	
	mylabel = new Label ("packagelabel",null);
	this.addControl (mylabel);
	
    this.openButton.addEventListener("ActionPerformed", function(){
		open_reader.update(true);
		open_reader.show();
	});
	
	this.addControl(this.openButton);
	
	this.ProposedButton.addEventListener("ActionPerformed", function(){
		
		proposed_reader.update(true);
		proposed_reader.show();
	});
	
	this.addControl(this.ProposedButton);
	
	this.featuresButton.addEventListener("ActionPerformed", function(){
		features_reader.update(true);
		features_reader.show();
	});
	
	this.addControl(this.featuresButton);
	
	mybuilds = new buildview(this);
	
	this.BuildButton.addEventListener("ActionPerformed", function(){
		//openURL (buildresultsUrl + Packageid);
		mybuilds.show();
	
		
	});
	
	this.addControl(this.BuildButton);
	
	
	this.MercurialButton.addEventListener("ActionPerformed", function(){
		self.readmercurial();
	});
	
	this.addControl(this.MercurialButton);
	
	
	this.ForumButton.addEventListener("ActionPerformed", function(){
		self.readforum();
	});
	
	this.addControl(this.ForumButton);
	
	mypackage=Packageid;	
	
	
	
	//self.update(true);
	
}


BugzillaSearchPanel.prototype = new ListView("bugzillaview","<img src=logo.png>");

BugzillaSearchPanel.prototype.update = function(myflag){
	var self = this;
	
	if (myflag) {
		self.openbugs();
		self.proposedbugs();
		self.features();
		mylabel.setText(Packageid);
		mybuilds.update(true);
		}
}

//http://developer.symbian.org/bugs/buglist.cgi?bug_status=UNCONFIRMED&bug_status=NEW&bug_status=ASSIGNED&content=test&field-1-0-0=bug_status&field-1-1-0=product&field-1-2-0=content&product=classicui&query_format=specific&remaction=&type-1-0-0=anyexact&type-1-1-0=anyexact&type-1-2-0=matches&value-1-0-0=UNCONFIRMED%2CNEW%2CASSIGNED&value-1-1-0=classicui&value-1-2-0=test&title=Bug%20List&ctype=atom
BugzillaSearchPanel.prototype.bugzillaSearchClicked = function() {
	// create the RssReader for bugzilla
	if(!Packageid){return;}
	var searchString = Packageid;
	var title = "Bugzilla: " + searchString;
	var url = symbianOrgBaseUrl + "/bugs/buglist.cgi?"
		+ "bug_status=NEW"
		+ "&field-1-0-0=bug_status&field0-0-0=product&"
		+ "&query_format=advanced&remaction=&type-1-0-0=anyexact"
		+ "&type0-0-0=substring&type0-0-3=substring"
		+ "&value-1-0-0=NEW"
		+ "&value0-0-0=" + searchString
		+ "&title=Bug List&ctype=atom";
	var reader = new RssReader(title, url, new BugzillaFeedPresenter(null), this, parseBugzillaFeed);
	reader.show();
}
BugzillaSearchPanel.prototype.openbugs = function() {
	// create the RssReader for bugzilla
	if(!Packageid){return;}
	mypackage=Packageid;
	var title = newtext + " : " + mypackage;
	var url = symbianOrgBaseUrl + "/bugs/buglist.cgi?"
		+ "bug_file_loc=&bug_file_loc_type=allwordssubstr&bug_id=&bug_status=NEW&bug_severity=Critical&bug_severity=Major&bug_severity=normal&bug_severity=Minor"
		+ "&bugidtype=include&chfieldfrom=&chfieldto=Now&chfieldvalue=&deadlinefrom=&deadlineto=&email1=&email2=&emailassigned_to1=1"
		+ "&emailassigned_to2=1&emailcc2=1&emailreporter2=1&emailtype1=substring&emailtype2=substring&field-1-0-0=product&field-1-1-0=bug_status&field-1-2-0=bug_severity&field0-0-0=noop&keywords=&keywords_type=allwords&long_desc=&long_desc_type=substring"
	    + "&product=" + mypackage
		+ "&query_format=advanced&remaction=&short_desc=&short_desc_type=allwordssubstr&"
		+ "type-1-0-0=anyexact"
		+ "&type-1-2-0=anyexact"
		+ "&type-1-1-0=anyexact&type0-0-0=noop&"
		+ "value-1-0-0=" + mypackage
		+ "&value-1-2-0=critical&Cmajor&normal&minor"
		+ "&value-1-1-0=NEW"
		+ "&value0-0-0=&title=Bug%20List&ctype=atom";
	open_presenter=new BugzillaFeedPresenter(null);
	open_reader = new RssReader(title, url, open_presenter, this, parseBugzillaFeed);
	open_reader.UpdateButton = this.openButton;
	open_reader.ButtonText=newtext;
	open_reader.update(true);
	
}
BugzillaSearchPanel.prototype.proposedbugs = function() {
	// create the RssReader for bugzilla
	if(!Packageid){return;}
	mypackage=Packageid;
	var title = proposedtext + " : " + mypackage;
	var url = symbianOrgBaseUrl + "/bugs/buglist.cgi?"
		+ "bug_file_loc=&bug_file_loc_type=allwordssubstr&bug_id=&bug_status=Proposed"
		+ "&bugidtype=include&chfieldfrom=&chfieldto=Now&chfieldvalue=&deadlinefrom=&deadlineto=&email1=&email2=&emailassigned_to1=1"
		+ "&emailassigned_to2=1&emailcc2=1&emailreporter2=1&emailtype1=substring&emailtype2=substring&field-1-0-0=product&field-1-1-0=bug_status&field-1-2-0=bug_severity&field0-0-0=noop&keywords=&keywords_type=allwords&long_desc=&long_desc_type=substring"
	    + "&product=" + mypackage
		+ "&query_format=advanced&remaction=&short_desc=&short_desc_type=allwordssubstr&"
		+ "type-1-0-0=anyexact"
		+ "&type-1-2-0=anyexact"
		+ "&type-1-1-0=anyexact&type0-0-0=noop&"
		+ "value-1-0-0=" + mypackage
		+ "&value-1-2-0=critical%2Cmajor%2Cnormal%2Cminor%2Cenhancement"
		+ "&value-1-1-0=PROPOSED"
		+ "&value0-0-0=&title=Bug%20List&ctype=atom";
	proposed_presenter=new BugzillaFeedPresenter(null);
	proposed_reader = new RssReader(title, url, proposed_presenter, this, parseBugzillaFeed);
	proposed_reader.UpdateButton = this.ProposedButton;
	proposed_reader.ButtonText=proposedtext;
	proposed_reader.update(true);
	
}

BugzillaSearchPanel.prototype.features = function() {
	// create the RssReader for bugzilla
	if(!Packageid){return;}
	mypackage=Packageid;
	var title = featurestext + " : " + mypackage;
	var url = symbianOrgBaseUrl + "/bugs/buglist.cgi?"
		+ "bug_file_loc=&bug_file_loc_type=allwordssubstr&bug_id=&bug_status=NEW&bug_status=ASSIGNED&bug_status=PROPOSED&bug_severity=Feature"
		+ "&bugidtype=include&chfieldfrom=&chfieldto=Now&chfieldvalue=&deadlinefrom=&deadlineto=&email1=&email2=&emailassigned_to1=1"
		+ "&emailassigned_to2=1&emailcc2=1&emailreporter2=1&emailtype1=substring&emailtype2=substring&field-1-0-0=product&field-1-1-0=bug_status&field-1-2-0=bug_severity&field0-0-0=noop&keywords=&keywords_type=allwords&long_desc=&long_desc_type=substring"
	    + "&product=" + mypackage
		+ "&query_format=advanced&remaction=&short_desc=&short_desc_type=allwordssubstr&"
		+ "type-1-0-0=anyexact"
		+ "&type-1-2-0=anyexact"
		+ "&type-1-1-0=anyexact&type0-0-0=noop&"
		+ "value-1-0-0=" + mypackage
		+ "&value-1-2-0=Feature"
		+ "&value-1-1-0=NEW&PROPOSED&ASSIGNED"
		+ "&value0-0-0=&title=Bug%20List&ctype=atom";
	features_presenter=new BugzillaFeedPresenter(null);
	features_reader = new RssReader(title, url, features_presenter, this, parseBugzillaFeed);
	features_reader.UpdateButton = this.featuresButton;
	features_reader.ButtonText=featurestext;
	features_reader.update(true);
	
}

BugzillaSearchPanel.prototype.readforum = function() {
	
	if (!myforumid) {
		var forum_choose = new RssReader(mypackage, forumsListUrl + "18", new ForumsSettingsFeedPresenter(null), bugzilla, forumListResponseParser);
		forum_choose.show();
	}
	else {
		forum_reader = new RssReader(myforumtitle, forumFeedURL + forumsForumSpecQuery + myforumid, new ThreadListFeedPresenter(null), bugzilla, null);
		forum_reader.show();
	}
}


BugzillaSearchPanel.prototype.readmercurial = function() {
	
	if (!mercurialUrl) {
		PackageMercurialUrl();	
	}
	
	var title = "Mercurial FCL " + Packageid;
		
	mercurial_reader = new RssReader(title, mercurialPackageUrl, new MercurialFeedPresenter(null), this, parseRepoFeed);
	debuglog.debug ("accessing mercurial package url: "+ mercurialPackageUrl);
	mercurial_reader.show();
	
}
function parseBugzillaFeed(broker, responseStatus, xmlDoc) {
    if (responseStatus == 200 && xmlDoc != null) {
        // node ref for iterating
        var node;

		// for compatibility with rss
		var lastModified = new Date();
		
        // init result items array
        var items = [];

		var itemElements = xmlDoc.getElementsByTagName("entry");
		
		for (var i = 0; i < itemElements.length; i++) {
            // iterate through child nodes of this item and gather
            // all the data we need for a feed item
            var title = null;
            var date = null;
            var description = null;
            var url = null;
            var author = null;
			var bugid;
            node = itemElements[i].firstChild;
            while (node != null) {
                if (node.nodeType == Node.ELEMENT_NODE) {
                    if (node.nodeName == "title") {
                        // item title
                        title = getTextOfNode(node);
						if ( title.length > 48) {
							title = title.substring(0,45) + "...";
						}
                    } else if (node.nodeName == "updated" ) {
                        // item publishing date
                        date = getTextOfNode(node);
                    } else if (node.nodeName == "summary" && !this.ignoreContent ) {
                        // item description
                        description = getTextOfNode(node);
                    } else if (node.nodeName == "link") {
                        // link URL
                        url = node.getAttribute("href");
						// extract bug id
						var ind = url.indexOf("?id=");
						if ( ind != -1 ) {
							bugid = url.substring(ind + 4);
							url = symbianOrgBaseUrl + "/bugtracker/show_bug.cgi?ctype=xml&id="+bugid;
						}
                    } else if (node.nodeName == "author" ) {
						author = getTextOfNode(node);
					}
                }
                node = node.nextSibling;
            }
            items.push({ title: title, date: date, description: description, url: url, author: author });
		}

        // update was completed successfully
        return { status: "ok", lastModified: lastModified, items: items };
    } else {
        // update failed
        return { status: "error" };
    }
}


// Implementation of FeedPresenter that shows feed as a clickable
// button and shows feed entry title as label
function BugzillaFeedPresenter(rssreader) {
	ButtonFeedPresenter.prototype.init.call(this, rssreader);
}

// BugzillaFeedPresenter is a subclass of ButtonFeedPresenter
BugzillaFeedPresenter.prototype = new ButtonFeedPresenter(null);

// Handle the button-press
BugzillaFeedPresenter.prototype.feedClicked = function(event){
	var clickedButton = event.source;
	var id = clickedButton.id;
	var url = this.items[id].url;
	var presenter = new HtmlFeedPresenter(null);
	presenter.expanded = true;
	var reader = new RssReader(this.items[id].title, url, 
		presenter, uiManager.currentView, parseBugzillaBugFeed);
	reader.show();
}


function parseBugzillaBugFeed(broker, responseStatus, xmlDoc) {
    if (responseStatus == 200 && xmlDoc != null) {
        // node ref for iterating
        var node;

		// for compatibility with rss
		var lastModified = new Date();
		
        // init result items array
        var items = [];

		var itemElements = xmlDoc.getElementsByTagName("bug");
		
		for (var i = 0; i < itemElements.length; i++) {
            // iterate through child nodes of this item and gather
            // all the data we need for a feed item
            var title = null;
            var date = null;
            var url = null;
            var author = null;
			var bugid = null;
			var creationTime = "Not specified";
			var product = "Not specified";
			var component = "Not specified";
			var classification = "Not specified";
			var op_sys = "Not specified";
			var bug_status = "Not specified";
			var bug_file_loc = "Not specified";
			var priority = "Not specified";
			var severity = "Not specified";
			var target_milestone = "Not specified";
			var version = "Not specified";
			var platform = "Not specified";
			var assignedToName = "Not specified";
			var solutionDetails = "Not specified";
			var keywords = "None";
			var longdesc = "";
			var shortDesc = "";
			var bugid = "";
			var buglink = "";
			
            node = itemElements[i].firstChild;
            while (node != null) {
                if (node.nodeType == Node.ELEMENT_NODE) {
                    if (node.nodeName == "bug_id") {
                        // item title
                        bugid = "Bug " + getTextOfNode(node);
						buglink = bugUrl + getTextOfNode(node);
                    } else if (node.nodeName == "updated" ) {
                        // item publishing date
                        date = getTextOfNode(node);
                    } else if (node.nodeName == "creation_ts" ) {
                        // item publishing date
                        creationTime = getTextOfNode(node);
                    } else if (node.nodeName == "short_desc" && !this.ignoreContent ) {
                        // item description
                        title = getTextOfNode(node);
                    } else if (node.nodeName == "reporter" ) {
						author = getTextOfNode(node);
					} else if (node.nodeName == "product" ) {
                        product = getTextOfNode(node);
					} else if (node.nodeName == "component" ) {
                        component = getTextOfNode(node);
					} else if (node.nodeName == "classification" ) {
                        classification = getTextOfNode(node);
					} else if (node.nodeName == "version" ) {
                        version = getTextOfNode(node);
					} else if (node.nodeName == "op_sys" ) {
                        op_sys = getTextOfNode(node);
					} else if (node.nodeName == "bug_status" ) {
                        bug_status = getTextOfNode(node);
					} else if (node.nodeName == "bug_file_loc" ) {
                        bug_file_loc = getTextOfNode(node);
					} else if (node.nodeName == "priority" ) {
                        priority = getTextOfNode(node);
					} else if (node.nodeName == "bug_severity" ) {
                        severity = getTextOfNode(node);
					} else if (node.nodeName == "target_milestone" ) {
                        target_milestone = getTextOfNode(node);
					} else if (node.nodeName == "platform" ) {
                        platform = getTextOfNode(node);
					} else if (node.nodeName == "cf_solutiondetails" ) {
                        solutionDetails = getTextOfNode(node);
					} else if (node.nodeName == "keywords" ) {
                        keywords = getTextOfNode(node);
					} else if (node.nodeName == "long_desc" ) {
                        longdesc += "<br><table style="+bugzillaTableStyle+">";
						var ld_nodes = node.childNodes;
						for ( var tmp = 0 ; tmp < ld_nodes.length ; tmp++ ) {
	                        longdesc += "<tr><td>" 
								+ getTextOfNode(ld_nodes[tmp]) + "</td></tr>";
						}
                        longdesc += "</table>";
					} else if (node.nodeName == "assigned_to" ) {
                        assignedToName = getTextOfNode(node);
					} 
                }
                node = node.nextSibling;
            }
			// format the description
			
			   var mybuf = "<br><div class=\"FeedItemLink\">";
	           mybuf += "<a href=\"JavaScript:void(0)\" onclick=\"openURL('" + buglink + "'); return false;\">";
    	       mybuf += "Click here to edit...";
        	   mybuf += "</a>";
        	   mybuf += "</div><br>";
			var description = "<table style="+bugzillaTableStyle+">";
			description += "<tr><td>Reported:" + "</td><td>" + creationTime + "</td></tr>";
			description += "<tr><td>Product:" + "</td><td>" + product + "</td></tr>";
			description += "<tr><td>Component:" + "</td><td>" + component + "</td></tr>";
			description += "<tr><td>Classification:" + "</td><td>" + classification + "</td></tr>";
		//	description += "<tr><td>Operating system:" + "</td><td>" + op_sys + "</td></tr>";
			description += "<tr><td>Status:" + "</td><td>" + bug_status + "</td></tr>";
			description += "<tr><td>Priority:" + "</td><td>" + priority + "</td></tr>";
			description += "<tr><td>Severity:" + "</td><td>" + severity + "</td></tr>";
			description += "<tr><td>Version:" + "</td><td>" + version + "</td></tr>";
		//	description += "<tr><td>Platform:" + "</td><td>" + platform + "</td></tr>";
			description += "<tr><td>Reported by:" + "</td><td>" + author + "</td></tr>";
			description += "<tr><td>Assigned to:" + "</td><td>" + assignedToName + "</td></tr>";
		//	description += "<tr><td>Target milestone:" + "</td><td>" + target_milestone + "</td></tr>";
		//	description += "<tr><td>File location:" + "</td><td>" + bug_file_loc + "</td></tr>";
			description += "<tr><td>keywords:" + "</td><td>" + keywords + "</td></tr>";
			description += "</table>";
			
			description +=  mybuf ;
			
			description += "<table style="+bugzillaTableStyle+">";
			description += "<tr><td>Description:" + "</td></tr>";
			description += "<tr><td>" + longdesc + "</td></tr>";
			description += "</table>";
			
			description += "<table style="+bugzillaTableStyle+">";
			description += "<tr><td>Solution details:" + "</td></tr>";
			description += "<tr><td>" + solutionDetails + "</td></tr>";
			description += "</table>";			
			
            items.push({ title: title, date: date, description: description, url: null, author: author });
		}

        // update was completed successfully
        return { status: "ok", lastModified: lastModified, items: items };
    } else {
        // update failed
        return { status: "error" };
    }
}

