﻿var activityRunning = false;
var missingzImages="";

$(function() {setUp();})

function setUp() {
    var qsf = $("#QuickSearch");
    if (qsf != null) {
        qsf.submit(doSearch);
    }
    setUpVoteBtns();
    setUpDeA();
    setUpProbPopup();

    var f = $("#list .introPage .imgContainer img");
    setTimeout(function () { resizePics(f, 90, 90, 10); }, 1000);
    f.each(function () { $(this).bind('error', function () { $(this).parents(".imgContainer").css("display", "none"); }); this.src = this.src; });

    var d = $("#list .item .body .imgclip img");
    setTimeout(function () { resizePicsAndContainer(d, 80, 125, 20, ".imgclip"); }, 1000);
    d.each(function () { $(this).bind('error', function () { $(this).parents(".imgclip").css("display", "none"); }); this.src = this.src; });
    d.load(function () { if ($(this).attr("src").indexOf("thegossipers.com") > -1) $(this).parents(".imgclip").css("display", "none"); });

    var a = $("#front .smallBox .smallPic");
    setTimeout(function () { resizePics(a, 90, 90, 0); }, 1000);
    a.each(function () { $(this).bind('error', function () { $(this).parents(".photoclip").css("display", "none"); }); this.src = this.src; });

    var b = $("#intropage .photoOfRel .smallPic");
    setTimeout(function () { resizePicsAndContainer(b, 75, 75, 20, ".photoOfRel"); }, 1000);
    b.each(function () { $(this).bind('error', function () { $(this).parents(".photoOfRel").css("display", "none"); }); this.src = this.src; });
    b.load(function(){if ($(this).attr("src").indexOf("thegossipers.com") > -1) $(this).parents(".photoOfRel").css("display", "none");});

    var c = $(".zmoreInfo .images img");
    setTimeout(function () { centerPics(c, 75, 75); }, 1000);
    //c.error(function () { missingzImages += $(this).attr("src") + ";"; });
    c.each(function () { $(this).bind('error', function () { missingzImages += $(this).attr("src") + ";"; }); this.src = this.src; });
    setTimeout(function () { if (missingzImages != "") fixMissingImgs(); }, 1000);

    var e = $("#artOnDetail .abstract .image img");
    setTimeout(function () { resizePicsAndContainer(e, 120, 130, 0, ".image"); }, 1000);
    e.each(function () { $(this).bind('error', function () { $(this).parents(".image").css("display", "none"); }); this.src = this.src; });
    e.load(function () { if ($(this).attr("src").indexOf("thegossipers.com") > -1) $(this).parents(".image").css("display", "none"); });

    var g = $("#blogList .entry .image img");
    setTimeout(function () { resizePics(g, 60, 60, 0); }, 1000);

    $("#front .multimedia .video img").load(function () { var a = $(this); if (a.outerHeight() == 0 && outerWidth() == 0) a.parents(".video").html(""); });
}

function test(e){
    $(this)
        //.bind('load readystatechange', function (e) { load_ready(e); })
        .bind('error', err)

   this.src = this.src;  
 }

function load_ready(e) {
  if (this.complete || (this.readyState == 'complete' && e.type =='readystatechange')) {
      var i = 0;
  }
//  else {
//      $(this).bind('load readystatechange', load_ready(e));
//  }
}

//function lload() {
//    if ($(this).attr("src").indexOf("castelvetranoselinunte.it") > -1) 
//        $(this).parents(".imgclip").css("display", "none"); 
//    }

function err() {
    $(this).parents(".imgclip").css("display", "none");
}

function resizePics(a, w, h, o) {
    for (var i = 0; i < a.length; i++) {
        var p = $(a[i]);
        var height = p.outerHeight(); // p.height();
        var width = p.outerWidth();
        if (width > (w + o)) {
            var h1 = Math.max(Math.round(height * (w + o) / width), h);
            var w1 = Math.round(width * h1 / height);
            p.width(w1);
            p.height(h1);
            height = p.height();
            width = p.width();
        }
        p.css('margin-left', -(width - w) / 2);
        p.css('margin-right', -(width - w) / 2);
        p.css('margin-top', -(height - h) / 2);
        p.css('margin-bottom', -(height - h) / 2);
    }
}

function resizePicsAndContainer(a, w, h, o, container) {
    for (var i = 0; i < a.length; i++) {
        var p = $(a[i]);
        var height = p.outerHeight();// p.height();
        var width = p.outerWidth();
        if (width > (w + o)) {
            p.height(Math.round(height * (w + o)/width));
            p.width(w + o);
            height = p.height();
            width = p.width();
        }
        p.css('margin-left', -(width - w) / 2);
        p.css('margin-right', -(width - w) / 2);
        if (height < h ) {
            p.parents(container).height(height);
        }
        else {
            p.css('margin-top', -(height - h) / 2);
            p.css('margin-bottom', -(height - h) / 2);
        }
    }
}


function fixMissingImgs() {
    $.ajax({
        url: "/imgreload",
        type: "post",
        data: "url=" + location.href,
        success: function (images) {
            if (images == null) return;
            var c = $(".zmoreInfo .images img");
            var missing = missingzImages.substring(0, missingzImages.length - 1).split(";");
            missingzImages = "";
            var index = 0;
            for (var i = 0; i < c.length; i++) {
                while (index < images.length && isMissing(images[index].SmallUrl, missing)) {
                    index++;
                }
                if (index < images.length) {
                    var p = $(c[i]);
                    var pic = images[index++];
                    p.attr("src", pic.SmallUrl);
                    p.parent().attr("href", p.SourceUrl);
                }
            }
            centerPics(c, 75,75);
        }
    }
   )
}

function isMissing(url, missings) {
    for (var i = 0; i < missings.length; i++) {
        if (url == missings[i])
            return true;
    }
    return false;
}

function centerPics(a,w,h) {  
    for (var i = 0; i < a.length; i++) {
        var p = $(a[i]);
        if (p.width() == 0)
            p.width(w);
        if (p.height() == 0)
            p.height(h);
        p.css('margin-left', -(p.width() - w) / 2);
        p.css('margin-right', -(p.width() - w) / 2);
        p.css('margin-top', -(p.height() - h) / 2);
        p.css('margin-bottom', -(p.height() - h) / 2);
        if (p.height() < h || p.width() < w)
            p.parent().parent().css("background-color", "#000");
    }
}

function centerPic(w,h) {
    var p = $(this);
    if (p.width() == 0)
        p.width(w);
    if (p.height() == 0)
        p.height(h);
    p.css('margin-left', -(p.width() - w) / 2);
    p.css('margin-right', -(p.width() - w) / 2);
    p.css('margin-top', -(p.height() - h) / 2);
    p.css('margin-bottom', -(p.height() - h) / 2);
    if (p.height() < h || p.width() < w)
        p.parent().parent().css("background-color", "#000");
}

function doSearch() {
    var t = $.trim($("#quickSearchTxt").val());
    if (t == "")
        alert("Inserire termini di ricerca.");
    else {
        location.href = "/search.aspx?qry=" + escape(t);
    }
    return false;
}

/* ------------------ meteo ---------------------------*/
$(function () {
    var el = $("#meteoCities");
    if (el.length == 0) return;
    el.change(changeMeteoLocHandler);
    setupMeteo();
});

function setupMeteo() {
    var e = $("#meteoCities");
    if (e != null) {
        if ($.cookie('meteo')) {
            e.attr("selectedIndex", $.cookie('meteo'));
        }
        changeMeteoLocHandler(); /* call in any case */
    }

}

function changeMeteoLocHandler() {
    var oldImg = $("#meteoBox .left img").attr("src");
    $.ajax({
        url: "/meteo/citymeteo",
        type: "post",
        data: "city=" + $("#meteoCities").attr("value"),
        beforeSend: function () { $("#meteoBox .left img").attr("src", "/img/meteo/clessidra.gif") },
        error: function () { $("#meteoBox .left img").attr("src", oldImg) },
        success: function (cityMeteo) {
            $("#meteoBox .left img").attr("src", "/" + cityMeteo.DisplayImage);
            $("#meteoBox .middle").html(cityMeteo.Description);
            $("#meteoBox .center span").html(cityMeteo.DisplayTemperature);
            $("#meteoBox .right span").html(cityMeteo.DisplayHumidity);
        }
    }
   )
    updateMeteoCookie();
}

function updateMeteoCookie() {
    var re = new RegExp("([^.]*\.[^.]*)$");
    var m = re.exec(document.domain);
    $.cookie('meteo', $("#meteoCities").attr("selectedIndex"), { expires: 90, path: '/', domain: m[0] });
}

/* --------------------- end meteo -----------------------*/

/* ---------------- jquery cookie plugin -------------- */
jQuery.cookie = function (name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
}

/*  ----------------------- end jquery cookie plugin --------------------*/

function setUpDeA() {
    var a = new Array(8);
    a[0] = new Array('/csm.aspx?cid=B91DAB80-FDF1-4C3D-9F09-13068909A63D&d=Cucina%20e%20Ricette', 'Cucina e Ricette');
    a[1] = new Array('/csm.aspx?cid=AAFE1DCA-530D-4F41-A183-0FA8A1E23D33&d=Salute%20e%20Benessere', 'Salute e Benessere');
    a[2] = new Array('/csm.aspx?cid=7CDEC69D-CC3E-49D6-ABD7-198DF93F1922&d=Fai%20da%20Te', 'Fai da Te');
    a[3] = new Array('/csm.aspx?cid=22B1CDEE-A3FD-4F2C-8C27-42CE66C4AA7A&d=Eventi%20e%20Luoghi', 'Eventi e Luoghi');
    a[4] = new Array('/csm.aspx?cid=0F36A64A-0449-481F-93D3-9A73F3251115&d=Stile%20e%20Bellezza', 'Stile e Bellezza');
    a[5] = new Array('/csm.aspx?cid=1A345F7B-53B2-4377-B86B-014F2DC62429&d=Bambini%20e%20Genitori', 'Bambini e Genitori');
    a[6] = new Array('/csm.aspx?cid=BB927C8D-1EFD-46CB-A155-CC0A2826EF3F&d=Vivere%20Eco', 'Vivere Eco');
    a[7] = new Array('/csm.aspx?cid=0E581BCC-E263-4346-A3B4-FFCD8FF62929&d=Occasioni%20Speciali', 'Occasioni Speciali');

    var cur = a[Math.floor(Math.random() * 8)];
    var el = $("#DeAbyDay .image, #DeAbyDay .text");
    if (el == null) return;
    el.click(function () { document.location = cur[0]; return false; });
    $("#DeAbyDay .text").html(cur[1]);
}

function dispwait(t) {
    activityRunning = true;
    var i = document.createElement("img");
    i.setAttribute("src", "/img/desmm_load_w.gif");
    i.setAttribute("width", "36px");
    i.setAttribute("height", "36px");
    i.setAttribute("id", "waitImage");
    t.append(i);
}

function hidewait() {
    $("#waitImage").remove();
    activityRunning = false;
    // d.removeChild(d.firstChild);
}

function voteBtnClickHandler() {
    if (activityRunning) {
        alert("Una richiesta è già in corso.  Attendere... ");
        return;
    }
    var voteDiv = $(this).parents(".vote");
    var artId = voteDiv.find("span").attr("id").replace("VoteTotal_", "");
    $.ajax({
        url: "/vote/cast",
        type: "post",
        data: "articleId=" + artId,
        beforeSend: function () { dispwait(voteDiv) },
        error: function () { hidewait() },
        success: function (votingInfo) {
            hidewait();
            if (votingInfo.Succeeded) {
                voteDiv.find(".VoteTotal b").html(votingInfo.Votes);
                voteDiv.find(".btn").remove();
                voteDiv.find(".top").css("background-image", "url('/img/bckg_vote_10x34.jpg')");
            }
            else {
                alert(votingInfo.ErrMessage);
            }
        }
    }
   )
}

function setUpVoteBtns() {
    var els = $(".vote .btn a");
    if (els != null)
        els.click(voteBtnClickHandler);
}

/* Propblem Popup Menu */


function showHidePop() {
    var nav = $('.probpop .entry0');
    var con = /*$('#ul' + i)*/$(this).parents(".probpop");
    if (nav.css("display") == "none") {
        nav.css("display", 'block');
        con.mouseout(function (evt) {
            if (!$.contains(this, evt.relatedTarget)) {
                nav.css("display", "none");
                $(this).unbind('mouseout');
            }
        });

    } else {
        nav.css("display", "none");
    }
}

function popProbClickHandler() {
    if (activityRunning) {
        alert("Una richiesta è già in corso.  Attendere... ");
        return;
    }
    var artContainer = $(this).closest(".artContainer");
    var artId = $(this).closest(".entry0").attr("id").replace("entry_","");
    var probType = $(this).closest("li").attr("class").replace("d-item entry", "");
    var voteDiv = $(this).closest(".artContainer").find(".vote");
    $.ajax({
        url: "/probpop/set",
        type: "post",
        data: "articleId=" +artId+"&probType=" + probType/*{ articleId: artId, probType: probType }*/,
        beforeSend: function () { dispwait(voteDiv); showHidePop(); },
        error: function () { hidewait(); }/*function (XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest + " " + textStatus + " " + errorThrown);
            }*/ ,
        success: function (probInfo) {
            hidewait();
            if (probInfo.Succeeded) {
                voteDiv.find(".VoteTotal b").html(probInfo.Votes);
                voteDiv.find(".btn").remove();
                artContainer.addClass('blur');
                artContainer.find('.probpop').css('display', 'none')
                voteDiv.find(".top").css("background-image", "url('img/bckg_blurred.jpg')");
            }
            else {
                alert(probInfo.ErrMessage);
            }
        }
    })
}



function setUpProbPopup() {
    var els = $(".probpop .d-item a");
    if (els != null)
        els.click(popProbClickHandler);
    $(".probpop .toplinep").click(showHidePop);
}
