/*
 * Init function
 */
$(document).ready(function(){
    window.version="1.0";
    document.addEventListener("searchbutton", onSearchKeyDown, true);    
    startStyles();
    setEvents();
    window.defaultNews     = 20;
    window.currentCategory = 0;
    loadSlider();
    loadFeaturedNews();
    loadRecentNews(defaultNews); 
    //createBanners();
});
window.androidVersion = 2.4;
document.addEventListener("deviceready", yourCallbackFunction, false);
function yourCallbackFunction(){
    //alert($(window).width());
    var version = getAndroidVersion();
    if (version) {
        window.androidVersion = parseFloat(version);
    }
}
function getAndroidVersion(ua) {
    var ua = ua || navigator.userAgent; 
    var match = ua.match(/Android\s([0-9\.]*)/);
    return match ? match[1] : false;
};
function setEvents() {
    $("#back").click(back);
    $("#list").click(function (){
        navigate.addPage("recent", "list");
        showRecentNews();
    });
    $("#home").click(function (){
        navigate.addPage(0, "home");
        showHome();
    });
    $("#featured").click(function () {
        navigate.addPage("featured", "list");
        showFeaturedNews();
    });
    $("#suscribe-button").click(function (event) {
        navigate.addPage(0, "suscribe");
        showSuscribe(event);
        
    });
    $("#previous-news").click(function (){
        navigate.previousPost();
    });
    $("#next-news").click(function (){
        navigate.nextPost();
    });
    $("#facebook").click(openFacebook);
    $("#twitter").click(openTwitter);
    $("#youtube").click(openYouTube);
    $("#closeApp").click(closeApp);
    $("#update").click(refresh);
    $(".search-option").click(onSearchKeyDown);
    $("#seach-form").submit(search);
    $("#close-search").click(onSearchKeyDown);
    $("#comment-form").submit(createComment);
}
function back() {
    //backFunction();
    if (navigate.arrayPages.length === 0) {
        closeApp();
    } else {
        navigate.back();
    }
}
// define endsWith on strings
String.prototype.endsWith = function(suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
/**
 * when search is triggered
 * @returns {undefined}
 */
function onSearchKeyDown() {
    $("#search-div").toggle();
    $("#search-query").focus();
    $("#search-query").select();
}
/**
 * Search on CRhoy using Google's API
 * @param {object} event event of submit
 * @returns {Boolean} //stop submit
 */
function search(event) {
    event.preventDefault();
    var query = $("#search-query").val();
    resultDiv =  $("#search-results");
    onSearchKeyDown();
    connectGoogleSearch(query, 1, resultDiv);
    navigate.addPage(query, 'list-search');
    return false;
} 
function createComment(event) {
    event.preventDefault();
    resultDiv = $("#comment-results");
    if( $("#comment-name input").val() === "" || $("#comment-mail input").val() === "" || $("#comment-text textarea").val() === "" ) {
        resultDiv.html("Todos los campos son requeridos para comentar.");
        return ;
    }
    var parameters = $(this).serialize();
    $.ajax({
        dataType: 'jsonp',
        type    : 'GET', 
        url     : "http://crhoy.com/MobileApps/comment.php?"+parameters,
        timeout : 30000,
        success : function (data) {
            resultDiv.html(data[0]);
            $("#comment-form").find("input[type=text], textarea, input[type=email]").val("");
        },
        error: function () {
            resultDiv.html(createConnectionErrorDiv()); 
        },
        beforeSend: function() {
            resultDiv.html(createLoadingImg());
        }
    });
}
/**
 * connects wiht Google's Search
 * @param {string} query
 * @param {int} startResult
 * @param {HTML Object} resultDiv
 * @returns {undefined}
 */
function connectGoogleSearch(query,startResult, resultDiv){
    $("#search-results .view-more-div-search").remove();
    $.ajax({
        dataType: 'jsonp',
        type    : 'GET', 
        url     : "https://www.googleapis.com/customsearch/v1?key=AIzaSyCMGfdDaSfjqv5zYoS0mTJnOT3e9MURWkU&cx=000169720976608467331:gxtmdgjqyh8&q="+query+"&start="+startResult,
        timeout : 30000,
        success : function (data) {
            if( startResult === 1) {
                html= createResultsInfo(
                    query, data.searchInformation.formattedTotalResults, 
                    data.searchInformation.formattedSearchTime
                ); 
            } else {
                html="";
            }
            printResults(data.items, resultDiv, startResult, query);
        
        },
        error: function () {
            resultDiv.html(createConnectionErrorDiv()); 
        },
        beforeSend: function() {
            showSearchResults();
            resultDiv.html(createLoadingImg());
        }
    });
}
function unLink(a,num){
    a.removeAttribute('onclick');
    a.innerHTML = "<div class='view-more-div news'><br>P&aacute;gina "+(((num-1)/10)+1)+"</div>";
}
/**
 * Prints Google's results
 * @param {array}       resultItems Google's results
 * @param {int} startResult secuence of showed results
 * @param {HTML Object} resultDiv where results are printed
 * @param {string} query searched query
 * @returns {undefined}
 */
function printResults(resultItems, resultDiv, startResult, query) {
    $("#recent-loading-img").remove();
    var type = "URL";
    if( resultItems !== undefined && resultItems.length > 0 ){
        $.each(resultItems, function(i, item){
            type = "URL";
            if(
                item !== undefined && 
                item.pagemap!== undefined && 
                item.pagemap.cse_image!== undefined && 
                item.pagemap.cse_image.length>0
            ) {
                img = item.pagemap.cse_image[0].src;
            } else {
                img="/img/logo.png";
            }
            if (item.link.indexOf("/noticias-sobre/") !== -1) {
                type = "Tag";
            }
            if (item.link.indexOf("/author/") === -1 && !item.link.endsWith(".jpg")&& !item.link.endsWith(".png")) {
                html += createListDiv(item.link, img, item.htmlTitle, "", type);
            }
        });  
        html += "<a onclick=\"unLink(this, "+(startResult+10)+");connectGoogleSearch('"+query+
                "',"+(startResult+10)+", $('#search-results-"+(startResult+10)+
                "'));\" class='view-more-a recent-view-more' href='javascript:void(0)' >"+
            "<div class='view-more-div news'><br>Ver m&aacute;s resultados</div></a><div id='search-results-"+
            (startResult+10)+"'></div>";
    } else {
        //resultDiv.append('Fin de los datos');
    }
    resultDiv.append(html);
}
function loadNewsTag(slug, nav, page) {
    if(slug.indexOf("crhoy.com") !== -1) {
        slug = slug.split("-sobre/")[1];
        if (slug.endsWith("/")) {
            slug = slug.substring(0, slug.length -1);
        }
    }
    if (nav) {
        navigate.addPage(slug, 'list-tag');
    }
    if(page === undefined) {
        page = 1;
    }
    if(page === 1) {
        $("#tag-news .content").html("<div class='page1'></div>");
    } else if(page === 0) {
        $("#tag-news .content").html("<div class='page1'></div>");
        page++;
    }
    window.currentTag = slug;
    var url = "http://www.crhoy.com/MobileApps/tag.php?slug="+slug+"&page="+page;
    connectToServer(url, $("#tag-news  .content .page"+page), 'list');
    showTag();    
    
}
/**
 * loads more news from a section
 * @returns {undefined}
 */
function loadMore() {
    if ($(".active").attr("id") === "list") {
        loadRecentNews(0);
        $(".recent-view-more").css("display", "none");
    }
}
/**
 * Opens Crhoy's Facebook in System app
 * @returns {undefined}
 */
function openFacebook() {
    window.open("https://facebook.com/crhoy.comnoticias", '_system');
}
/**
 * Send call event to the OS
 * @returns {undefined}
 */
function callCRHoy() {
    window.open("tel:22108600", '_system');
}
/**
 * Seand mail event to the OS
 * @returns {undefined}
 */
function mailCRHoy() {
    window.open("mailto:info@crhoy.com", '_system');
}
/**
 * Opens Crhoy's Twitter in System app
 * @returns {undefined}
 */
function openTwitter() {
    window.open("http://twitter.com/crhoycom", '_system');
}
/**
 * Opens Crhoy's YouTube in System app
 * @returns {undefined}
 */
function openYouTube() {
    window.open("http://www.youtube.com/user/crhoycom", '_system');
}
/**
 * call the server function to load recent news 
 * @param {int} number (0 for undefined)
 * @returns {undefined}
 */
function loadRecentNews(number){
    var url="";
    if(number===defaultNews) {
        url = 'http://www.crhoy.com/MobileApps/ultimas-noticiasJSON20.php';
    } else {
        url = 'http://www.crhoy.com/MobileApps/ultimas-noticiasJSON.php';
    }    
    connectToServer(url, $("#recent-news .content"), 'list');
}
/**
 * Call the server function to load featured news
 * @returns {undefined}
 */
function loadFeaturedNews(){
    url = 'http://www.crhoy.com/MobileApps/mas-leidasJSON20.php';  
    connectToServer(url, $("#featured-news .content"), 'list');
}
/**
 * Defines the URL of the server call
 * @returns {undefined}
 */
function loadSlider() {
    url = 'http://www.crhoy.com/MobileApps/portada.php?ads=&v='+window.version; 
    connectToServer(url, $("#slider-container"), 'slider');
}
/**
 * Load post from category
 * @param {int}    catID category id
 * @param {string} page  page url
 * @returns {undefined}
 */
function loadCat(catID, page) {
    if(page === 1) {
        //toggleMenu();
        $("#category-news .content").html("<div class='page1'></div>");
    } else if(page === 0) {
        $("#category-news .content").html("<div class='page1'></div>");
        page++;
    }
    window.currentCategory = catID;
    var url = "http://www.crhoy.com/MobileApps/category.php?cat="+catID+"&page="+page;
    connectToServer(url, $("#category-news .content .page"+page), 'list');
    showCategory();    
}
/**
 * Displays a formated list from json
 * @param {array}       arrayList
 * @param {HTML Object} resultDiv
 * @returns {undefined}
 */
function createList(arrayList, resultDiv) {
    var listNews = "";
    $.each(arrayList, function(i, noticia){
        if (noticia[1]!== undefined && noticia != "terminecorrectamentemasleidas") {
            listNews += createListDiv(noticia[2], noticia[1], noticia[3], noticia[0].toString(), '');             
        }
    });
    //console.debug(resultDiv);
    //$("#recent-news .content").html(listNews);
    resultDiv.html(listNews);
}
/**
 * Create html for home from json
 * @param {array}       arrayList
 * @param {HTML Object} resultDiv
 * @returns {undefined}
 */
function createHome(arrayList, resultDiv) {
    createSlider(arrayList[0], resultDiv);
    createHomeCategory(arrayList[1], $("#minislider-national"));
    createHomeToon(arrayList[2], $("#toon"));
    createHomeCategory(arrayList[3], $("#minislider-sports"));
    createHomeDiva(arrayList[4], $("#diva"));
    createHomeOpinion(arrayList[5], $("#minislider-opinion"));
    createPhrase(arrayList[6], $("#day-phrase"));
    createHomePhoto(arrayList[7], $("#day-photo"));
    createHomeSecs(arrayList[8], $("#minislider-secs"));
    setSpecialTag(arrayList[9]);
    $("#emergency-code").html(arrayList[10]);
}
function createBanners() {
    $.ajax({
        dataType: 'jsonp',
        type    : 'GET', 
        url     : "http://www.crhoy.com/MobileApps/manualDFP.php",
        timeout : 30000,
        success : function (data) {
            $("#div-gpt-ad-1404939406920-3").html(data[0]);
            $("#div-gpt-ad-1404939406920-4").html(data[1]);
            $("#div-gpt-ad-1404939406920-5").html(data[2]);
            $("#div-gpt-ad-1404939406920-1").html(data[3]);
            $("#div-gpt-ad-1404939406920-2").html(data[4]);
            $("#div-gpt-ad-1404939406920-0").html(data[5]);
            $("#div-gpt-ad-1404939406920-7").html(data[6]);
            $("#div-gpt-ad-1404939406920-6").html(data[7]);
        },
        error: function () {
            console.debug("Could't load banners") 
        },
        beforeSend: function() {
            console.debug("Loading Banners") 
        }
    });
}
function setSpecialTag(tagInfo) {
    if(tagInfo[0] === "") {
      $(".special-tag").remove();
      return;
    }
    $(".special-tag span").html(tagInfo[0]);
    $(".special-tag").click(function (){
        loadNewsTag(tagInfo[1], true, 1); 
    });
}
/**
 * Creates the html for the toon category
 * @param {string} img URL
 * @param {HTML Object} resultDiv where results r printed
 * @returns {undefined}
 */
function createHomeToon( img, resultDiv) {
    html = "<img onclick='loadNews("+img[1]+", true)' id='toon-img' src='"+img[0]+"'/>";
    resultDiv.html(html);
}
/**
 * Creates the html for the diva category
 * @param {string} img
 * @param {HTML Objject} resultDiv where results r printed
 * @returns {undefined}
 */
function createHomeDiva( img, resultDiv) {
    html = "<a onclick='loadNews("+img[2]+", true)'><img  id='diva-img' src='"+img[0]+"'/><div id='diva-title'>"+img[1]+"</div></a>";
    resultDiv.html(html);
}
/**
 * reates the html for the Day photo category
 * @param {type} img
 * @param {type} resultDiv
 * @returns {undefined}
 */
function createHomePhoto( img, resultDiv) {
    html = "<img onclick='loadNews("+img[1]+", true)' id='photo-img' src='"+img[0]+"'/>";
    resultDiv.html(html);
}
function createPhrase(data, resultDiv) {
    html = "<table  onclick='loadNews("+data[3]+", true)'><tr><td><div class='framefotofrase'> <img id='img-phrase' src='"+data[1]+"' alt='La frase del día' class='Thumbnail thumbnail medium' ></div></td><td><div class='phraseframe'><div class='simbolofrase'></div>"+data[2]+"<div class='titulofrase'> "+data[0]+"</div> </div></td></tr></table>";
    resultDiv.html(html);
}
function createHomeCategory(arrayList, resultDiv) {
    var html = "<table id='table-category-news'><tr>";
    $.each(arrayList, function(i, noticia){
        if (noticia[1]!== undefined) {
           html+= createHomeCategoryElement(noticia[0], noticia[1], noticia[2], noticia[3]);
        }
    });
    html+= "</tr></table>";   
    resultDiv.html(html);
}
function createHomeSecs(arrayList, resultDiv) {
    var html = "<table id='table-category-news'><tr>";
    $.each(arrayList, function(i, news){
        if (news[1]!== undefined) {
           html+= createHomeSecsElement(news);
        }
    });
    html+= "</tr></table>";  
    resultDiv.html(html);
}
function createHomeOpinion(arrayList, resultDiv) {
    var html = "<table id='table-category-news'><tr>";
    $.each(arrayList, function(i, element){
        if (element[1]!== undefined) {
           html+= createOpinionElement(element);
        }
    });
    html+= "</tr></table>";  
    resultDiv.html(html);
}
function loadNewsURL(url, newNav) {
    if (newNav) {
        navigate.addPage(url, "singleURL");
        $("body,html").scrollTop('0px');
    }
    url = 'http://www.crhoy.com/MobileApps/single.php?type=url&postid='+url;  
    connectToServer(url, $("#info-single"), 'single');
}
/**
 * Creates the home slider from json
 * @param {array}       arrayList
 * @param {HTML Object} resultDiv
 * @returns {undefined}
 */
function createSlider(arrayList, resultDiv) {
    var html = "<table id='table-slider-news'><tr>";
    if($(window).width() < 800) {
        w=496;
        h=496;
    } else {
        w=600;
        h=500;
    }
    $.each(arrayList, function(i, element){
        if (element[1]!== undefined) {
           html+= createSliderElement(element);
        }
    });
    html+= "</tr></table>";  
    resultDiv.html(html);
}
/**
 * Display categories separated by '>'
 * @param {array} categories
 * @returns {html|String}
 */
function displayCategories(categories) {
    var html = "";
    $.each(categories, function(i, category){
        if( i === 0) {
            html = "<a href='#"+category[0]+"'>"+category[1]+"</a>";
        } else {
            html += " > "+"<a href='#"+category[0]+"'>"+category[1]+"</a>";
        }
    });
    return html;
}
/**
 * actios after server load info
 * @param type string tipe of recived data 
 * @returns {undefined}
 */
function afterLoadFromServer(type) {
    if (
        $(".recent-view-more").size() === 0 &&
        $("#recent-news .noticia").size() <= 20 && 
        $("#recent-news .noticia").size() > 1
    ) {
        $("#recent-news .content").html($("#recent-news .content").html()+
            "<a onclick='loadMore()' class='view-more-a recent-view-more' href='javascript:void(0)' >"+
            "<div class='view-more-div news'><br>Ver todas las noticias del d&iacute;a</div></a>"
        );
    }
    if( $("#category-news").hasClass('showing') ) {
        var catPage = ( $("#category-news .noticia").size() / 20 ) + 1;
        $("#category-news .content").html($("#category-news .content").html()+
            "<div class='top-border page"+catPage+"'></div><a onclick=\"loadCat('"+window.currentCategory+"', '"+catPage+"');$(this).remove();\" class='view-more-a recent-view-more' href='javascript:void(0)' >"+
            "<div class='view-more-div news'><br>Ver m&aacutes</div></a>"
        );
    }
    if( $("#tag-news").hasClass('showing') ) {
        var tagPage = ( $("#tag-news .noticia").size() / 20 ) + 1;
        $("#tag-news .content").html($("#tag-news .content").html()+
            "<div class='top-border page"+tagPage+"'></div><a onclick=\"loadCatloadNewsTag('"+window.currentTag+"',false, '"+tagPage+"');$(this).remove();\" class='view-more-a recent-view-more' href='javascript:void(0)' >"+
            "<div class='view-more-div news'><br>Ver m&aacutes</div></a>"
        );
    }
}
/**
 * connects to the server for load news 
 * @param {string}      url 
 * @param {html object} resultDiv
 * @param {string}      type
 * @returns {undefined}
 */
function connectToServer(url, resultDiv, type){
    $.ajax({
        dataType: 'jsonp',
        type    : 'GET',
        jsonp   : 'callback',
        url     : url,
        timeout : 30000,
        success: function (data) {
            if(data===undefined) {
                $(".hideonload").show();
                $("#post-div").hide();
                resultDiv.html(createConnectionErrorDiv()); 
                return ;
            }
            if(  data[0]==="notallowed") {
                $("body").html("<img onclick='closeApp();' class='app-update' src='img/update800x500.png' />" );
                return;
            }
            if (type === 'list') {
                createList(data, resultDiv);
            } else if (type === 'slider') {
                createHome(data, resultDiv);
                $(".section-title").show();
            } else if(type === 'single') {
                if(data[0] === "noPost") { 
                    resultDiv.html(""); 
                    $(".hideonload").show();
                } else {
                    createSingle(data, resultDiv);
                }
            }
            afterLoadFromServer(type);
        },
        error: function () {
            $(".hideonload").show();
            $("#post-div").hide();
            resultDiv.html(createConnectionErrorDiv()); 
        },
        beforeSend: function() {
            if(type === 'single') {
                $(".hideonload").hide();
                showSingle();
            }            
            resultDiv.html(createLoadingImg());
        }
    });
}
function onConfirm(buttonIndex) {
    if(buttonIndex === 1) {
        navigator.app.exitApp();
    }
}
/**
 * Closes the App
 * @returns {undefined}
 */
function closeApp() {
    
navigator.notification.confirm(
    '¿Desea salir?',  // message
    onConfirm,         // callback to invoke
    'CRHoy',        // title
    ['Salir','Seguir leyendo']     // buttonLabels
);
}
function loadNews(id, newNav) {
    if (newNav) {
        navigate.addPage(id, "single");
        $("body,html").scrollTop('0px');
    }
    url = 'http://www.crhoy.com/MobileApps/single.php?postid='+id;  
    connectToServer(url, $("#info-single"), 'single');
}
function createSingle(data, resultDiv) {
    $("#comment-box").html("");
    $("#featured-img").html("");
    $("#single-contenido").html("");
    $("#player-container").html("");
    $("#comment-results").html("");
    $("#single-subtitle").parent().css("display", "");
    $("#single-subtitle2").parent().css("display", "");
    $("#single-title").html(data[0]);
    $("#single-subtitle").html(data[6]);
    $("#single-subtitle2").html(data[7]);
    $("#single-pretitle").html(data[8]);
    /*$("#single-author-url").attr("href", data[2][1]); */$("#single-author-url").hide();
    $("#single-author").html(data[2][1] + " "+ data[2][2]);
    $("#single-author-email").html(data[9]);
    var singleContent = transformMP3(data[5]);
    singleContent = singleContent.replace(/(?:http:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?!embed)(?:watch\?v=)?(.{11})?(&amp;feature=youtu.be)?/g, '<iframe width="420" height="345" src="http://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>');
    document.getElementById("single-contenido").innerHTML = singleContent;
    $("#single-contenido img").removeAttr("width").removeAttr("height");
    $("#single-contenido").ready(openExternal);
    $("#comment-post-id").val(data[14]);
    $("#iframes-analytics").html(
        "<iframe src='http://www.crhoy.com/MobileApps/analytics.php?utm_source=App%20Firefox%20OS&utm_medium=App&utm_content="+
        data[0]+"&utm_campaign="+
        data[4][0][0]+"&url="+data[3]+"' />"
    );
    $("#share-button").removeAttr("onclick");
    $("#share-button").attr("onclick", "window.plugins.socialsharing.share('"+data[0]+"', null, null, '"+data[3]+"')");
    createHomeCategory(data[12], $("#category-recent"));
    $("#category-recent-name").html(data[4][0][0]);
    $(".fb-comments").css('margin-bottom', $("#pre-footer").height());
    var contenido = $("#single-contenido iframe");
    if($("#single-contenido iframe")[0] !== undefined && $("#single-contenido iframe").attr("src").indexOf("youtube")!==-1) {
        $("#single-contenido iframe").removeAttr("width").attr("width", "100%").attr("height", $(window).height()/3);        
    }
    if (data[10] === "single-vdestacada.php" ) {
       $("#player-container").html("<div id='player'></div>");
       createYouTubeIframeAPI(data[11]);
    }
    if (data[10] === "single-fdestacada.php" ) {
       $("#featured-img").html("<img src='"+data[11]+"' class='featured-img'/>");
    }
    if (data[10] === "single-foto.php" || data[10] === "single-humor.php" || data[10] === "single-crayer.php") {
       $("#single-contenido img").css("width", "100%");
    }
    if (data[10] === "single-frase.php" ) {
        $("#single-title").html("La Frase del d&iacute;a");
        html = "<div class='framefotofrase-single'> <img class='img-phrase-single' src='"+data[11]+"' alt='La frase del d&iacute;a' class='Thumbnail thumbnail medium' ></div><div class='phraseframe-single'><div class='simbolofrase'></div><div>"+data[5]+"</div><div class='titulofrase-single'> "+data[0]+"</div> </div>";
        $("#single-contenido").html(html);
        resultDiv.html(html);
    }
    if (data[10] === "single-columna.php" ) {
        html = "<div class='columna-author'><img class='img-opinion' src='http://www.crhoy.com/wp-content/themes/crch/Slider/timthumb.php?src="+data[11]+"'/>"+data[2][1] + " "+ data[2][2]+"</div>";
        $("#single-contenido").html(html+$("#single-contenido").html());
    }
    if (data[10] === "single-galerianew.php" ) {
        var max    = 0;
        var maxPos = 0;
        newWidth   = $("body").width()*.85;
        $.each(data[11], function(i, img){
            temp = newWidth*img[3]/img[2];
           if(temp > max) {
               max    = temp;
               maxPos = i;
           }
        });
        html="";
        $.each(data[11], function(i, img){
            if(i !== maxPos) {
                html += "<td><img width="+newWidth+" src='"+img[0]+"'/>"+img[1]+"</td>";
            } else {
                html = "<td><img width="+newWidth+"  src='"+img[0]+"'/>"+img[1]+"</td>"+ html;
            }                
        });
        html="<div id='galery'><table><tr>"+html+"</tr></table></div>";
       $("#featured-img").html(html);
       $("#scroll-bar").show();
    }
    if($("#single-subtitle").html()==="") {
        $("#single-subtitle").parent().css("display", "none");
    }
    if($("#single-subtitle2").html()==="") {
        $("#single-subtitle2").parent().css("display", "none");
    }
    $("#info-single").html("");
    $(".hideonload").show();
    loadFacebookComments(data[3], $(".comment-box") );
    loadWordpressComments(data[13], $(".comment-box2") );
}
function facebookComment() {
    var fbLoginSuccess = function (userData) {
        alert("UserInfo: " + JSON.stringify(userData));
    };
    facebookConnectPlugin.login(["basic_info"],
        fbLoginSuccess,
        function (error) { alert("" + error); }
    );
    
    var fbLoginSuccess = function (userData) {
        alert("UserInfo: " + JSON.stringify(userData));
        facebookConnectPlugin.getLoginStatus(
            function (status) {
                alert("current status: " + JSON.stringify(status));

                var options = { method:"feed" };
                facebookConnectPlugin.showDialog(options,
                    function (result) {
                        alert("Posted. " + JSON.stringify(result));             },
                function (e) {
                    alert("Failed: " + e);
                });
            }
        );
    };
    
}
function loadFacebookComments(Posturl,resultDiv ) {
    var html = "";
    $.ajax({
        dataType : 'jsonp',
        type     : 'GET', 
        url      : "https://graph.facebook.com/comments/?ids="+Posturl,
        timeout  : 30000,
        success  : function (data) {
            $.each(data, function(i, element){
                comments = element['comments']['data'];
                $.each(comments, function(i, FBcommment){
                    html+= createCommentDiv(
                        "javascript:void(0)",
                        "http://graph.facebook.com/" + FBcommment['from']['id'] + "/picture?type=square", 
                         FBcommment['from']['name'], 
                         dateFormat(
                              Date(FBcommment['created_time']), 
                              "dddd, dS  mmmm , yyyy, h:MM:ss TT"
                          ),  
                         minComment(FBcommment['message']) 
                );
            });
            });
            if (html !== "") { 
                html = "<h3 class='section-title'>Comentarios de Faceboook</h3>"+html;
            }
            resultDiv.html(html);            
        },
        error: function () {
            resultDiv.html(createConnectionErrorDiv()); 
        },
        beforeSend: function() {
            resultDiv.html(createLoadingImg());
        }
    });
}
function loadWordpressComments(comments,resultDiv ) {
    var html = "";
    $.each(comments, function(i, element){
        html+= createCommentDiv(
            "javascript:void(0)",
            "", 
             element[0], 
             dateFormat(
                  Date(element[2]), 
                  "dddd, dS  mmmm , yyyy, h:MM:ss TT"
              ),  
              minComment(element[1])
        );
    });
    if (html !== "") {
        html = "<h3 class='section-title'>Comentarios</h3>"+html;
    }
    resultDiv.html(html);           
        
}
function minComment(comment) {
    var cararNumber = 175;
    var formated1 = comment.substring(0, cararNumber);
    var formated2 = comment.substring(cararNumber, comment.length);
    if(formated2==="" ||comment.length < cararNumber*1.3)
        return comment;
    return formated1+"<a class='view-more-text' onclick='$(this).hide();$(this).next().show()'>... Ver m&aacute;s</a><span class='hidden'>"+formated2+"</span>";
}
function refresh() {
    loadSlider();
    loadFeaturedNews();
    loadRecentNews(defaultNews); 
}
function openExternal() {
    $.each($("#single-contenido a"), function(i, a)
    {
        if(true)//a.parentNode.className !== "fb-xfbml-parse-ignore") 
        {
            url = a.getAttribute("href");
            if(url.indexOf("crhoy.com")!== -1) {
                if(url.endsWith("crhoy.com")) {
                    a.setAttribute("onclick", "showHome()");
                } else {
                    if(!url.endsWith(".jpg") && !url.endsWith(".png")&& !url.endsWith(".jpeg")&& !url.endsWith(".gif")) {
                        a.setAttribute("onclick", "loadNewsURL('"+ url + "', true)");
                    }
                }
            } else {
                a.setAttribute("onclick", "window.open('"+ url + "', '_system')");
            }       
            a.setAttribute("href", "javascript:void(0)");
            a.removeAttribute("target");
        }
    });
}
function transformMP3(data) {
    var posF = data.indexOf(".mp3");
    if (posF === -1) 
        return data;
    var posI = posF;
    while (data[posI] !== ":") {
        posI--;
    }
    audio = "<audio controls><source src='http" + data.substring(posI, posF) + ".mp3'type='audio/mpeg'>Su navegador no soporta elementos de audio</audio>";
    return data.substring(0, posI-4) + audio + transformMP3(data.substring(posF+4));
}
// PLAY YOUTUBE VIDEOS API
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
window.player;
function createYouTubeIframeAPI(videoID) {
  window.player = new YT.Player('player', {
    height   : $( window ).height()*.55,
    width    : '100%',
    videoId  : videoID
  });
}
function stopVideo() {
  window.player.stopVideo();
}
// END OF YOUTUBE VIDEO PLAYER API  
function scrollPos() {
    return $("html").scrollTop() + $("body").scrollTop(); 
}
