/**
 * Makes the call to rate a article
 *
 * @example request_articleRatings(10,5)
 * @param interger $rating  The rating the user selected
 * @param interger $article_id The ID of the article being rated 
 */
function request_article_ratings($rating,$article_id)
{
    var params = new Array();
    params[0] = $rating;
    params[1] = $article_id;
    var json = new JSON;
    json.request('article_rating',params,callback_article_ratings,'','/libs/JSON/article_actions.php');
}

/**
 * The Callback actions for request_article_ratings
 * It displays the rating of a article   
 *  
 * @param array $data [hasRating, rid, article_id, mustread, helpful, nothelpful]
 */
function callback_article_ratings($data)
{
    var hasRating = $data.hasRating;
    var article_id = $data.articleid;
    if($data.err_code){
        error_handler_by_id($data.err_code);
    }else{
        var divmustread = $('#articlerating'+ article_id +'_0');
        divmustread.text($data.mustread);
        
        var divhelpful = $('#articlerating'+ article_id +'_1');
        divhelpful.text($data.helpful);
        
        var divnothelpful = $('#articlerating'+ article_id +'_2');
        divnothelpful.text($data.nothelpful);
    }
}

/**
 * @var array Keeps track of all article on the stage as well as the page
 */ 
var calledArticles = new Array();
var currentArticlePages = new Array();


/**
 * If the page isnt already loaded load it
 * Makes the call to get a page of articles
 *
 * @param interger $id The ID of the listing the articles belongs to
 * @param {string} $section_type Declares the type of page the user is on. This will determine the content in the element 
 * @param interger $page  The Page Number To Load
 * @param boolean $override Will call in the content no matter what (even if the element is already loaded) 
 */
function request_article_page($id,$section_type,$page,$override)
{
    if( $('#articles_wrapper') && ($override || !currentArticlePages[$id+"-"+$page]) ){
        var article_wrapper = $('$articles_wrapper');
        enterPreLoader(article_wrapper[0]);
        
        var params = new Array();
        params[0] = $id;
        params[1] = $page;
        var json = new JSON;
        json.request('article_page',params,callback_article_page,$section_type,'/libs/JSON/article_actions.php');
        currentArticlePages[$id+"-"+$page] = $id+"-"+$page;
    }
}

/**
 * The Callback actions for request_article_page
 * It displays a full page of articles
 * Resets the calledarticles array
 * It writes the HTML to a DIV with the ID articles_wrapper
 * Then loops though an array of each article and embeds the flash files 
 * If $data.full_article is set the element is set in calledarticles
 * 
 * @param array $data [html,articles[],num_articles]
 */
function callback_article_page($data)
{
    if($data.err_code) {
        error_handler_by_id($data.err_code);
    } else {
        loadScript(conf.jsurl + 'content_display/add_article.js');
        calledArticles = new Array()

        var article_wrapper = $('#articles_wrapper');
        article_wrapper.html($data.html);
        
        if($('#article_buisness_form_'+$data.id)[0]){
            inlinePopups['square_popup_add_article_'+$data.id] = true;

            var params = { wmode: "transparent", quality: "high" }
            var flashvars = {};
            flashvars.title = "ARTICLE";
            
            swfobject.embedSWF(conf.swfurl + 'popup_h1_square.swf', 'popup_h1_square_popup_add_article_'+$data.id, '500', '28', '8', '', flashvars, params);
            
            rating_stars(conf.swfurl +'rating.swf','hidden_field','rating_element',0,$data.id,140,30);
            
            // I hate this so very much.
            var rating = document.createElement("input");                        
            rating.id    = "rating";
            rating.name  = "params[4]";
            rating.type  = "hidden";
            if($data.rating){
                rating.value = $data.rating;
            }else{
                rating.value = 0;
            }
            rating.onMouseDown = function(){ clearDragObject(); }
            $('#rating_hidden_holder').append(rating);
            
        }

        for(i=0;i<$data.num_articles;i++){
            if($data.articles[i].full_article){
                calledArticles[$data.articles[i].article_id] = $data.articles[i].article_id;
            }
            var flashDivID = "article_rating_"+$data.articles[i].article_id;
            var params = { wmode: "transparent", quality: "high" }
            var flashvars = {};
            flashvars.rating = $data.articles[i].rating;
            flashvars.id = $data.articles[i].article_id;
            flashvars.rating_type = "article";

            swfobject.embedSWF(conf.swfurl + "rating.swf", flashDivID, "70", "15", "6", '', flashvars, params);
        }
    }
}

/**
 * If the article isnt on stage and the function isnt set to overide this uses open_article_element to show details
 * Otherwise it will create a new article element as the first child in 'articles_wrapper' or use the one already on stage
 * It sets the className and makes the AJAX call for the HTML needed
 *
 * @example request_article_details(5,null,true,'listing_details')
 * @param {interger} $article_id  The ID of the article being requested
 * @param {string} $display_type Declaring the type of display(article_full,article_short) of the element
 * @param {boolun} $override Tells the function to get data from the server, no matter what 
 * @param {string} $section_type Declares the type of page the user is on. This will determine the content in the element
 */
function request_article_details($article_id,$display_type,$override,$section_type, $listing_id)
{
    if($override || !calledArticles[$article_id]){
        
          var articleHolder = $("#article_element_"+$article_id)[0];
  
          // If there is no element create one  
          if(!articleHolder){
              if($('#articles_wrapper')[0]){
                 var articleHolder = document.createElement('div');
                 articleHolder.id = "article_element_"+$article_id;
                 articleHolder.className = "article_full";
                 $('#articles_wrapper')[0].insertBefore(articleHolder, $('#articles_wrapper')[0].firstChild);
                 $('#articles_wrapper')[0].className ="gen_box_content no_bottom";
              }
          }else{
              var articleHolder = $("#article_element_"+$article_id)[0];
          }
  
          var displayFlag = null;
          if($display_type){ displayFlag = $display_type; }else{ displayFlag = "article_full"; }
          articleHolder.className = displayFlag;
  
          enterPreLoader(articleHolder);
  
          var params = new Array();
          params[0] = $article_id;
          if($listing_id) {
            params[1] = $listing_id;
          }
          var json=new JSON;
          json.request('article_details',params,callback_details_ListingArticle,$section_type,'/libs/JSON/article_actions.php') ;
          calledArticles[$article_id] = $article_id;
        
    }else{
        open_article_element($article_id);
    }    
}


/**
 * The Callback actions for request_article_details
 * It adds the content to the articleHolder   
 * Embeds the rating starts
 * Adds the ID to calledarticles array
 *  
 * @param array $data [article_id, html, rating]
 */
function callback_details_ListingArticle($data)
{
    if($data.err_code) {
        error_handler_by_id($data.err_code);
    } else {
        var articleHolder = $("#article_element_"+$data.article_id);
        articleHolder.html($data.html);

        var flashDivID = "article_rating_"+$data.article_id;
        var params = { wmode: "transparent", quality: "high" }
        
        swfobject.embedSWF(conf.swfurl + "rating.swf?rating="+$data.rating+"&id="+$data.article_id+"&rating_type=article", flashDivID, "70", "15", "6", '', flashvars, params);

        calledArticles[$data.article_id] = $data.article_id;
    }
}

/**
 * Removing a article element completely from the DOM
 * Also its ID from the array of article elements on stage 
 *  
 * @param integer $elementID The ID of the DIV
 * @example remove_article_element(this.id);
 */
function remove_article_element($elementID)
{                    
    var articleHolder = $("#article_element_"+$elementID)[0];
    var articleWrapper = $("#"+articleHolder.parentNode.id)[0];
    calledArticles[$elementID] = false;
    articleWrapper.removeChild(articleHolder);
}

/**
 * Closeses a article if it is already on the stage
 *  
 * @param integer $elementID The ID of the DIV
 * @example close_article_element(this.parentNode.id);
 */
function close_article_element($elementID)
{                    
    var articleHolder = $("#article_element_"+$elementID);
    articleHolder.removeClass().addClass("article_short");
    return false;
}

/**
 * Opens a article if it is already on the stage and has all content needed
 *  
 * @param integer $elementID The ID of the DIV
 * @example open_article_element(this.parentNode.id);
 * @todo make it request content if its not already populated 
 */
function open_article_element($elementID)
{                    
    var articleHolder = $("#article_element_"+$elementID);
    articleHolder.removeClass().addClass("article_full");
    return false;
}

/**
 * Is called on submit of the add comments form 
 *  
 * @param object $element
 * @example article_comment(this);
 */
function article_comment($element){
    var params = new Array();
    params[0] = $('#title_comment').attr('value');
    params[1] = $('#comment').attr('value');
    params[2] = $('#article_id').attr('value');
    params[3] = getPopUpWrapperId($element);
    params[4] = $('#section_type').attr('value');
    if($('#listing_id')[0]) {
        params[5] = $('#listing_id').attr('value');
    }
    var json = new JSON;
    json.request('article_comment',params,callback_article_comment,'','/libs/JSON/article_actions.php');
}

/**
 * Call back for article_comment
 * Updates the current article  
 * Closes The Popup
 *  
 * @param array $data [elementID, article_id]
 */
function callback_article_comment($data) {
    if ($data.err_code) {
//        alert($data.err_str);
        error_handler_by_id($data.err_code, $data.err_str);
    }else{
        // Calling to update the article
        request_article_details($data.article_id,null,true, $data.section_type, $data.listing_id)
        popup_close_all();
    }
}

/**
 * Is called on submit of the attach_article form 
 *  
 * @param object $element
 * @example attach_article(this);
 */
function attach_article($element){
    var params = new Array();
    params[0] = new Array();
    // listings select is multiple
    if($('#lid')[0]) {
        for (var i=0; i<$('#lid').options.length; i++) {
            if ($('#lid')[0].options[i].selected) {
                params[0].push($('#lid')[0].options[i].value);
            }
        }
    }

    params[1] = $('#article_id').attr('value');
    params[2] = getPopUpWrapperId($element);
    params[3] = $('#section_type').attr('value');
    
    var json = new JSON;
    json.request('attach_article',params,callback_attach_article,'','/libs/JSON/article_actions.php');
}

/**
 * Call back for attach_article
 * Display success message
 * Closes The Popup
 *  
 * @param array $data [elementID, article_id]
 */
function callback_attach_article($data) {
   if( $data != undefined ) {
        if ($data.err_code) {
            alert($data.err_str);
            error_handler_by_id($data.err_code, $data.err_str)
        }else{
            var url_ar = getCurrentURL();
            if(url_ar['file'] != 'actions.php'){
                // Close the popup window
                $('#popup_content').html('<form onsubmit="popup_close_all(); return false;"><br>Article '+ $data.article_headline +' was attached to business sucessfully.<br><br><div style="text-align: right;"><input type="submit" value="CLOSE &gt;" class="big_button" /></div></form>');
            }else{
               var redirectLocation = '/';
               if($('#referer')[0]){ redirectLocation = $('#referer').attr('value'); }
               window.document.location = redirectLocation;
            }
        }
    }
    return false;
}


/**
 * Delete a user's article
 *  
 * @param integer article id
 * @example delete_article( article_id );
 */
function delete_article( a_id ){
    if( confirm('Do you really want to delete this article ?') ) {
        var params = new Array();
        params[0] = a_id;
        var json = new JSON;
        json.request('delete_article',params,callback_delete_article,'','/libs/JSON/article_actions.php');
    }
}

function callback_delete_article( $data ) {
    p = $('#article_element_' + $data['a_id'] )[0].parentNode;
    p.removeChild( $('#article_element_'+$data['a_id'])[0] );
}


/**
 * Unlink a user's article
 *  
 * @param integer article id
 * @param integer listing id
 * @example unlink_article( article_id );
 */
function unlink_article( a_id, l_id ) {
    if( confirm('Do you really want to unlink this article ?') ) {
        var params = new Array();
        params[0] = a_id;
        params[1] = l_id;
        var json = new JSON;
        json.request('unlink_article',params,callback_unlink_article,'','/libs/JSON/article_actions.php');
    }
}

function callback_unlink_article( $data ) {
    if ($data.err_code) {
        alert($data.err_str);
        error_handler_by_id($data.err_code, $data.err_str);
    } else {
        if($('#article_unlink_successfully')[0] && $data['listing_articles_link']) {
            document.location.href = $data['listing_link'];
        } else if($('#article_element_' + $data['a_id'])[0]) {
            p = $('#article_element_' + $data['a_id'])[0].parentNode;
            p.removeChild($('#article_element_' + $data['a_id'])[0]);
        } 
    }
}

