/***
 Javascript library for the ITS Help service request page
***/

var help_vars = {
  json_url: 'https://www.case.edu/cgi-bin/its/help/userinfo.pl',
  service_request_url: 'https://cdi-its-servicedesk.com/MRcgi/MRTicketPage.pl?USER=&PROJECTID=9&MRP=0&NEWSTATUS=_REQUEST_&MAJOR_MODE=CREATE&CUSTM=',              
  fullhoursDiv: null
};

var eventsDiv;
var calColors = [
                  {'calid': 'ITS Maintenance', 'color': '#2952A3'},
                  {'calid': 'ITS Proposed Maintenance', 'color': '#9fb9ed'},
                  {'calid': 'case.edu_0vk56c5ee4ifuqe4nqk3iccoho', 'color': '#A32929'}
                ];

/****
* ITS Help Home Funtions
*****/

function init_help_home() {
  help_vars.fullhoursDiv = document.getElementById('fullhours');
  eventsDiv = document.getElementById('its_maint_gcal');

  load_json('https://www.case.edu/cgi-bin/services/footprints_global_tickets.pl?callback=displayGlobal');
  load_json('https://www.case.edu/cgi-bin/services/footprints_change_cal.pl?status=approved&type=json&callback=insertAgenda');
  load_json('https://www.case.edu/cgi-bin/services/proxyxml2json.pl?callback=hotTopicsResponse&feed=https://sites.google.com/a/case.edu/help/hot-topics/posts.xml');

  init_fancy_box();
  init_hot_topics();
  init_catelog_page();
}

function expandGlobalTicket(i) {
  document.getElementById('ticketdiv' + i).style.display = (document.getElementById('ticketdiv' + i).style.display=='block'?'none':'block');
}

function displayGlobal(json) {
  var html = new Array();
  if (json.length == 0) {
    html[0] = "There are no Current Issues at this time.";
  } else {
    for (var cnt=0; cnt<json.length; cnt++) {
      var year = json[cnt].mrsubmitdate.substr(0, 4);
      var month = json[cnt].mrsubmitdate.substr(5, 2);
      var day = json[cnt].mrsubmitdate.substr(8, 2);
      var hours = json[cnt].mrsubmitdate.substr(11, 2);
      var minutes = json[cnt].mrsubmitdate.substr(14, 2);
      var seconds = json[cnt].mrsubmitdate.substr(17, 2);

      json[cnt].datex= new Date(year, month-1, day, hours, minutes, seconds);
    }

    json.sort(function (a,b) {
      return a[0] - b[0];
    });
    var dateString = '';

    for (var cnt=0; cnt<json.length; cnt++) {
      var tempDateString = json[cnt].datex.toLocaleDateString();

      if (tempDateString != dateString) {
        dateString = tempDateString;
        html[html.length] = '<div class="PortletText2 heading" style="font-weight: bold; background-color: #800000; color: #ffffff;">' + dateString + '</div>';
        rowcnt = 0;
      }

      var row_class = ((rowcnt==0)?"":"hr_top");
      html[html.length] = '<div id="ticket' + cnt + '" class="' + row_class + '" onclick="expandGlobalTicket(' + cnt + ');" style="cursor: pointer;">';
      html[html.length] = ((json[cnt].datex.getHours()>12)?(json[cnt].datex.getHours()-12):(json[cnt].datex.getHours()===0?12:json[cnt].datex.getHours())) + ':' + ((json[cnt].datex.getMinutes()<10)?('0' + json[cnt].datex.getMinutes()):(json[cnt].datex.getMinutes())) + ' ' + ((json[cnt].datex.getHours()>=12)?'PM':'AM') + '   ';
      html[html.length] = '<span style="color: #800000" class="heading_txt">' + json[cnt].mrtitle + '</span>';
      html[html.length] = '</div>';
      html[html.length] = '<div id="ticketdiv' + cnt + '" style="display: none">';
      html[html.length] = json[cnt].mralldescriptions.replace("<p>&nbsp;</p>","");
      html[html.length] = '</div>';
    }
  }
  document.getElementById("tickets").innerHTML = html.join("");
}

function toggle_its_maint_gcal() {
  (eventsDiv.style.display == 'block')?eventsDiv.style.display = 'none':eventsDiv.style.display = 'block';
}

function toggle_hours() {
  (help_vars.fullhoursDiv.style.display == 'block')?help_vars.fullhoursDiv.style.display = 'none':help_vars.fullhoursDiv.style.display = 'block';
}

/*****
* Service Request Page Functions
******/
function init_service_request() {
  get_data(true, "get_user_info", help_vars.json_url, "display_service_request");
}

function display_service_request(json) {  
  //$('#service_request_frame').attr('src', help_vars.service_request_url+json.id);
  window.location.href = help_vars.service_request_url+json.id;
}

/***
* Generic Help Subpage functions
****/ 
function init_help_sub() {
  help_vars.fullhoursDiv = document.getElementById('fullhours');
  init_fancy_box();
}

/****
* Fancy Box Code
****/

function init_fancy_box() {
  if ( ! DetectTierIphone() && !DetectTierTablet() ) {
    $(".mappop").fancybox({
          'width'				: '85%',
          'height'			: '85%',
          'autoScale'     	: false,
          'transitionIn'		: 'none',
          'transitionOut'		: 'none',
          'type'				: 'iframe'
      });
      
      $(".formpop").fancybox({
        'width'				: '55%',
        'height'			: '85%',
        'autoScale'     	: false,
        'transitionIn'		: 'none',
        'transitionOut'		: 'none',
        'type'				: 'iframe'
	    });
  } else {
    //alert("Mobile Device");
    // do stuff specific to mobile devices here
    ;
  }  
}


/***
* Utility/JSON functions
***/

function get_data(_secure, _mode, _url, _callback, _params) {
	var url = _url + "?mode=" + _mode + "&callback=" + _callback;
	if (_params != null) {
		url += "&" + _params;
	}
	
	var head = document.getElementsByTagName('head')[0];
  var script = document.createElement('script');
  script.type = 'text/javascript';
  if (_secure) {
	  script.src = "https://login.case.edu/cas/login?service=" + escape(url);
  } else {
  	script.src = url;
  }
  //alert(script.src);
  head.appendChild(script);
}

/***
* Hot topics RSS
***/

function load_json(url) {
  var myscript = document.createElement('script');
  myscript.setAttribute('src', url);
  myscript.setAttribute('type', 'text/javascript');
  document.body.appendChild(myscript);

}

function xmlstr2xml(xmlstr) {
  var response;
  if (window.ActiveXObject) {
    //for IE
    response=new ActiveXObject("Microsoft.XMLDOM");
    response.async="false";
    response.loadXML(xmlstr);
  } else if (document.implementation && document.implementation.createDocument) {
    //for Mozila
    parser=new DOMParser();
    response=parser.parseFromString(xmlstr,"text/xml");
  }
  return response;
}

function convertDateString(str) {
  //YYYY-MM-DDThh:mm:ss[.f*](Z|-hh:mm|+hh:mm)
  var atomFormat = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d*)?(Z|[+-]\d{2}:\d{2})$/i;
  if(!atomFormat.test(str)) return str.replace(/\+00:00/, "");	//not atom... chop off +00:00 because google adds it and it doesn't work in ie

  var months = new Array("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");

  var year, month, date, hour, minute, second, offset;
  year = str.slice(0,4);
  month = months[1*str.slice(5,7)];		//Jan-Dec
  date = str.slice(8,10);		//01-31
  hour = str.slice(11,13);	//00-23
  minute = str.slice(14,16);	//00-59
  second = str.slice(17,19);	//00-59
  offset = "GMT";
  if(str.indexOf("Z") == -1) {  //time zone offset specified
    var x = str.lastIndexOf(":");
    offset += str.slice(x-3,x) + str.slice(x+1);
  }

  //DD MMM YYYY hh:mm:ss GMT[(+|-)hhmm]
  return date+" "+month+" "+year+" "+hour+":"+minute+":"+second+" "+offset;
}

function atomDateStr2Date(str) {
  //YYYY-MM-DDThh:mm:ss[.f*](Z|-hh:mm|+hh:mm)
  var atomFormat = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d*)?(Z|[+-]\d{2}:\d{2})$/i;
  if(!atomFormat.test(str)) return str.replace(/\+00:00/, "");	//not atom... chop off +00:00 because google adds it and it doesn't work in ie

  var months = new Array("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");

  var year, month, date, hour, minute, second, offset, monthstr;
  year = str.slice(0,4);
  month = str.slice(5,7);
  monthstr = months[1*month];		//Jan-Dec
  date = str.slice(8,10);		//01-31
  hour = str.slice(11,13);	//00-23
  minute = str.slice(14,16);	//00-59
  second = str.slice(17,19);	//00-59
  offset = "GMT";
  if(str.indexOf("Z") == -1) {  //time zone offset specified
    var x = str.lastIndexOf(":");
    offset += str.slice(x-3,x) + str.slice(x+1);
  }
  //DD MM YYYY hh:mm:ss GMT[(+|-)hhmm]
  var datestr = month+" "+date+" "+year+" "+hour+":"+minute+":"+second+" "+offset;
  //var date = new Date(datestr);
  var date = new Date(parseInt(year), parseInt(month)-1, parseInt(date), parseInt(hour), parseInt(minute), parseInt(second), 0);
  //alert("x " + date.getFullYear());
  return date;
}


function hotTopicsDisplay(xml) {
  var html = new Array();
  var months = new Array("January","February","March","April","May","June","July","August","September","October","November","December");

  var entries = xml.getElementsByTagName("entry");

  html[html.length] = "<ul>\n";

  for (var i=0; i<entries.length && i<4; i++) {
    var title = "";
    var link = "";
    var date;
    var datestr = "";;
    var atomdatestr = "";;
    if ((entries[i].getElementsByTagName("title").length > 0) && (entries[i].getElementsByTagName("title")[0].firstChild)) {
      title = entries[i].getElementsByTagName("title")[0].firstChild.nodeValue;
    }
    var links = entries[i].getElementsByTagName("link");
    if (links.length > 0) {
      for (var l=0; l<links.length; l++) {
        if (links[l].getAttribute('rel')=="alternate") {
          link = links[l].getAttribute('href');
        }
      }
    }
    if ((entries[i].getElementsByTagName("published").length > 0) && (entries[i].getElementsByTagName("published")[0].firstChild)) {
      atomdatestr = entries[i].getElementsByTagName("published")[0].firstChild.nodeValue;
      //alert(atomdatestr);
      //date = new Date(Date.parse(atomdatestr));
      
      //date = atomDateStr2Date(atomdatestr);

      atomdatestr = atomdatestr.replace(/-0500/, "EST");
      date = new Date(Date.parse(convertDateString(atomdatestr)));
      //alert(date);
      datestr = months[date.getMonth()] + " " + date.getDate() + ", " + date.getFullYear();
    }

    if ((title != "") && (title.indexOf("[Closed]") != 0)) {
      html[html.length] = "<li><a href='" + link + "' target='_blank'>" + title + "</a><div class='its_news_entry_date' style='color:gray; font-size: 80%; font-style: italic; margin-top: -1em;'>" + datestr + "</div></li>";
    }
  }
  html[html.length] = "</ul>\n";
  return html.join("");
}

function hotTopicsResponse(xmlstr) {
  var xml = xmlstr2xml(xmlstr);
  if (xml == null || typeof(xml) != "object" || xml.firstChild == null) {
    //document.getElementById("content_div").innerHTML = "<span class='PortletText2'>There was an error, please reload the page.</span>";
    return;
  } else {
    var html = hotTopicsDisplay(xml);
    document.getElementById("training_documents").innerHTML = html;
  }
}


