/*
Copyright © Interactive Services 2013 - 2015 All Rights Reserved.  
No part of this code may be used, with or without modification, without prior consent from Interactive Services. 
Version 1.102, 30 June 2014
*/

//Variables used with iSort
editSeverity = new Array("","Preferential","Low","Medium","High","Critical");
editType = new Array("","Text","Graphic","Programming","ID","Video","Audio","Other");
screenEdits = new Array();
var editNum;

window.initIsort = function() {
	$("#isort").removeClass("invisible");
	minmax();
	closeBtn();
	dragItems();
	// LOGIN BUTTON FUNCTIONALITY
	$('#isortLogin').click(function(){
		//If the user does not enter a name then pop up the warning indicator.
		if($('#uname').val().length==0){
			$('#uname').css("border", "2px dotted red");
			setTimeout(function(){ $('#uname').css("border", "0px dotted red"); },2000)
		}else{
			$('#login').hide("fast");
			$('#existingEdits').show("fast", function(){
				loadexistingEdits();
			});
		}
	});
	$('#isortLogin').mouseover(function() {$(this).addClass("over")});
	$('#isortLogin').mouseout(function() {$(this).removeClass("over")});
	
	// SUBMIT EDIT BUTTON FUNCTIONALITY
	$('#is_submit').click(function(){
		$('#recordEdit').hide("fast");
		$('#savingEdit').show("fast");
		text = jQuery('#is_comment').val();
		text = text.replace(/\n\r?/g, '<br/>');
		jQuery('#is_comment').val(text);
		$('#isort_edits').submit();
		
		if(jQuery('#is_submit').html()=='Submit') {
			editNum = screenEdits.length;
			//setCookie(editNum);
		}

		populateEdits();
		islDebug("Submit Edits", "green")
  });
	getDeviceInfo();
	$('#is_submit').mouseover(function() {$(this).addClass("is_btn_over")});
	$('#is_submit').mouseout(function() {$(this).removeClass("is_btn_over")});

// KEYPRESS COMBINATION DETECTION
// Merlin 18/04/14
// Detects if certain keypress detections are pressed to show previously closed debug or isort panels
var map = {34: false, 73: false, 68: false}; /*PGDN=34, D=68, I=73*/
$(document).keydown(function(e) {
	//console.log("key="+ e.keyCode);
	  if (e.keyCode in map) {
        map[e.keyCode] = true;
        if (map[34] && map[68] ) {
            $('#debugWindow').removeClass("invisible");
        }
         if (map[34] && map[73] ) {
            $('#isort').removeClass("invisible");
        }
    }
}).keyup(function(e) {
    if (e.keyCode in map) {
        map[e.keyCode] = false;
    }
});

	
	// CANCEL NEW EDIT BUTTON FUNCTIONALITY
	$('#is_cancel').click(function(){
		$('#recordEdit').hide("fast");
		$('#existingEdits').show("fast", function(){
			loadexistingEdits();
		});
	});
	$('#is_cancel').mouseover(function() {$(this).addClass("is_btn_over")});
	$('#is_cancel').mouseout(function() {$(this).removeClass("is_btn_over")});
	
	// NEXT EDIT BUTTON FUNCTIONALITY
	$('#is_next').click(function(){
		editNum = (editNum != screenEdits.length-1)? parseInt(editNum)+1 : 0
		populateEdits();
		//setCookie(editNum);
	});
	$('#is_next').mouseover(function() {$(this).addClass("is_btn_over")});
	$('#is_next').mouseout(function() {$(this).removeClass("is_btn_over")});
	
	// PREVIOUS EDIT BUTTON FUNCTIONALITY
	$('#is_back').click(function(){
		editNum = (editNum != 0)? editNum-1 : screenEdits.length-1
		populateEdits();
		//setCookie(editNum);
	});
	$('#is_back').mouseover(function() {$(this).addClass("is_btn_over")});
	$('#is_back').mouseout(function() {$(this).removeClass("is_btn_over")});
	
	// NEW EDIT BUTTON FUNCTIONALITY
	$('#is_new').click(function(){
			$('#existingEdits').hide("fast");
			$('#recordEdit').show("fast");
			updateValues()
	});
	$('#is_new').mouseover(function() {$(this).addClass("is_btn_over")});
	$('#is_new').mouseout(function() {$(this).removeClass("is_btn_over")});
	
	// DELETE EDIT BUTTON FUNCTIONALITY
	$('#is_delete').click(function(){
		$('#existingEdits').hide("fast", function(){
			$('#savingEdit').show("fast");
		});
		$('#delete_id').val(parseInt($('#edit_id').html()));
		$('#isort_delete_edit').submit();
		setTimeout(function(){$('#savingEdit').hide("fast")},500);
		editNum = editNum - 1;
		if(editNum === -1) editNum = 0;
		//setCookie(editNum);
		populateEdits();

	});

	$('#is_delete').mouseover(function() {$(this).addClass("is_btn_over")});
	$('#is_delete').mouseout(function() {$(this).removeClass("is_btn_over")});
	

	// UPDATE EDIT BUTTON FUNCTIONALITY
	$('#is_edit').click(function(){
		$('#existingEdits').hide("fast");
		$('#recordEdit').show("fast", function(){
			updateValues(parseInt($('#edit_id').html()));
		});
	});
	$('#is_edit').mouseover(function() {$(this).addClass("is_btn_over")});
	$('#is_edit').mouseout(function() {$(this).removeClass("is_btn_over")});
	
	// RETURN TO MAIN SCREEN AFTER VIEWING ERROR MESSAGE
	$('#is_return').click(function(){
		$('#isortError').hide("fast");
		$('#existingEdits').show("fast", function(){
			loadexistingEdits();
		});
	});
	$('#is_return').mouseover(function() {$(this).addClass("is_btn_over")});
	$('#is_return').mouseout(function() {$(this).removeClass("is_btn_over")});

	// jQuery function to overide the form submit functionality when a new
	// edis is recorded to the database.
	$('#isort_edits').submit(function(){
		$.post($(this).attr('action'), $(this).serialize(), function(response){
			checkResponse(response)
			$('#savingEdit').hide("fast");
			$('#existingEdits').show("fast", function(){
				loadexistingEdits();
			});
		});
		return false;
	});

	// jQuery function to overide the form submit functionality when the 
	// databse is queried for the existing edits.
	$('#isort_get_edits').submit(function(){
		$.post($(this).attr('action'), $(this).serialize(), function(response){
		
			if(!checkResponse(response)){
				return;
			}

			editNum = 0;
			//if(getCookie('LastEdit')) editNum = getCookie('LastEdit');

			screenEdits = new Array();
			//Parse the string returned from the database by first splitting on the edit identifier
			var tmpEdits = response.split("&rsEdit");
			//Parse each individual edit into an object that can be referenced later
			for(var i=1; i<tmpEdits.length; i++){
				var editElements = tmpEdits[i].split("][")
				editObj = new Object();
				editObj.reviewer = editElements[2];
				editObj.screen = editElements[3];
				editObj.date = editElements[4];
				editObj.edit = editElements[5];
				editObj.category = editType[parseInt(editElements[6])];
				editObj.severity = editSeverity[parseInt(editElements[7])];
				editObj.edit_id = parseInt(editElements[0].split("=")[1])
				screenEdits.push(editObj)
			}

			if(editNum>screenEdits.length) editNum = 0;

			populateEdits();

		});

		return false;
	});
	
// jQuery function to overide the form submit functionality when an
	// edit is deleted from the database.
	$('#isort_delete_edit').submit(function(){
		$.post($(this).attr('action'), $(this).serialize(), function(response){
			$('#savingEdit').hide("fast");
			$('#existingEdits').show("fast");
			loadexistingEdits();
		});
		return false;
	});
};
//+++++++++++++++++++++++++++++ updateValues ++++++++++++++++++++++++++++++++++++
// This function is used to populate the new edit from with the standard data - 
// id, date, current page name.  The user can then fill in the rest of the edit
// themselves.  The function is also used to update an edit and in this case every
// field is populated with the data from the database.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function updateValues(editID){
	islDebug("currentPage.src "+currentPage.src,"green");
	
	if(currentPage.src == undefined){
		var thePage = "launchPage"
	}else{
		var thePage = currentPage.src;
	}
	
	$('#is_id').val(isortObj.id);
	$('#is_id_show').html(isortObj.id);
	
	$('#is_name').val($('#uname').val());
	$('#is_name_show').html($('#uname').val());
	
	$('#is_date').val($.datepicker.formatDate('d/M/y', new Date()));
	$('#is_date_show').html($.datepicker.formatDate('d/M/y', new Date()));
	
	$('#is_page').val(thePage);
	$('#is_page_show').html(thePage);
	
	$('#is_comment').val("");
	
	if(editID!=undefined){
		//A (U) is appended to the username to show that the edit has be updated from the original edit.
		if($('#edit_reviewer').html().indexOf("(U)")==-1){
			$('#is_name').val($('#edit_reviewer').html()+" (U)");
		}else{
			$('#is_name').val($('#edit_reviewer').html());
		}
		$('#is_comment').val($('#edit_comment').html());
		//change the text value back to a number.
		var severityNum = $.inArray($('#edit_severity').html(), editSeverity)-1;
		var categoryNum = $.inArray($('#edit_category').html(), editType)-1;
		
		$("#is_editlevel").prop("selectedIndex", severityNum);
		$("#is_editype").prop("selectedIndex", categoryNum);
		$("#is_edit_id").val(editID)
		//Update the button to the new text
		$('#is_submit').html("Update Edit")
	}else{
		$("#is_edit_id").val("");
		$('#is_submit').html("Submit")
	}
	
	isortBrowser();
}

//+++++++++++++++++++++++++++++ loadexistingEdits +++++++++++++++++++++++++++++++++++
// This function is used to update the edits on a screen by screen basis so that all
// the edits for the current screen are being displayed to the user. It also checks 
// if the user has logged into isort before retrieving the edits.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function loadexistingEdits(){
	if(!$('#login').is(":visible") && $('#recordEdit').is(":visible")){
		$('#existingEdits').show("fast");
		$('#recordEdit').hide("fast");
	}
	if(!$('#login').is(":visible")){
		$('#get_id').val(isortObj.id);
		if(currentPage.src == undefined){
			$('#get_page').val("launchPage");
		}else{
			$('#get_page').val(currentPage.src);
		}
		$('#isort_get_edits').submit();
	}
}


//+++++++++++++++++++++++++++++ populateEdits +++++++++++++++++++++++++++++++++++++++
// This function is used to show all the data for the current edit on screen so it
// can be reviewed by the user. It also checks if there are any edits and removes
// the unused buttons if there isn't an edit to update/delete etc
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function populateEdits(){
	if(screenEdits.length!=0){
		$('#edit_count').html((parseInt(editNum)+1) +" of "+ screenEdits.length);
		if (screenEdits[editNum] && screenEdits[editNum].screen) {
			$('#edit_name').html(screenEdits[editNum].screen);
			$('#edit_reviewer').html(screenEdits[editNum].reviewer);
			$('#edit_date').html(screenEdits[editNum].date);
			$('#edit_category').html(screenEdits[editNum].category);
			$('#edit_severity').html(screenEdits[editNum].severity);
			$('#edit_comment').html(screenEdits[editNum].edit);
			$('#edit_id').html(screenEdits[editNum].edit_id);
		}
		
		if(!$('#is_edit').is(":visible")){
			$('#is_next').show('fast');
			$('#is_back').show('fast');
			$('#is_edit').show('fast');
			$('#is_delete').show('fast');
		}
	}else{
		$('#edit_count').html("No Edits");
		if(currentPage.src == undefined){
			$('#edit_name').html("launchPage");
		}else{
			$('#edit_name').html(currentPage.src);
		}
		$('#edit_reviewer').html($('#uname').val());
		$('#edit_date').html($.datepicker.formatDate('d/M/y', new Date()));
		$('#edit_category').html("");
		$('#edit_severity').html("");
		$('#edit_comment').html("Press <b>New Edit</b> to record a new edit.");
		$('#edit_id').html("");
		$('#is_next').hide('fast');
		$('#is_back').hide('fast');
		$('#is_edit').hide('fast');
		$('#is_delete').hide('fast');
	}
}

function checkResponse(str){
	islDebug(str,"green")
	var errorNum = parseInt(str.split("error=")[1].charAt(0));
	if(errorNum == 0){
		return true;
	}else{
		
		$("#isortError span.description").html(str.split("&description=")[1])
		$("#isortError span.date").html($.datepicker.formatDate('d/M/y', new Date()))
		$("#isort").children().each(function(index){
			islDebug("::: "+index,"#ff00ff")
			if(index>1 && $(this).is(":visible")){
				$(this).hide('fast');
			}
		});
		$("#isortError").show('fast');
		return false;
		
	}
}


function getDeviceInfo() {

	var unknown = '-';

        // screen
        var screenSize = '';
        if (screen.width) {
            width = (screen.width) ? screen.width : '';
            height = (screen.height) ? screen.height : '';
            screenSize += '' + width + " x " + height;
        }

        //browser
        var nVer = navigator.appVersion;
        var nAgt = navigator.userAgent;
        var browser = navigator.appName;
        var version = '' + parseFloat(navigator.appVersion);
        var majorVersion = parseInt(navigator.appVersion, 10);
        var nameOffset, verOffset, ix;

        // Opera
        if ((verOffset = nAgt.indexOf('Opera')) != -1) {
            browser = 'Opera';
            version = nAgt.substring(verOffset + 6);
            if ((verOffset = nAgt.indexOf('Version')) != -1) {
                version = nAgt.substring(verOffset + 8);
            }
        }
        // MSIE
        else if ((verOffset = nAgt.indexOf('MSIE')) != -1) {
            browser = 'Microsoft Internet Explorer';
            version = nAgt.substring(verOffset + 5);
        }
        // Chrome
        else if ((verOffset = nAgt.indexOf('Chrome')) != -1) {
            browser = 'Chrome';
            version = nAgt.substring(verOffset + 7);
        }
        // Safari
        else if ((verOffset = nAgt.indexOf('Safari')) != -1) {
            browser = 'Safari';
            version = nAgt.substring(verOffset + 7);
            if ((verOffset = nAgt.indexOf('Version')) != -1) {
                version = nAgt.substring(verOffset + 8);
            }
        }
        // Firefox
        else if ((verOffset = nAgt.indexOf('Firefox')) != -1) {
            browser = 'Firefox';
            version = nAgt.substring(verOffset + 8);
        }
        // MSIE 11+
        else if (nAgt.indexOf('Trident/') != -1) {
            browser = 'Microsoft Internet Explorer';
            version = nAgt.substring(nAgt.indexOf('rv:') + 3);
        }
        // Other browsers
        else if ((nameOffset = nAgt.lastIndexOf(' ') + 1) < (verOffset = nAgt.lastIndexOf('/'))) {
            browser = nAgt.substring(nameOffset, verOffset);
            version = nAgt.substring(verOffset + 1);
            if (browser.toLowerCase() == browser.toUpperCase()) {
                browser = navigator.appName;
            }
        }
        // trim the version string
        if ((ix = version.indexOf(';')) != -1) version = version.substring(0, ix);
        if ((ix = version.indexOf(' ')) != -1) version = version.substring(0, ix);
        if ((ix = version.indexOf(')')) != -1) version = version.substring(0, ix);

        majorVersion = parseInt('' + version, 10);
        if (isNaN(majorVersion)) {
            version = '' + parseFloat(navigator.appVersion);
            majorVersion = parseInt(navigator.appVersion, 10);
        }

        // mobile version
        var mobile = /Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(nVer);

        // cookie
        var cookieEnabled = (navigator.cookieEnabled) ? true : false;

        if (typeof navigator.cookieEnabled == 'undefined' && !cookieEnabled) {
            document.cookie = 'testcookie';
            cookieEnabled = (document.cookie.indexOf('testcookie') != -1) ? true : false;
        }

        // system
        var os = unknown;
        var clientStrings = [
            {s:'Windows 3.11', r:/Win16/},
            {s:'Windows 95', r:/(Windows 95|Win95|Windows_95)/},
            {s:'Windows ME', r:/(Win 9x 4.90|Windows ME)/},
            {s:'Windows 98', r:/(Windows 98|Win98)/},
            {s:'Windows CE', r:/Windows CE/},
            {s:'Windows 2000', r:/(Windows NT 5.0|Windows 2000)/},
            {s:'Windows XP', r:/(Windows NT 5.1|Windows XP)/},
            {s:'Windows Server 2003', r:/Windows NT 5.2/},
            {s:'Windows Vista', r:/Windows NT 6.0/},
            {s:'Windows 7', r:/(Windows 7|Windows NT 6.1)/},
            {s:'Windows 8.1', r:/(Windows 8.1|Windows NT 6.3)/},
            {s:'Windows 8', r:/(Windows 8|Windows NT 6.2)/},
            {s:'Windows NT 4.0', r:/(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/},
            {s:'Windows ME', r:/Windows ME/},
            {s:'Android', r:/Android/},
            {s:'Open BSD', r:/OpenBSD/},
            {s:'Sun OS', r:/SunOS/},
            {s:'Linux', r:/(Linux|X11)/},
            {s:'iOS', r:/(iPhone|iPad|iPod)/},
            {s:'Mac OS X', r:/Mac OS X/},
            {s:'Mac OS', r:/(MacPPC|MacIntel|Mac_PowerPC|Macintosh)/},
            {s:'QNX', r:/QNX/},
            {s:'UNIX', r:/UNIX/},
            {s:'BeOS', r:/BeOS/},
            {s:'OS/2', r:/OS\/2/},
            {s:'Search Bot', r:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/}
        ];
        for (var id in clientStrings) {
            var cs = clientStrings[id];
            if (cs.r.test(nAgt)) {
                os = cs.s;
                break;
            }
        }

        var osVersion = unknown;

        if (/Windows/.test(os)) {
            osVersion = /Windows (.*)/.exec(os)[1];
            os = 'Windows';
        }

        switch (os) {
            case 'Mac OS X':
                osVersion = /Mac OS X (10[\.\_\d]+)/.exec(nAgt)[1];
                break;

            case 'Android':
                osVersion = /Android ([\.\_\d]+)/.exec(nAgt)[1];
                break;

            case 'iOS':
                osVersion = /OS (\d+)_(\d+)_?(\d+)?/.exec(nVer);
                osVersion = osVersion[1] + '.' + osVersion[2] + '.' + (osVersion[3] | 0);
                break;
        }
        
        // flash (you'll need to include swfobject)
        /* script src="//ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js" */
        var flashVersion = 'no check';
        if (typeof swfobject != 'undefined') {
            var fv = swfobject.getFlashPlayerVersion();
            if (fv.major > 0) {
                flashVersion = fv.major + '.' + fv.minor + ' r' + fv.release;
            }
            else  {
                flashVersion = unknown;
            }
        }
    

    jscd = {
        screen: screenSize,
        browser: browser,
        browserVersion: version,
        mobile: mobile,
        os: os,
        osVersion: osVersion,
        cookies: cookieEnabled,
        flashVersion: flashVersion
    };

    return jscd;
}