﻿(function ($) {
	$(document).ready(function () {
		parteneri.init ();			
	});
	
	// namespace definition
	var parteneri = {
		preferences: {
			mainBox: 'parteneriContainer',
			pullDownId: 'parteneriPullDown',
			secondColumnId: 'parteneriSecondColumn',
			leadspaceURL: '/businesscenter/cpe/image0/173433.jpg',
			goButton: 'parteneriGoButton',
			path: '/businesscenter/cpe/html0/174321.xml'		
		},
		
		xml: null,
		pullDown: [],
		
		// on page load function
		init: function () {
			// wait for XML to get loaded
			this.getXML (function () {
				// now get list of all counties and create pull down with them
				
				var list = [];
				$ ('county', parteneri.xml).each(function () {
					var n = $(this).attr('name');									   
														   
					list.push ('<option value="'+ n + '">'+ n + '</option>');					
				});
				
				parteneri.pullDown = list;
				
				$ ('#' + parteneri.preferences.pullDownId + ' > option:first').after (list.join (''));
				
				// attach event listener for selecting anything in pull down.
				// when user selects something, we need to check if there is more then 1 tab
				// if so, then create another pull down, where he/she can select which specific tab to go to.
				
				$ ('#' + parteneri.preferences.pullDownId).change (function () {
					var value = $(this).attr ('value'),
						county = $ ('county[name="' + value + '"]', parteneri.xml),
						numberOfTabs = $ ('tab', county);
						
					if (numberOfTabs.length > 1) {
						// we need to generate second pull down .. :(	
						var html = '<h2>Selectaţi produsul:</h2><form action="" method="get"><p><select id="parteneriPullDown1" name="parteneriPullDown1">';
						var tabs = numberOfTabs.get ();
						for (var i = 0; i < tabs.length; i += 1) {
							html += '<option value="' + i  + '">' + tabs[i].getAttribute ('name')  + '</option>';
						}
						
						html += '<option value="">__________________________</option></select>' +
						'<input src="//www.ibm.com/i/v16/buttons/short-btn.gif" value="Go" name="ibm-go" id="parteneriGoButton1" class="ibm-btn-go" type="image" />' +
						'</p></form>';
						
						$ ('#' + parteneri.preferences.goButton ).hide ();
						$ ('#' + parteneri.preferences.secondColumnId).append (html);
						$ ('#' + parteneri.preferences.secondColumnId).removeClass ('ibm-access');
					} else {
						$ ('#' + parteneri.preferences.goButton ).show ();
						$ ('#' + parteneri.preferences.secondColumnId).html ('').addClass ('ibm-access');
					}
				});
						
				// update ver 1.1 - dynamicaly switch to region based on url
				var urlCounty = parteneri.urlPar ('county');
				if (urlCounty) {
					parteneri.renderResult (parteneri.commonAbbrev (urlCounty));	
				}	
						
						
				// attach event listener to the button
				$ ('#' + parteneri.preferences.mainBox ).click (function (e) {
					var $target = $ (e.target);
					if ($target.is ('#' + parteneri.preferences.goButton)) {
						parteneri.renderResult ();
					} else if ($target.is ('#parteneriGoButton1')) {
						parteneri.renderResult ($ ('#' + parteneri.preferences.pullDownId).val (), $ ('#parteneriPullDown1').val () );
					}
					
					return false;					
				});
			});
		},
		
		getXML: function (fn) {
			$.ajax({
				url: parteneri.preferences.path,
				cache: true,
				dataType: "xml",
				success: function (x) {
					parteneri.xml = x;
					fn ();					
				}, 
				error: function () {
					return parteneri.error ("XML file couldn't be parsed !");
				}
			});					
		},
		
		error: function (t) {
			$ ("#ibm-content-main > *:first").before ('<p class="ibm-ind-error">' + t);	
			return;
		},
		
		// when user clicks on submit button..
		// we need to delete current content of page and create new one
		// v -> county name
		// t -> which tab should we display (number)
		// o -> which offering (number)
		renderResult: function (v, t, o) {
			// v -> current value in dropdown..
			// $x -> shortcut to xml content
			// $c -> selected county
			// $t -> tabs in this county
			var v = v || $ ('#' + parteneri.preferences.pullDownId).val (),
				$x = parteneri.xml,
				$c = $ ('county[name="' + v + '"]', $x),
				$t = $ ('tab', $c),
				$selectedTab = t || 0;			
			
			// create new pull down in sidebar - at the bottom

			// if 'val' is empty, then it's probably the first or last option from pull down..
			if (v === '') {
				return false;
			}

			// !! handle sidebar
			parteneri.createSidebarPulldown (v);
			
			// !! handle head part
			
			// clear out current content
			$ ('#ibm-content-main').empty ().append ('<div id="ibm-leadspace"><img src="' + parteneri.preferences.leadspaceURL + '" alt="" /></div>');
			// add flash
			var so = new SWFObject("/businesscenter/cpe/html0/177947.swf","flash_lead","530","200","9");
			so.useExpressInstall("/software/uk/swf/expressinstall.swf"); // for older Flash versions
			so.addParam("wmode", "opaque");
			so.addVariable("urlPageName", '?county=' + parteneri.commonAbbrevReverse(v));
			// append flash
			so.write("ibm-leadspace");
			// flash should be on page now.
			
			// change title to dropdowns value
			$ ('#ibm-content-head h1').text (v);
			// if there is only one tab, then put it's name into subtitle
			if ($t.length == 1) {
				if (!$ ('#ibm-content-head').hasClass ('ibm-content-subtitle')) {
					$ ('#ibm-content-head').addClass ('ibm-content-subtitle')	
				}
				
				$ ('#ibm-content-head > p').remove ();
				$ ('#ibm-content-head').append ('<p><em>' + $t.attr ('name') + '</em></p>');				
			} else {
				$ ('#ibm-content-head').removeClass ('ibm-content-subtitle');
				$ ('#ibm-content-head > p').remove ();			
			};
			
			// !! handle content part
			var template = parteneri.tabLayout ( $t.length );
			var tabs = [];
			
			tabs.push (template.top);
			if ($t.length > 1) {
				$t.each (function (i) {
					tabs.push ('<li class="');
					
					// if this is the first tab or last one
					if (i === 0) {
						tabs.push ('ibm-first-tab');				
					} else if (i === ($t.length - 1) ) {
						tabs.push ('ibm-last-tab');
					}
					
					// is this tab highligted ?
					if (i == $selectedTab) {
						tabs.push (' ibm-highlight-tab');
					}
					
					tabs.push ('"><a href="#' + i + '">'+ $(this).attr('name') + '</a></li>');
				});
			};
			
			tabs.push (template.content);
			
			// now we need to create the anchors list ..
			// uff..
			// first lets see how offering items will be there
			var oferings = $t.eq ($selectedTab);
			var oferingsRaw = $ ('offering', oferings);
			oferings = oferingsRaw.get ();
			
			if (oferings.length > 1 || $t.length > 1) {
			
				// how many links to display in one column
				var perColumn = Math.round (oferings.length / 2);
				
				tabs.push ('<div class="ibm-column ibm-first"><ul class="ibm-bullet-list">');
				// first column loop
				for (var i = 0; i < perColumn; i += 1) {
					var selected = '';
					if ((!o && i == 0) || o == oferings[i].getAttribute ('name')) {
						selected = ' class="ibm-highlight-link"';					
					}
					
					
					tabs.push ('<li' + selected + '><a href="#' + oferings[i].getAttribute ('name') + '">' + oferings[i].getAttribute ('name') + '</a></li>');
				};
				
				tabs.push ('</ul></div><div class="ibm-column ibm-second"><ul class="ibm-bullet-list">');
				
				// second column loop
				for (var i = perColumn; i < oferings.length; i += 1) {
					var selected = '';
					if ((!o && i == 0) || o == oferings[i].getAttribute ('name')) {
						selected = ' class="ibm-highlight-link"';					
					}
					
					
					tabs.push ('<li' + selected + '><a href="#' + oferings[i].getAttribute ('name') + '">' + oferings[i].getAttribute ('name') + '</a></li>');
				};
				
				tabs.push ('</ul></div>');
				
				tabs.push (template.bottom);
				// append it to content
				$ ('#ibm-content-main').append (tabs.join (''));
				
			} else if (oferings.length == 0 || typeof(oferings) == 'undefined' ) {
				$('#ibm-content-main').append('<div class="ibm-container ibm-alternate-six"><div class="ibm-container-body"><p><b>În judeţul selectat nu sunt disponibili parteneri de afaceri ai IBM.<br />Vă rugăm căutaţi în judeţele învecinate.</b></p></div></div>');
				
				// stop script execution at this point
				return false;
				
			} else {
				var text = oferings[0].getAttribute ('name');
				$('#ibm-content-head em:first').append (' - ' + text);			
			}

			// !! tabs generated !!
			// !! attach event handlers for them 
			$ ('ul.ibm-tabs a').click (function () {
				var href = $(this).attr('href');
				parteneri.renderResult (v, parseInt(href.substr (href.indexOf ('#') + 1)) );											 
			});
			
			$ ('div.ibm-tabs a').click (function () {
				var href = $(this).attr('href');
				parteneri.renderResult (v, $selectedTab, href.substr (href.indexOf ('#') + 1) );											 
			});
			// !! event handlers are in place			
			// !! generate content beneath it !!
			
			var content = [];
			
			// get proper offerings
			// if 'o' is defined, then we know the name of the offering and get that one
			// otherwise, select the first one
			var box;
			
			if (o) {
				box = $ ('box', oferingsRaw.filter('[name="' + o + '"]') );
			} else {
				box = $ ('box', oferingsRaw.filter(':first'));
			}
			
			box.each (function () {
				content.push ('<div class="ibm-container"><h2>' + $(this).attr ('name') + '</h2>');				
				content.push ('<div class="ibm-container-body ibm-two-column">');
								
				var entries = $ ('c', this).get ();	
				// again, there will be 2 columns
				// so we need to find out how many entries will be in each of them								
				var perColumn = Math.round (entries.length / 2);
			
				// first column loop
				for (var i = 0; i < entries.length; i += 2) {
					content.push ('<div class="ibm-column ibm-first">');
					content.push (parteneri.offeringColumns (entries[i]));
					
					
					content.push ('</div><div class="ibm-column ibm-second">');		
					if (entries[i +1]) {
						content.push (parteneri.offeringColumns (entries[i + 1]));
					}
					content.push ('</div>');
			
					if (i + 2 < entries.length) {
						content.push ('<div class="ibm-rule"><hr /></div>');	
					}
				
				};
				
				content.push ('</div></div>');
			});

			
			$ ('#ibm-content-main').append (content.join (''));
			$ ('#ibm-content-main').append ('<div class="ibm-container ibm-footnote"><div class="ibm-container-body"><p>Numele, adresele şi alte informaţii de contact ale companiilor înscrise în paginile  următoare sunt actualizate şi întreţinute de IBM. Datele nu pot fi folosite  pentru a fi trimise ca mesaje de tip spam, în campanii de telemarketing sau  alte activităţi de marketing de volum.<br /><a href="/businesscenter/smb/ro/ro/partnerfinder">Nota</a>:  Optiunea de cautare rapida este activata.</p></div></div>');
			
			// handle external links
			jQuery.getScript("//www.ibm.com/common/js/leaving-ibm.js");

		},
		
		// generate pull down in rightnav 
		createSidebarPulldown: function (county) {
			var sidebar = $ ('#ibm-pullDown-parteneri-sidebar');
			if (sidebar.length == 0) {
				sidebar.remove ();
			
				var html = '<div class="ibm-container ibm-alternate-three" id="ibm-pullDown-parteneri-sidebar">' + 
						   '<div class="ibm-container-body">' +
						   '<form action="" method="get">' + 
						   '<p><label for="parteneriPullDown">Selectaţi judeţul:</label></p>' + 
						   '<p>' +
						   '<select id="parteneriPullDown" name="parteneriPullDown">' + 
						   '<option value="" selected="selected">Selectaţi ...</option>' +
						   parteneri.pullDown.join ('') + 
							'<option value="">_____________</option>' +
							'</select>' +
							'<input src="//www.ibm.com/i/v16/buttons/short-btn.gif" value="Go" name="ibm-go" id="ibm-pullDown-parteneri-go" class="ibm-btn-go" type="image" />' +
							'</p></form></div></div>';
				$ ('#ibm-content-sidebar').append (html);

				$ ('#ibm-pullDown-parteneri-go').click (function () {
					parteneri.renderResult ( $ ('#ibm-pullDown-parteneri-sidebar').attr ('value') );
					return false;
				});
			
			}
			// set current county as selected
			$ ('#ibm-pullDown-parteneri-sidebar option').each(function () {
				if (this.value == county) {
					$ (this).attr ('selected', 'selected');	
					
				}
			});
		},
		
		tabLayout: function (i) {
			return i === 1 ? {
				top: '<div class="ibm-container ibm-alternate">' +
				   '<div class="ibm-tab-section ibm-text">' +
				   '<div class="ibm-tabs ibm-two-column">',
				content: '',
				bottom: '</div></div><div class="ibm-container-body"></div></div>'
				
			} : {
				
				top: '<div class="ibm-container ibm-alternate ibm-graphic-tabs ibm-combo-tabs">' +
					'<div class="ibm-tab-section"><ul class="ibm-tabs">',
				content: '</ul></div><div class="ibm-tab-section ibm-text"><div class="ibm-tabs ibm-two-column">',					
				bottom: '</div></div><div class="ibm-container-body"></div></div>'
			}
		},
		
		offeringColumns: function (e) {
			var c = e;
			
			// if attribute 'reuseId' exists, then we need to find proper content for it
			if (c.getAttribute ('reuseId')) {
				c = $ ('c[id="' + c.getAttribute ('reuseId') + '"]', parteneri.xml).get (0);
			}
			
			var output = '<h2>' + c.getAttribute ('name') + '</h2><p>' + c.getAttribute ('address') + '</p>';
			var childs = $ (c).children ().get ();
			var length = childs.length;
			
			if (length > 0) {
				output += '<ul class="ibm-link-list">';
				for (var j = 0; j < length; j += 1) {
					var child = childs [j];
					
					// if tag name is 'ph', then it's phone number
					if (child.nodeName == 'ph') {
						output += '<li><p class="ibm-call-info">' + child.getAttribute ('number') + '</p>'	
					// if it is email address
					} else if (child.nodeName == 'email') {
						output += '<li><a class="ibm-email-link" href="mailto:' + child.getAttribute('mailto') + '">' + child.getAttribute('text') + '</a>';						
					// for link to website
					} else if (child.nodeName == 'url') {
						output += '<li><a class="ibm-external-link ibm-leaving-prompt" href="' + child.getAttribute('url') + '">' + child.getAttribute('text') + '</a>';
					} else if (child.nodeName == 'print') {
						output += '<li class="ibm-print-link"><p>' + child.getAttribute ('number') + '</p>';
					} else if (child.nodeName == 'wireless') {
						output += '<li class="ibm-wireless-link"><p>' + child.getAttribute ('number') + '</p>'
					}
					
					output += '</li>';									   
				};
				
				
				output += '</ul>';
			};					
					
			return output;
		},
		
		urlPar: function (n) {
  			n = n.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
			var regexS = "[\\?&]"+n+"=([^&#]*)";
			var regex = new RegExp( regexS );
			var results = regex.exec( window.location.href );
			if( results == null ) {
				return "";
			} else {
				return results[1];
			}
		},
		
		translationMatrix: {
			'AB': 'Alba',
			'AR': 'Arad',
			'AG': 'Argeş',
			'BC': 'Bacău',
			'BH': 'Bihor',
			'BN': 'Bistriţa-Năsăud',
			'BT': 'Botoşani',
			'BV': 'Braşov',
			'BR': 'Brăila',
			'BZ': 'Buzău',
			'CS': 'Caraş Severin',
			'CL': 'Călăraşi',
			'CJ': 'Cluj',
			'CT': 'Constanţa',
			'CV': 'Covasna',
			'DB': 'Dâmboviţa',
			'DJ': 'Dolj',
			'GL': 'Galaţi',
			'GR': 'Giurgiu',
			'GJ': 'Gorj',
			'HR': 'Harghita',
			'HD': 'Hunedoara',
			'IL': 'Ialomiţa',
			'IS': 'Iaşi',
			'IF': 'Bucureşti / Ilfov',
			'MM': 'Maramureş',
			'MH': 'Mehedinţi',
			'MS': 'Mureş',
			'NT': 'Neamţ',
			'OT': 'Olt',
			'PH': 'Prahova',
			'SM': 'Satu Mare',
			'SJ': 'Sălaj',
			'SB': 'Sibiu',
			'SV': 'Suceava',
			'TR': 'Teleorman',
			'TM': 'Timiş',
			'TL': 'Tulcea',
			'VS': 'Vaslui',
			'VL': 'Vâlcea',
			'VN': 'Vrancea'
		},
		
		commonAbbrev: function (t) {
			if (this.translationMatrix[t]) {
				return this.translationMatrix[t];
			} else {}	
		},
		
		commonAbbrevReverse: function (v) {
			var $m = this.translationMatrix;
			for (var i in $m)  {
				if ($m[i] == v) {
					return i;
				}				
			}
			
			// not found
			return '';
		}
	};
}) (jQuery);