﻿/// <reference name="MicrosoftAjax.js"/>

//file per funzioni Javascript custom

//Fa partire il gioco
function play_game(width, height, limbid, gameid, idplayer, idworkphase, idwork) {
  //alert("play game\n{width:" + width + "height:" + height + "limbid:" + limbid + ", gameid:"+gameid+", idplayer:" + idplayer + ", "+
  //      "idworkphase: "+idworkphase+", idwork: "+idwork+"}");
  
        UpdateAndShowIntroGame(limbid, gameid, width, height);
  /*flashbox.show('/getflash.asp?limbid='+limbid+"&gameid="+gameid+"&idplayer="+idplayer+"&"+
                "idworkphase="+idworkphase+"&idwork="+idwork, 300, 200, 'game'); //width e height devono essere settati per i futuri game
                */
}

//Finito il gioco (concluso o interrotto)
function finish_game(limbid, idplayer, idworkphase, idwork) {
  //alert("finish_game\n{limbid:" + limbid + "idplayer:" + idplayer + ", " +
  //      "idworkphase: "+idworkphase+", idwork: "+idwork+"}");
  //if (limbid > 0) {
      SaveIntroGame();
  //}
  //else {
  //    cancel_game(limbid, idplayer, idworkphase, idwork); 
  //}
  /*$.get('/savegame.asp', {limbid:limbid, idplayer:idplayer, idworkphase:idworkphase, idwork:idwork}, function(data) {
    flashbox.hide();
    flashbox.getmovie('flashMovie').game_plaid(limbid, 0);
    alert("calling game_plaid in flash with limbid:"+limbid);
  });*/
}

function cancel_game(limbid, idplayer, idworkphase, idwork) {
  //alert("canceled game\n{limbid:" + limbid + ", idplayer:" + idplayer + ", "+
    //    "idworkphase: "+idworkphase+", idwork: "+idwork+"}");
  /*flashbox.hide();*/
  HidePopupIntroGame();
}

//chiama l'exercise di un alto player
function view_exercise(limbid, flowerid, idplayer, idworkphase, idwork, idexercise) {
  //alert("view exercise\n{limbid:" + limbid + ", flowerid:" + flowerid + ", idplayer:" + idplayer + ", "+
  //                     "idworkphase: "+idworkphase+", idwork: "+idwork+", idexercise: "+idexercise+"}");
  ShowUpdateProgressExercise();
  setExerciseProfileProperties(idplayer,idwork,idexercise, limbid, flowerid);
}

//Inizia esercizio
function play_exercise(limbid, flowerid, idplayer, idworkphase, idwork, idexercise) {
  //alert("play exercise\n{limbid:" + limbid + ", flowerid:" + flowerid + ", idplayer:" + idplayer + ", "+
  //                   "idworkphase: "+idworkphase+", idwork: "+idwork+", idexercise: "+idexercise+"}");
  ShowUpdateProgressExercise();
  setExerciseProfileProperties(idplayer,idwork,idexercise, limbid, flowerid);
}

function cancel_exercise(limbid, flowerid, idplayer, idworkphase, idwork, idexercise) {
  //in questo caso non serve fare niente
  // $("div#exercise").remove();
}

// Finito l'esercizio (concluso o interrotto)
function finish_exercise(limbid, flowerid, idplayer, idworkphase, idwork, idexercise) {
  //alert("finish exercise\n{limbid:" + limbid + ", flowerid:" + flowerid + ", idplayer:" + idplayer + ", "+
  //                     "idworkphase: "+idworkphase+", idwork: "+idwork+", idexercise: "+idexercise+"}");

}
function view_help(topic) {
  //alert('view_help: ' + topic);
  window.open("/layout/www1/custom/aspx/help.aspx?topic=" + topic, "help", "height=600, width=800, resizable=no",true);
  //flashbox.show('/help.swf', 600, 450, 'game');             
}

function close_help() {
  alert('close_help');
  //flashbox.hide();
}

function updateNavTree(limbid, flowerid)
{
    // aggiorno l'albero
    //alert( "updateNavTree: limbid:" + limbid + "; flowerid: " + flowerid); 
    $get('navTree').game_plaid(limbid, flowerid);
    //ProfileGameInfoUpdate();
}


function SaveIntroGame()
{
    //alert("SaveIntroGame " + Sys.Services.ProfileService.properties.navIntroGame);
    // salvo su db via webservice
    Xtend.HPV.WebServices.SyndromeWS.SaveIntroGame(SaveIntroGameOnSucceeded,SaveIntroGameOnFailed);

}

function SaveIntroGameOnSucceeded(result, userContext, methodName)
{
    // se tutto ok, chiudo la finestra ed aggiorno l'albero
    //alert("SaveIntroGameOnSucceeded");
    updateNavTree(Sys.Services.ProfileService.properties.navIdLimb, 0);
    HidePopupIntroGame();
}

function SaveIntroGameOnFailed(error, userContext, methodName)
{
    // oops...
    alert("Error: " + error.get_message());
    HidePopupIntroGame();
}

function ShowUpdateProgressExercise(){
        //alert("ShowUpdateProgressExercise");
        var tag = $get("UpdateProgressExercise");
        var parentTag = tag.parentNode;
        parentTag.style.display='block';
        parentTag.style.visibility='visible'; 
    }
function HideUpdateProgressExercise(){
        var tag = $get("UpdateProgressExercise");
        var parentTag = tag.parentNode;
        parentTag.style.display='none';
        parentTag.style.visibility='hidden'; 
    }


// SCRIPT PER VIRTUAL EARTH : EXERCISE MAP

//Run-Time
var map = null;

//Desing-Time
//var map = new VEMap();

var pinid = 0;
var currentItem = 0;
var IdItem1 ;
var IdItem2 ;
var IdItem3 ;
var IdItem4 ;
var IdItem5 ;


function OnLoad()
{
    //alert("OnLoad");
    // carico la mappa se esiste il div myMap
    if ($get("myMap") != null)
    {
        //alert("loadMap");
        map = new VEMap("myMap"); 
        //alert(map);
        var startPoint = new VELatLong(46.4931,11.3395);
        map.LoadMap(startPoint,12,VEMapStyle.Hybrid,false);
        map.SetMapMode(VEMapMode.Mode2D);
        map.SetScaleBarDistanceUnit(VEDistanceUnit.Kilometers);
        map.ShowMiniMap(0,250,VEMiniMapSize.Small);
        //map.onLoadMap = changeStyle;
        //map.AttachEvent("onchangeview", changeStyle);
        //ImportGeoRssFeed();
        //changeStyle();
    }
    
    
}

function changeStyle()
{
    if ($get("myMap") != null)
    {
      $get("myMap").style.zIndex = 999;
    }
    
}
//function pageLoad()
//{
//    alert("pageLoaded");
//}


function AddPushpin(latitude, longitude, title, description)
{
    //alert("addPushpin: lat=" + latitude + "; long=" + longitude +  "; title=" + title + "; descr=" + description);
    
    var point = new VELatLong(latitude, longitude, 0, VEAltitudeMode.RelativeToGround);
    
    var shape =  new VEShape(VEShapeType.Pushpin, point);
    
    // tolgo gli stile di default x stile custom
    map.ClearInfoBoxStyles();  
    
    //var icon = "<img src='/images/pin.png'/>";
    var icon = GetCustomIcon("/layout/www1/images/pin.png", title)
    //Set the icon         
    shape.SetCustomIcon(icon);
    
    if (title != ""){
        shape.SetTitle(title);
    }
    if (description != ""){
        shape.SetDescription(description);
    }
    pinid++;
    
    map.AddShape(shape);
    
    return shape.GetID();
    
}
function SetPushpin(item){
    //map.ShowMiniMap(0,0);
    //map.HideDashboard();
    //alert("SetPushpin " + item);
    DectivateOtherSetButton(item);
    currentItem = item;
    SetCursor("HPVCrosshair");
    map.AttachEvent("onmouseup",CheckMouseEvent);
    ActivateCancelButton(item);
    
}

function SetCursor(type){

    
    if (type == "default"){
        $get("myMap").childNodes[0].className = "MSVE_Map";
        //$get("myMap").childNodes[0].style.cursor = "";
    }
    else if (type == "crosshair"){
        $get("myMap").childNodes[0].style.cursor = "pointer";
    }
    else if (type == "HPVCrosshair"){
        //alert($get("myMap").childNodes[0].className);
        //$get("myMap").childNodes[0].style.cursor = "url('/layout/www1/images/SetPin2.cur')";
        $get("myMap").childNodes[0].className = "HpvCrosshair";
        //alert($get("myMap").childNodes[0].className);
        //alert($get("myMap").childNodes[0].style.cursor);
    }
    
}


function CheckMouseEvent(e){
    var x = e.mapX;
    var y = e.mapY;
    pixel = new VEPixel(x, y);
    var LL = map.PixelToLatLong(pixel);
      
    if (e.eventName == "onmouseup"){
        if (e.leftMouseButton){
            if (CheckDataPushpin(currentItem)){
                SetCursor("default");
                //assegno l'id del pushpin creato alla variabile globale di riferimento
                var s;
                s = map.GetShapeByID(AddPushpin(LL.Latitude, LL.Longitude, GetTitle(currentItem),GetCustomDescription(currentItem)));
                window['IdItem'+ currentItem.toString()] = s; 
                
                SetLatLong('txt' + currentItem + '_LatLong');
                map.DetachEvent("onmouseup",CheckMouseEvent);
                ToggleButton();
                DeactivateCancelButton(currentItem);
            }
        }
    }

}

function GetTitle(i){

    var el = "txt" + i + "_Title";
    return $get(el).value;
}

function SetLatLong(elem)
{
    var s = window['IdItem'+ currentItem.toString()];
    if (s.GetType() == VEShapeType.Pushpin){
        var p = new VELatLong();
        p = s.GetPoints()[0];
        var el = document.getElementById(elem);
        el.value = p.Latitude + "#" + p.Longitude;
    }
}

function DeleteLatLong(elem)
{
    var el = document.getElementById(elem);
    el.value = "";
}


function ToggleButton(){

    if (document.getElementById("ExerciseContainer1_ctl01_ctl19_" + "btn" + currentItem + "_Set").disabled != true){
        document.getElementById("ExerciseContainer1_ctl01_ctl19_" + "btn" + currentItem + "_Set").disabled = true;
        document.getElementById("ExerciseContainer1_ctl01_ctl19_" + "btn" + currentItem + "_Del").disabled = false;
    }
    else{
        document.getElementById("ExerciseContainer1_ctl01_ctl19_" + "btn" + currentItem + "_Set").disabled = false;
        document.getElementById("ExerciseContainer1_ctl01_ctl19_" + "btn" + currentItem + "_Del").disabled = true;
    }
    
}

function ActivateCancelButton(item){
    //alert("ActivateCancelButton");
    document.getElementById("ExerciseContainer1_ctl01_ctl19_" + "btn" + item + "_Cancel").disabled = false;
}
function DeactivateCancelButton(item){
    document.getElementById("ExerciseContainer1_ctl01_ctl19_" + "btn" + item + "_Cancel").disabled = true;
}

function DectivateOtherSetButton(item){
    //alert("DectivateOtherSetButton");
    for(i=1;i<=5;i++)
    {
        if (i != item)
        {
            CancelSetPushpin(i);
        }
    }
    
}
function CancelSetPushpin(item)
{
    if (map != null){
        map.DetachEvent("onmouseup",CheckMouseEvent);
        SetCursor("default");
        DeactivateCancelButton(item);
    }
}

function DeletePushpin(item){
    try
    {
      currentItem = item;
      var shape = window['IdItem' + item];
      
      map.DeleteShape(shape);
      ToggleButton();
      DeleteLatLong('txt' + currentItem + '_LatLong');
    } catch (err)
    {
      //take no action because pushPin does not exist
    }
    
}

function MouseHandler(e){
//    var msg;         
//    if (e.eventName == "onclick"){
//        if (e.leftMouseButton)               
//            msg = "onclick (left mouse button)  event";            
//        else if (e.rightMouseButton)               
//            msg = "onclick (right mouse button)  event";            
//        else if (e.leftMouseButton)               
//            msg = "onclick (middle mouse button)  event";        
//    }
//    else{
//        msg = e.eventName + " event.";         
//    }
//    document.getElementById("messageBox").innerHTML = msg;
    //document.getElementById("messageBox").className = "show";
}


function ImportGeoRssFeed(){
    //alert("ImportGeoRssFeed");
    if ($get("myMap") != null && map != null )
    {
        // creo un layer dedicato
        DeleteAll();
        var l = new VEShapeLayer();
        //
        var veLayerSpec = new  VEShapeSourceSpecification(VEDataType.GeoRSS, "/layout/www1/custom/WebServices/MapGeoRss.aspx?rnd="+Math.round(Math.random() * 99999), l);
        map.ImportShapeLayerData(veLayerSpec, onFeedLoad, true);
        //se non esistono item disattivo il messaggio
        map.ShowMessageBox = false;
    }
}

function onFeedLoad(feed){
    var numShapes = feed.GetShapeCount();
    // per ogni item personalizzo l'output del pushpin
    for(var i=0; i < numShapes; ++i)
    {
        var s = feed.GetShapeByIndex(i);
        s.SetCustomIcon(GetCustomIcon("/layout/www1/images/pin.png",s.GetTitle()));
        s.SetDescription(s.GetDescription());
    }
    //riattivo la messagebox
    map.ShowMessageBox = true;
    //alert("feed importato!!");
    
}

function GetCustomIcon(imgSrc, title){
    var _img = "";
    var _title = "";
    if (imgSrc != "")
    {
        _img = "<div class='pushpinIconImage'><img src='"+ imgSrc +"' /></div>";
    }
    if (title != "")
    {
        _title = "<div class='pushpinIconText'>" + title + "</div>";
    }
    
    var icon = "<div class='pushpinIcon'>"
             + _img
             + _title
             + "</div>";
             
    return icon;      

}

function GetCustomDescription(i){
    var el = "txt" + i + "_Description";
    //var descr = "<span class='title'>" + GetTitle(i) + "</span><br/>";
    var descr = "";
    descr += "<span class='description'>" + $get(el).value + "</span><br/>";
    
    // Attention!!
    var container = "ExerciseContainer1_ctl01_ctl19_";
    
    var resource = container + "txt" + i + "_Resource_hidden";
    var resourceType = container + "txt" + i + "_Resource_contentType";
    
    if ($get(resourceType).value.startsWith("image")){
        descr += "<img src='/"+$get(resource).value+".jpg?w=300&h=200&keepratio=1' alt='"+ GetTitle(i) +"' width='300' height='200'/><br/>";
    }
    else if ($get(resourceType).value.startsWith("video")){
        descr += "<embed src='/layout/www1/custom/Flash/mediaPlayer/player.swf' width='320' height='240' allowscriptaccess='always' allowfullscreen='true' wmode='Transparent' flashvars='file=/"+$get(resource).value+".flv&autostart=false' class='mapPLayer'/>";
        //descr += "<embed src='/"+$get(resource).value+".wmv' width='320' height='240' type='" + $get(resourceType).value + "' play='false' loop='true' menu='true'></embed>";
    }
    else if ($get(resourceType).value.startsWith("audio")){
        descr += "<embed src='/layout/www1/custom/Flash/mediaPlayer/player.swf' width='350' height='20' allowscriptaccess='always' allowfullscreen='false' wmode='Transparent' flashvars='file=/"+$get(resource).value+".mp3&autostart=false' class='mapPLayer'/>";
        //descr += "<embed src='/"+$get(resource).value+".mid' width='320' height='240' type='" + $get(resourceType).value + "' play='false' loop='true' menu='true'></embed>";
    }
    
    return descr;   

}
function ViewAll(){
    if (map != null){
        map.ShowAllShapeLayers();
    }
}

function DeleteAll(){
    if (map != null){
        map.DeleteAllShapeLayers();
        map.DeleteAllShapes();
    }
}

function SaveMapExercise(){
    //alert("SaveMapExercise");
    if (CheckData()){
        var points = "";
        for (i=1; i<=5;i++){
            var el = "txt"+ i + "_LatLong";
            var title = "txt"+ i + "_Title";
            var descr = "txt"+ i + "_Description";
            //alert($get(el).value);
            if ($get(el) != null && $get(el).value != ""){
                if (i>1){
                    points += "|"
                }
                points += $get(el).value + "#" + GetTitle(i)  + "#" +  GetCustomDescription(i);
            }
        }
        //alert("Chiamata WS: " + points);
        Xtend.HPV.WebServices.SyndromeWS.SaveMapExercise(points, callbackOk, callbackKo);
    }
    else
    {
        return false;
    }
}


function callbackOk(result, eventArgs){
    //alert("Dati salvati correttamente!")
    return true;
}
function callbackKo(error){
    alert(error.get_message());
    return false;
}

function CheckData(){
    var ok = true;
    var pushpin = 0;
    for(i=1;i<=5;i++){
        if (ok == true){
            var latLong = "txt"+ i + "_LatLong";
            /*
            
            if ($get(latLong).value == ""){
               ok = false;
               alert("Settare Pushpin" + i); 
               break;
            }
            */
            // considero solo i pushpin inseriti
            if ($get(latLong)){
                if ($get(latLong).value != ""){
                    pushpin ++;
                    if (ok == true){
                        ok = CheckDataPushpin(i);
                    }
                }
            }
        }
    }
    // deve essere inserito almeno un pushpin
    if (pushpin == 0){
        ok = false;
        alert($get("ExerciseContainer1_ctl01_ctl19_alertPushpin").value);
    }
    
    return ok;
}

function CheckDataPushpin(item){
    /*verifico se per i pushpin inseriti esiste un titolo e descrizione*/
    var ok = true;

    var title = "txt"+ item + "_Title";
    if ($get(title).value == ""){
       ok = false;
       alert($get("ExerciseContainer1_ctl01_ctl19_alertTitle").value + " " + item); 
    }
    if (ok == true){
        var descr = "txt"+ item + "_Description";
        if ($get(descr).value == ""){
           ok = false;
           alert($get("ExerciseContainer1_ctl01_ctl19_alertDescr").value + " " + item); 
        }
    }

    return ok;
}
function MessageBox(txt){
    alert(txt);
}
function addOnClick()
{
    //alert("addOnClick");
    for (i=0;i<document.links.length;i++){
        var hHref=document.links[i].getAttribute("href")
        document.links[i].setAttribute("href","javascript:intercept('"+hHref+"')");
    }
}
function intercept(lnk){
    //alert(lnk.indexOf("?",0));
    if (lnk.indexOf("?",0) > 0)
    {
        document.location.href= lnk + "&popup=1";
        
    }
    else
    {
        document.location.href= lnk + "?popup=1";
    }
    
}

function SaveAvatar(){
    window.opener.location.href = window.opener.location.href;
    window.close();
}

function UpdateInProgress(){

    $get("Uploading").style.display = "block";
}

function SetNavTree() {
    if ($get('navTree') != null) {
        window.navTree = $get('navTree');
    }
    else {
        setTimeout('SetNavTree();', 100);
    }
    
}
 
