$(function () {
	var option = XH.settings.nsu;
	var nsupack = new XH.Package(XH.settings.nsu.files, XH.settings.nsu.site);
	var div = $(XH.settings.nsu.contentTargetSelector);
	var nsucontext;
	var dummyXml;
	var currentDeviceId; // new variable
    var i; // new variable
	var langCodeExist;
	var languages = {};
	XH.nsu = {};
	var overlay = false;
	var newDiv;
	
	function calloverlay() {
	    if (overlay != true) {
	        $('body').append('<div id="fade" class="black-overlay"></div>');
	        overlay = true;
	        $('#fade').show();
	    }
	}

	function wifiopen(e) {
	    calloverlay();
	    if (!document.getElementById("wifi-new")) {
	        newDiv = document.createElement("div");
	        newDiv.id = "wifi-new";
	        newDiv.className = "video-content";
	        newDiv.innerHTML = $('#wifi').html();
	        document.body.appendChild(newDiv);
	        $('.closepopup').click(closepopup);
	        $(newDiv).show();
	        $('#fade').show();
			// hide dropdown ie6 fix
		    $('#langs-list').hide();
	    }
		e.preventDefault();
	}

	function oviopen(e) {
	    calloverlay();
	    if (!document.getElementById("ovi-new")) {
	        newDiv = document.createElement("div");
	        newDiv.id = "ovi-new";
	        newDiv.className = "video-content";
	        newDiv.innerHTML = $('#ovi-suite-vid').html();
	        document.body.appendChild(newDiv);
	        $('.closepopup').click(closepopup);
	        $(newDiv).show();
	        $('#fade').show();
			// hide dropdown ie6 fix
		    $('#langs-list').hide();
			
	    }
		e.preventDefault();
	}

	function iad2open(e) {
		calloverlay();
	    if (!document.getElementById("iad2-new")) {
	        newDiv = document.createElement("div");
	        newDiv.id = "iad2-new";
	        newDiv.className = "video-content";
	        newDiv.innerHTML = $('#iad2-vid').html();
	        document.body.appendChild(newDiv);
	        $('#iad2-new .closepopup').click(closepopup);
	        $(newDiv).show();
	        $('#fade').show();
			// hide dropdown ie6 fix
		    $('#langs-list').hide();
	    }
		e.preventDefault();
	}

	function closepopup() {
	    $('#fade').hide();
		// show dropdown ie6 fix
		$('#langs-list').show();
	    document.body.removeChild(newDiv);
	}

	function openpopups() {
	    $('#openwifi').click(wifiopen);
	    $('#openovi').click(oviopen);
	    $('#openiad2').click(iad2open);
	    $('.closepopup').click(closepopup);
	}

	function populateLanguageSelection(langs) {
		var selection = $('#langs-list');
		var opt1;
		for (var prop in langs) {
			if (langs.hasOwnProperty(prop)) {
				opt1 = document.createElement('option');
				opt1.value = prop;
				opt1.innerHTML = langs[prop];
				selection.append(opt1);
			}
		}
	}

	/* // original function 
	function createxmllink(id, countLink) {
		var device = nsupack.get('device', id);
		var devicermid = device.deviceRMid;
		var xmlfulllink = nsupack.get('setting', 'device-rm-url-prefix') + devicermid + nsupack.get('setting', 'device-rm-url-suffix');
		return xmlfulllink;
	}*/
	
	function createxmllink(id, countLink) {
        var fulllink; // new variable
        var device = nsupack.get('device', id);
        var devicermid = device.deviceRMid;
        var xmlfulllink = nsupack.get('setting', 'device-rm-url-prefix') + devicermid + nsupack.get('setting', 'device-rm-url-suffix');
        var xmlfulllinkNew = nsupack.get('setting', 'device-rm-url-prefix') + devicermid + nsupack.get('setting', 'device-rm-url-suffix-new'); // new variable			
		
        if (!countLink) {
			//console.log("langCodeExist: " + langCodeExist);
            if (!langCodeExist) {
				countLink = 1;				
                langCodeExist = "";                
            } else {
				countLink = 0;                
            }
        }
       if (countLink == 0) { // condition to determine new or old xml link
            fulllink = xmlfulllinkNew; //New
			//console.log("xmlfulllinkNew: " + fulllink);
        } else {
            fulllink = xmlfulllink;
			//console.log("xmlfulllink: " + fulllink);
        }
        return fulllink;
    }

	/*function changeFileInfo() {
		var selectionLangId = $('#langs-list').val();
		var installer = nsupack.get('nsuInstaller', selectionLangId);
		$('#downloadInfo').html('');
		if (selectionLangId != '0') {
			nsucontext.js.fileType = installer.fileInfo.split('|')[0];
			nsucontext.js.fileSize = installer.fileInfo.split('|')[1];
			nsucontext.js.fileLang = languages[selectionLangId];
			nsucontext.js.downLink = installer.url;
			$('#downloadInfo').html(XH.supplement(nsupack.get('template', 'nsu-downInfo'), nsucontext));
		}
		$('#selectorStyle').html(languages[selectionLangId]);
	}
*/
	function changeFileInfo() {
        var selectionLangId = $('#langs-list').val() || nsupack.get('setting', 'default-language');
        var installer = nsupack.get('nsuInstaller', selectionLangId);
        $('#downloadInfo').html('');
        if (selectionLangId != '0') {
            nsucontext.js.fileType = installer.fileInfo.split('|')[0];
            nsucontext.js.fileSize = installer.fileInfo.split('|')[1];
            nsucontext.js.fileLang = languages[selectionLangId];
            nsucontext.js.downLink = installer.url;
            $('#downloadInfo').html(XH.supplement(nsupack.get('template', 'nsu-downInfo'), nsucontext));
        }
        $('#selectorStyle').html(languages[selectionLangId]);
    }
	


	function writeswfobject(xmllink) {
		var flashvars = {
			// function name inside flash - use only this one
			jsfunc: "XH.nsu.sendToJS",
			xmlPath: xmllink
		};
		var params = {
			scale: "noscale",
			allowScriptAccess: "always"
		};
		swfobject.embedSWF(nsupack.get('setting', 'flash-parser'), "hiddenflash", "1", "1", "9.0.0", "expressInstall.swf", flashvars, params);
	}
	

	function writecontent(id) {
		var device = nsupack.get('device', id);
		var deviceupmet = device.upMet;
		currentDeviceId = id; //variable to store product id
		i = ''; // variable to determine wheather the old XML file was loaded
		deviceupmet = deviceupmet.split(',');
		//alert(deviceupmet);
		nsucontext.device = device;
		//var output = XH.supplement(nsupack.get('template', 'uyp'), nsucontext);
		var output = '';
		var commoncontent = nsupack.get('setting', 'common-content');
		var x, len, template;
		commoncontent = commoncontent.split(',');
		for (x = 0, len = commoncontent.length; x < len; x++) {
			template = nsupack.get('template', commoncontent[x]);
			output += XH.supplement(template, nsucontext);
		}
		for (x = 0, len = deviceupmet.length; x < len; x++) {
			template = nsupack.get('template', deviceupmet[x]);
			output += XH.supplement(template, nsucontext);
		}
		$('#uypaeb').hide();
		$('#nsu-content').remove();
		div.html(output);
		populateLanguageSelection(languages);
		$('#langs-list').change(changeFileInfo);
		$('#writeXMLoutput').addClass('updates_loading');
		if (swfobject.hasFlashPlayerVersion("9.0.18")) {
			window.setTimeout(function () {
				writeswfobject(createxmllink(id));
			}, 100);
		}
		else {
			$('#writeXMLoutput').removeClass('updates_loading');
			$('#writeXMLoutput').append(XH.supplement(nsupack.get('template', 'no-flash'), nsucontext));
		}
		$('#langs-list').val(nsupack.get('setting', 'default-language'));
		changeFileInfo();
	}
	XH.nsu.sendToJS = function (flashoutput) {
		if (flashoutput === '') {
			
			if (!i && langCodeExist != '') { // condition checks if the old XML file was loaded, if not swfobject will run again with new parameter
                var oldLink = createxmllink(currentDeviceId, 1);
                //console.log("Loading old RM file.");
                i = oldLink;
                writeswfobject(oldLink);
                return;
            } else {
                usingDummyXml = true;
			
				if (!dummyXml) {
					$.ajax({
						type: "GET",
						url: nsupack.get('setting', 'default-rm-file'),
						dataType: "text",
						success: function (text) {
							dummyXml = text;
							XH.nsu.sendToJS(dummyXml);
						}
					});
				}
				else {
					XH.nsu.sendToJS(dummyXml);
				}
			}
			return;
		}
		var dummy; // = document.createElement('div');
		var parser;
		if (window.DOMParser) {
			parser = new DOMParser();
			dummy = parser.parseFromString(flashoutput, "text/xml");
		}
		else // Internet Explorer
		{
			dummy = new ActiveXObject("Microsoft.XMLDOM");
			dummy.async = "false";
			dummy.loadXML(flashoutput);
		}
		$('#writeXMLoutput').html('');
		var zaklad = $(dummy).contents().find('newest_version').text();
		nsucontext.js.rmListLi = '';
		nsucontext.js.rmTitle = '';
		$('update target_version:contains("' + zaklad + '")', $(dummy).contents()).each(function () {
			var update = $('whatsnew', this.parentNode).get(0);
			nsucontext.js.rmTitle = $('title', update).text();
			$('bullet', update).each(function () {
				nsucontext.js.rmOneListLi = $(this).text();
				nsucontext.js.rmListLi += XH.supplement(nsupack.get('template', 'nsu-rm-single-li'), nsucontext);
			});
		});
		$('#writeXMLoutput').removeClass('updates_loading');
		$('#writeXMLoutput').append(XH.supplement(nsupack.get('template', 'nsu-rm-xml-output'), nsucontext));
	};
	
	function createselector(pack, context) {
		var selector = new XH.DeviceSelector(option.selector.id, option.selector),
			devices, deviceList, imagePre, imageSuf, prop, oviPackage = pack,
			oviContext = context;
		devices = oviPackage.get('device');
		deviceList = oviPackage.getList('device');
		imagePre = oviPackage.get('setting', 'device-image-url-prefix');
		imageSuf = oviPackage.get('setting', 'device-image-file-extension');
		for (prop in devices) {
			if (devices.hasOwnProperty(prop) && devices[prop].name && devices[prop].image && devices[prop].upMet) {
				devices[prop].name = XH.supplement(devices[prop].name || '', oviContext);
				if (devices[prop].image.indexOf('/') === -1) {
					devices[prop].image = imagePre + devices[prop].image;
				}
				if (devices[prop].image.indexOf('.', devices[prop].image.lastIndexOf('/')) === -1) {
					devices[prop].image = devices[prop].image + imageSuf;
				}
			}
			else {
				delete devices[prop];
			}
		}
		selector.addAll(deviceList, devices);
		selector.select(function (e, id) {
			writecontent(id);
			openpopups();
		});
	}

	function setLanguages(aData) {
		var items = aData.split(','),
			item, x, lex;
		for (x = 0, lex = items.length; x < lex; x++) {
			item = items[x].split(':');
			languages[item[0].trim()] = item[1].trim();
		}
	}
	nsupack.ready(function () {
		nsucontext = {
			text: nsupack.get('text'),
			setting: nsupack.get('setting'),
			template: nsupack.get('template'),
			device: nsupack.get('device'),
			installer: nsupack.get('nsuInstaller'),
			devicermid: nsupack.get('deviceRMid'),
			deviceupmet: nsupack.get('upMet'),
			js: {}
		};
		
		langCodeExist = nsupack.get('setting', 'device-rm-url-suffix-new');
		createselector(nsupack, nsucontext);
		setLanguages(nsupack.get('setting', 'selection-languages'));
		$('#nsu-show-btn').click(function (e) {
			$('#nsu-content').html(XH.supplement(nsupack.get('template', 'nsu-uyypcCombo'), nsucontext));
			e.preventDefault();
			populateLanguageSelection(languages);
			$('#langs-list').change(changeFileInfo);
			$('#langs-list').val(nsupack.get('setting', 'default-language'));
			changeFileInfo();
			
		});
	});
});
