var tags;

var guid = getParameter('guid');

// check if query string exists :: if not, escape
if (document.URL.indexOf('guid=') == -1) {
	window.location = "/en/experience/news/";
}

//Function to set Permalink value
function setPermalink(){
    document.permalink.url.value = location.href;
}
    
    
//Face Book Link Code
function fbs_click() {
    u=location.href;t=document.title;window.open("http://www.dodge.com/en/experience/news/bounce.html?item="+encodeURIComponent('http://www.facebook.com/sharer.php?u=')+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');return false;
}


//Link function for delicious
function delicious_click(){
    u=location.href;t=document.title;window.open("http://www.dodge.com/en/experience/news/bounce.html?item="+encodeURIComponent('http://del.icio.us/post?url=')+encodeURIComponent(u),'delicious');return false;
    
}

//Link function for Digg
function digg_click(){
    
    var pageData = feeds.getArticleByGUID(guid);
    
    //Get Text of description
    var descStorage = new Element('div', {});
	descStorage.setHTML(pageData['description']);
	var metaDesc = descStorage.getText().substring(0, 150) + "...";
   
    u=location.href;t=document.title;window.open("http://www.dodge.com/en/experience/news/bounce.html?item="+encodeURIComponent('http://digg.com/submit?url='+u+'&bodytext='+metaDesc+'&title='+pageData['title']+'&media=news&topic=autos'),'digg');return false;
}

//Share News Story Javascript

function setFormValidationRequirements(arg_formObj) {

    
    // Only proceed if rssDoc is not Null
	if (!arg_formObj) {
		setTimeout("setFormValidationRequirements("+arg_formObj+");", 1000);
		return;
	}
		
		
    // these will be validated all the time
    arg_formObj.FromName.required = "Your Name";
    arg_formObj.FromAddress.required  = "Your Email Address";
    arg_formObj.ToName.required = "Your Friends Name";
    arg_formObj.ToAddress.required = "Your Friends Email Address";
    
    // these will be validated only if filled in:
    arg_formObj.FromAddress.subtype = "email";
    arg_formObj.ToAddress.subtype = "email";
   
}


function submitForm(){
    document.tellafriend.submit();
}

function submitTellaFriend(form_id){

    var pageData = feeds.getArticleByGUID(guid);
    
    var validation = validateForm(form_id);

    $('form_messages').setStyle('display','none');
    
    if(validation){
        var params = "";
        params += "URLFail=/flash/forms/error.html";
        params += "&URLOK=/flash/forms/thankyou.html";
        //params += "&ecardhost="+location.hostname;
        //params += "&ecardtarget=/en/experience/news/articles/";
        params += "&URLTemplate=mailer%2Ftemplates%2Fsaf_by_parameters_nogreet.txt";
        params += "&params="+escape("&guid=" + guid);
        //params += "&MailFormat=text%2Fhtml";
        params += "&Subject=Check This Out: " + pageData['title'];
        params += "&bodytext=This message was sent from "+form_id.FromName.value+" " + "<" + form_id.FromAddress.value + ">.\nThis name and address were not verified.\n\n\n\nHI,\n\nI thought you might be interested in the following article I found on dodge.com.\n\n"+ pageData['title'] + "\n\nTo read this article, go to:\nhttp://www.dodge.com/en/experience/news/articles/?guid=" + guid + "\n\n\nFor More Dodge News, go to:\nhttp://www.dodge.com/en/experience/news/ \n\n\n\nThis e-mail was sent from www.dodge.com. Please do not reply to this e-mail as it is unmonitored.\n\nDodge e-mail Headquarters, 880 W. Long Lake Road, Troy MI 48098,(800) 946-0600";
        params += "&prelinktext=";
        params += "&salutation=";
        params += "&FromName="+form_id.FromName.value;
        params += "&ToName=";
        params += "&FromAddress="+form_id.FromAddress.value;
        params += "&ToAddress="+form_id.ToAddress.value;
        makePOSTRequest('/mailer/oo_mailer_encoding.jsp', params, 'tellaFriendResult(http_request[i].responseXML, http_request[i].responseText)');
        submitClicked = false;
        form_id.ToAddress.value = "";
        form_id.ToName.value = "";
    }else{
        return false;
    }
 }
  
 function tellaFriendResult(xmlObj, xmlText){
	var was_success = xmlText.split("true");
    if (was_success[1]) {
		 $('form_messages').setHTML('<b>MESSAGE SENT</b> <br />Your friend will now get this article sent to them. Thanks for your interest.<br /><br /><a class="submitButton" href="javascript:void(0);" onclick="return closeMessage()">OK</a>');
		   document.tellafriend.ToAddress.value = "";
    } else {
         $('form_messages').setHTML('<b>ERROR</b> <br />We are unable to tell your friend about this article. Please make sure you have completed all of the required fields and try again.<br /><br /><a class="submitButton" href="javascript:void(0);" onclick="return closeMessage()">OK</a>');
    }
    
     $('form_messages').setStyle('display','block');
     $('tell_a_friend').setStyle('display','none');
  }


function closeMessage(){
    $('form_messages').setStyle('display','none');
    $('tell_a_friend').setStyle('display','block');
}

function buildArticle(){

        // Only proceed if feeds have been loaded
		if (!feeds.feedLoaded) {
			setTimeout("buildArticle();", 1000);
			return;
		}
		
		var newsArticle = feeds.getArticleByGUID(guid);
		
		//Build out main article
		var rss_output = "";
		
		if(newsArticle['source']){
		    rss_output +="<h1 class=\"pr\">PRESS RELEASE:</h1>";
		}
		
		if(newsArticle['pubDate']){
		    rss_output +="<p>"+newsArticle['pubDate']+"</p>";
		}
		
		if(newsArticle['title']){
		    rss_output +="<h1>"+newsArticle['title']+"</h1>";
		}
		
		if(newsArticle['enclosure']){
		    rss_output +="<img src=\""+newsArticle['enclosure']+"\" />";
		}
		
		rss_output +="<div id=\"description\">";
		rss_output += newsArticle['description'];
		
		if(newsArticle['source']){
		    rss_output += "<p><strong>Source:"+newsArticle['source']+"</strong></p>";
		}
	
		rss_output +="</div>";
		
		//Output Data
		$('article_content').setHTML(rss_output);
		
	    //Get Realted Subject Links
		buildRelatedSubjects(newsArticle);
		
		//Get Article Links
		buildArticleLinks(newsArticle);
		
		//Get Related Article Links
		buildRelatedLinks(newsArticle);
		
		//Set Share Forms up
        setShareForms();
}

function buildRelatedSubjects(newsArticle){
        //Find Related Subjects Links
		var rss_output = "";
		var pathname = "/en/experience/news/archive/index.html?subject=";
		
		rss_output +="<ul>";
	    rss_output +="<li><h2>Find Out About</h2></li>";
	    
	    //Loop Thru Category Array to find Subjects that are Public
	    for (var tag in newsArticle.categories) {
		    if (typeof(newsArticle.categories) == 'object') {
		      
		        if(feeds.tagTree.tagIsPublic(newsArticle.categories[tag])){
			        rss_output +="<li><a href='" + pathname + newsArticle.categories[tag] + "'>" + feeds.tagTree.getDisplayName(newsArticle.categories[tag]) + "</a></li>";
		        }
		    }
		}
	    rss_output +="<li><a href=\"/en/experience/news/archive/\">See All Stories</a></li>";
		rss_output +="</ul>";
		
		//Output data
		$('wrap_tags').setHTML(rss_output);
		
}

function buildArticleLinks(newsArticle){

        //Find Article Links
		var rss_output = "";
		
		rss_output +="<ul>";
		rss_output +="<li><h2>Also On This Site</h2></li>";
	
		for(var link in newsArticle.links) {
		    //console.log(newsArticle.links[link]);
		    if (typeof(newsArticle.links[link]) != 'function') {
		            rss_output +=" <li><a href=\""+newsArticle.links[link]['url']+"\" name=\"&amp;lpos=on_this_site\">"+newsArticle.links[link]['name']+"</a></li>";
		    }
		}
		
		rss_output +="</ul>";
		
		//Output data
		if(newsArticle.links.length > 0){
		    $('wrap_pages').setHTML(rss_output);
		}
}		

function buildRelatedLinks(newsArticle){
    
    //Set Brand path for Realter Links
    var pathname = "http://www.dodge.com/en/experience/news/articles/?guid=";
    
    var relatedArticles = new Array();
       
       //Loop Tru Category Array of article to create relatedArticles Array
       for(var tag in newsArticle.categories) {
		    if (typeof(newsArticle.categories) == 'object') {
		        if(feeds.tagTree.tagIsPublic(newsArticle.categories[tag])){
			        relatedArticles.merge(feeds.tagTree.getArticles(newsArticle.categories[tag]));
		        }
		    }
		}
	
    var articleGUIDs = new Array();
     
        //Loop Thru relatedArticles Array to find articles with Internal Category to generate a GUID array
	    for(var item in relatedArticles){
	   
           if (typeof(feeds.feedItems[relatedArticles[item]]) == 'object') {
 
              if(feeds.feedItems[relatedArticles[item]].categories.contains("internal")){
      
                 if(feeds.feedItems[relatedArticles[item]]['guid'] != guid){
                    articleGUIDs.include(feeds.feedItems[relatedArticles[item]]['guid']);
                 }
              }
              
            }
	    }
	    
	var relatedLinks = '';
	  //Loop thru GUID array to create Links for article.
	   for (i = 0; i < 5; i++){
            if (typeof(articleGUIDs[i]) == 'string') {
                var thisItem = feeds.getArticleByGUID(articleGUIDs[i]); 
                relatedLinks +='<li><a href="'+ pathname + thisItem.guid +'" name="&amp;lpos=related_stories"><p>'+ thisItem.title +'</p><br /><small>'+ thisItem.pubDate + '<br />' + thisItem.source +'</small></a></li>';
           } 
       } 
	  
	  //Output data if there is any, else kill the section
	 if(relatedLinks != ''){
	     $('related_stories_container').setHTML(relatedLinks);
	 }else{
	     $('related_stories_container').setStyle('display','none');
	 }

}


function setShareForms(){

    global.initAccordion("shareNews","div.shareNewsAccordion","a.shareNewsToggler", false, true);
	setFormValidationRequirements(document.tellafriend);
	setPermalink();
	
	$('tellafriend').addEvent('submit', function(e) {
        submitTellaFriend(document.tellafriend);
        new Event(e).stop();
    });
}


onload_register("feeds.read('/en/experience/feeds/dodge-news-internal.xml');");

onload_register('buildArticle()');