code
stringlengths
1
2.08M
language
stringclasses
1 value
var curr_page = 1; var per_page = 16; var num_pages = Math.ceil(searchresults.length / per_page); if(num_pages == 0){ num_pages = 1; } function makePaginator(){ $("#paginator").paginate({ count: num_pages, start: curr_page, display: 5, border: true, border_color: '#CD9F33', text_color: '#6F4632', background_color: '#FAF2E1', border_hover_color: '#B18110', text_hover_color: '#6F4632', background_hover_color: '#DCC388', images: false, mouse: 'press', onChange: function(page){ DisplayPage(page); positionPaginator(); $(".resize-150").load(function(){ resize($(this), 150); }); replaceIdByName(); replaceIdByPic(); } }); } function DisplayPage(page){ var html = ''; num = 0; curr_page = page; for (var i = 0; i < per_page; i++){ var counter = ((page - 1) * per_page) + i; if (typeof(searchresults[counter]) == "undefined"){ if(html == ''){ html += '<br /><span class="medium-text">No items found. <br /><br />Try another Search!</span>'; } break; } if(num % 4 == 0){ html += '<div class="row-container">'; } html += '<div class="item-container">'; html += '<div class="img-container"><a href="'+base_url+'itemdescription/' + searchresults[counter].offer_id + '"><img class="resize-150" src="'+base_url+'resources/offer_images_thumbnail/' + searchresults[counter].item_pic + '" title="'+searchresults[counter].item_title+'"/></a></div>'; html += '<div class="cnt-container normal-text" style="font-size:11pt">'; html += searchresults[counter].item_title.substr(0, 20); if (searchresults[counter].item_title.length > 20){ html += '...'; } html += '<br />'; html += 'Price: '; if(searchresults[counter].item_price == '0.00'){ html += 'Free<br />'; } else{ html += '$' + searchresults[counter].item_price + '<br />'; } html += 'Status: ' + searchresults[counter].status + '<br />'; html += '</div></div>'; if(num % 4 == 3){ html += '<div style="clear:both"></div></div>'; } num++; } if(num % 4 != 0){ html += '<div style="clear:both"></div></div>'; } $("#items-grid").html(html); } function positionPaginator(){ var width = $('#items-grid').width(); var length = num_pages > 5 ? 5 : num_pages; var actual = 60 + 60 + 25 * num_pages; $('#paginator').css('margin-left', (width - actual) / 2); } $(function(){ makePaginator(); DisplayPage(curr_page); positionPaginator(); });
JavaScript
// areas is a variable containing all the areas available in the database //var areas_preference = new Array (); // area object function area (area_id, area_name) { this.area_id = area_id; this.area_name = area_name; } // area sorting function function sort_area(a,b) { return a.area_name > b.area_name; } // check whether an area is alr in the area preference. // return true if alr existed, and false otherwise. function exist_area(area) { var flag = false; for (var i=0; i < area_preference.length; ++i) { if (area_preference[i].area_id == area.area_id) { flag = true; break; } } return flag; } // add new area function add_area() { var chosen_area = document.getElementById("choose_area"); var new_area = new area (areas[chosen_area.value-1].area_id, areas[chosen_area.value-1].area_name); if (exist_area(new_area) == false) { area_preference.push(new_area); area_preference.sort(sort_area); display_area(); } update_area(); } // display the area container function display_area() { var area_container = document.getElementById("area_container"); while (area_container.hasChildNodes()) { area_container.removeChild(area_container.lastChild); } for (var i=0; i < area_preference.length; ++i) { var newdiv = document.createElement('div'); newdiv.setAttribute('id','area_' + area_preference[i].area_id); var cancel = document.createElement('a'); cancel.setAttribute('href','Javascript:void(0);'); cancel.setAttribute('id','cancel_'+i); cancel.setAttribute('onclick','remove_area(' + area_preference[i].area_id + ')'); cancel.innerHTML = "Remove"; newdiv.appendChild(cancel); var text = document.createElement('span'); text.setAttribute('class', 'normal-text'); text.innerHTML = "&nbsp-- " + area_preference[i].area_name; newdiv.appendChild(text); area_container.appendChild(newdiv); } } // remove the corresponding category when a cancel is click function remove_area(no) { var area_container = document.getElementById("area_container"); var area = document.getElementById('area_' + no); for (var i=0; i < area_preference.length; ++i) { if (area_preference[i].area_id == no) { area_preference.splice(i,1); break; } } area_container.removeChild(area); update_area(); } // Update the area list input form to send to the sever; function update_area(){ var area_list = document.getElementById("area_list"); area_list.value = area_array_to_string(area_preference); } // Convert an array of area to string (only keep the area_id) function area_array_to_string(a){ var str = "[" ; for (var i=0; i < a.length-1; ++i) { str += '{"area_id":"' + a[i].area_id + '"},' ; } if (a.length > 0) { str += '{"area_id":"' + a[a.length-1].area_id + '"}' ; } str += "]"; return str; } $(function() { display_area(); update_area(); });
JavaScript
function slider(){ var currentPosition = 0; var slideWidth = 800; var slides = $('.slide'); var numberOfSlides = slides.length; // Wrap all .slides with #slideInner div slides.wrapAll('<div id="slideInner"></div>') // Float left to display horizontally, readjust .slides width .css({ 'float' : 'left', 'width' : slideWidth, }); // Set #slideInner width equal to total width of all slides $('#slideInner').css('width', slideWidth * numberOfSlides); // Hide left arrow control on first load manageControls(currentPosition); // Create event listeners for .controls clicks $('.control') .bind('click', function(){ // Determine new position currentPosition = ($(this).attr('id')=='rightControl') ? currentPosition+1 : currentPosition-1; // Hide / show controls manageControls(currentPosition); // Move slideInner using margin-left $('#slideInner').animate({ 'marginLeft' : slideWidth*(-currentPosition) }); }); // manageControls: Hides and shows controls depending on currentPosition function manageControls(position){ // Hide left arrow if position is first slide if(position==0){ $('#leftControl').hide() } else{ $('#leftControl').show() } // Hide right arrow if position is last slide if(position==numberOfSlides-1){ $('#rightControl').hide() } else{ $('#rightControl').show() } } } function binding(){ $('.mouseover').bind('mouseover', function(){ var element = $(this); var height = element.height(); var width = element.width(); if(height > width){ element.css('height', '120' + 'px'); element.css('width', ''); element.css('margin-top', ((120 - element.height()) / 2)); } else{ element.css('width', '120' + 'px'); element.css('height', ''); element.css('margin-top', ((120 - element.height()) / 2)); } element.parent().css('margin', '0px 3px'); element.parent().css('height', '120px'); element.parent().css('width', '120px'); var id = $(this).attr('id'); var title = "#offer_" + id; $('#item-title').html('Item: ' + $(title).html()); $('#item-title').toggle(); }); $('.mouseover').bind('mouseout', function(){ var element = $(this); var height = element.height(); var width = element.width(); if(height > width){ element.css('height', '100' + 'px'); element.css('width', ''); element.css('margin-top', ((100 - element.height()) / 2)); } else{ element.css('width', '100' + 'px'); element.css('height', ''); element.css('margin-top', ((100 - element.height()) / 2)); } element.parent().css('margin', '10px 13px'); element.parent().css('height', '100px'); element.parent().css('width', '100px'); $('#item-title').toggle(); }); } $(function(){ slider(); resizePictures(); binding(); });
JavaScript
var offer_curr_page = 1; var offers_per_page = 5; var offers_num_pages = Math.ceil(offers.length / offers_per_page); if(offers_num_pages == 0){ offers_num_pages = 1; } var request_curr_page = 1; var requests_per_page = 5; var requests_num_pages = Math.ceil(requests.length / requests_per_page); if(requests_num_pages == 0){ requests_num_pages = 1; } function editPageHeight(){ var tmp = (requests_num > offers_num) ? requests_num : offers_num; if (tmp < 1){ tmp = 1; } $("#successful-requests").height(120 + (tmp * 170)); $("#successful-offers").height(120 + (tmp * 170)); $("#requests-container").height((tmp * 170)); $("#offers-container").height((tmp * 170)); $("#vertical-bar").height(120 + (tmp * 170)); } function makeRequestsPaginator(){ $("#requests-paginator").paginate({ count: requests_num_pages, start: request_curr_page, display: 5, border: true, border_color: '#CD9F33', text_color: '#6F4632', background_color: '#FAF2E1', border_hover_color: '#B18110', text_hover_color: '#6F4632', background_hover_color: '#DCC388', images: false, mouse: 'press', onChange: function(page){ requestsDisplayPage(page); positionRequestsPaginator(); $(".resize-100").load(function(){ resize($(this), 100); }); editPageHeight(); replaceIdByName(); replaceIdByPic(); } }); } function requestsDisplayPage(page){ var html = ''; requests_num = 0; request_curr_page = page; for (var i = 0; i < requests_per_page; i++){ var counter = ((page - 1) * requests_per_page) + i; if (typeof(requests[counter]) == "undefined"){ if(html == ''){ html += '<br /><span class="medium-text">No successful requests found. <br /><br /><a href="browse/">Browse </a> for new items now!</span>'; } break; } requests_num++; console.log(requests[counter]); html += '<div class="item-container">'; html += '<div class="img-container"><a href="itemdescription/' + requests[counter].offer_id + '"><img class="resize-100" src="resources/offer_images_thumbnail/' + requests[counter].item_pic + '" title="'+requests[counter].item_title+'"/></a></div>'; html += '<div class="cnt-container normal-text">'; html += '<a href="itemdescription/' + requests[counter].offer_id + '"><span class="medium-text">' + requests[counter].item_title + '</span></a><br />'; html += 'Previous Owner: <span class="get-fb-name">' + requests[counter].fb_id + '</span><br />'; html += 'Description: <br />' + requests[counter].item_desc.substr(0, 90); if(requests[counter].item_desc.length > 90){ html += '...'; } html += '</div>'; html += '<div style="clear: both;"></div>'; html += '</div>'; html += '</div>'; } $("#requests-container").html(html); } function positionRequestsPaginator(){ var width = $('#requests-container').width(); var length = requests_num_pages > 5 ? 5 : requests_num_pages; var actual = 60 + 60 + 25 * requests_num_pages; $('#requests-paginator').css('margin-left', (width - actual) / 2); } function makeOffersPaginator(){ $("#offers-paginator").paginate({ count: offers_num_pages, start: offer_curr_page, display: 5, border: true, border_color: '#CD9F33', text_color: '#6F4632', background_color: '#FAF2E1', border_hover_color: '#B18110', text_hover_color: '#6F4632', background_hover_color: '#DCC388', images: false, mouse: 'press', onChange: function(page){ offersDisplayPage(page); positionOffersPaginator(); $(".resize-100").load(function(){ resize($(this), 100); }); editPageHeight(); replaceIdByName(); replaceIdByPic(); } }); } function offersDisplayPage(page){ var html = ''; offer_curr_page = page; offers_num = 0; for (var i = 0; i < offers_per_page; i++){ var counter = ((page - 1) * offers_per_page) + i; if (typeof(offers[counter]) == "undefined"){ if(html == ''){ html += '<br /><span class="medium-text">Do you have stuff hidden under your bed? <br /><br /><a href="offerform/0">Create </a> a new offer now!</span>'; } break; } offers_num++; console.log(offers[counter]); html += '<div class="item-container">'; html += '<div class="img-container"><a href="itemdescription/' + offers[counter].offer_id + '"><img class="resize-100" src="resources/offer_images_thumbnail/' + offers[counter].item_pic + '" title="'+offers[counter].item_title+'"/></a></div>'; html += '<div class="cnt-container normal-text">'; html += '<a href="itemdescription/' + offers[counter].offer_id + '"><span class="medium-text">' + offers[counter].item_title + '</span></a><br />'; html += 'New Owner: <span class="get-fb-name">' + offers[counter].requester_fb_id + '</span><br />'; html += 'Description: <br />' + offers[counter].item_desc.substr(0, 90); if(offers[counter].item_desc.length > 90){ html += '...'; } html += '</div>'; html += '<div style="clear: both;"></div>'; html += '</div>'; html += '</div>'; } $("#offers-container").html(html); } function positionOffersPaginator(){ var width = $('#offers-container').width(); var length = offers_num_pages > 5 ? 5 : offers_num_pages; var actual = 60 + 60 + 25 * length; $('#offers-paginator').css('margin-left', (width - actual) / 2); } $(function(){ makeRequestsPaginator(); makeOffersPaginator(); requestsDisplayPage(request_curr_page); offersDisplayPage(offer_curr_page); positionRequestsPaginator(); positionOffersPaginator(); editPageHeight(); });
JavaScript
// onselect year function change_age_month_box() { var age_year = document.getElementById('age_year'); var age_year_label = document.getElementById('age_year_label'); var age_month = document.getElementById('age_month'); // remove the month_box when year is > 3. if (age_year.value > 3) { $('label[for="age_month"]').hide(); $('#age_month').hide(); } else { $('label[for="age_month"]').show(); $('#age_month').show(); if (age_year.value == 0) { age_month.options[0].text = "<1"; } else { age_month.options[0].text = "0"; } } // years and year if (age_year.value > 1) { age_year_label.innerHTML = "years"; } else { age_year_label.innerHTML = "year"; } } // onselect month function change_age_month_label() { var age_month = document.getElementById('age_month'); var age_month_label = document.getElementById('age_month_label'); if (age_month.value > 1) { age_month_label.innerHTML = "months"; } else { age_month_label.innerHTML = "month"; } } // onselect price choice // remove the price box if user wants to give the item free. function change_price_box() { if (document.getElementById('price_free').checked == true) { $('#item_price').hide(); document.getElementById('item_price').value = 0; } else { $('#item_price').show(); } } // onselect category function change_sub_category_box() { var category_id = document.getElementById('category_id'); var subcat = document.getElementById('sub_category_id'); // reveal the sub_category_box only when category is not miscellaneous subcat.options.length = 0; var count = 0 ; for (var i = 0; i < sub_categories.length; ++i) { if (sub_categories[i].category_id == category_id.value) { subcat.options[count] = new Option(sub_categories[i].sub_category_name, sub_categories[i].sub_category_id); ++count; } } if (count == 0) { $('label[for="sub_category"]').hide(); $('#sub_category_id').hide(); } else { $('label[for="sub_category"]').show(); $('#sub_category_id').show();; } // change the default image if no image is selected. var item_pic_name = document.getElementById('item_pic_name'); var image_preview = document.getElementById('image_preview'); var default_image_array = ["miscellaneous_default.jpg", "appliances_default.jpg", "apparel_default.jpg", "electronics_default.jpg", "equipment_and_tools_default.jpg", "furniture_default.jpg", "games_default.jpg", "handheld_devices_default.jpg", "paper_default.jpg", "stationery_default.jpg"]; if (jQuery.inArray(item_pic_name.value,default_image_array) >= 0) { while (image_preview.hasChildNodes()) { image_preview.removeChild(image_preview.lastChild); } item_pic_name.value = default_image_array[category_id.value-1]; var image = document.createElement('img'); image.setAttribute('src',base_url + 'resources/offer_images_thumbnail/' + default_image_array[category_id.value-1]); image_preview.appendChild(image); } } $(function(){ change_sub_category_box(); change_age_month_box(); change_age_month_label(); change_price_box(); var subcat = document.getElementById('sub_category_id'); // display the subcategory for (var i = 0; i < subcat.options.length; ++i) { if (subcat.options[i].value == sub_cat_id) { subcat.options[i].selected = "1"; } } });
JavaScript
/*! * jQuery Form Plugin * version: 2.84 (12-AUG-2011) * @requires jQuery v1.3.2 or later * * Examples and documentation at: http://malsup.com/jquery/form/ * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html */ ;(function($) { /* Usage Note: ----------- Do not use both ajaxSubmit and ajaxForm on the same form. These functions are intended to be exclusive. Use ajaxSubmit if you want to bind your own submit handler to the form. For example, $(document).ready(function() { $('#myForm').bind('submit', function(e) { e.preventDefault(); // <-- important $(this).ajaxSubmit({ target: '#output' }); }); }); Use ajaxForm when you want the plugin to manage all the event binding for you. For example, $(document).ready(function() { $('#myForm').ajaxForm({ target: '#output' }); }); When using ajaxForm, the ajaxSubmit function will be invoked for you at the appropriate time. */ /** * ajaxSubmit() provides a mechanism for immediately submitting * an HTML form using AJAX. */ $.fn.ajaxSubmit = function(options) { // fast fail if nothing selected (http://dev.jquery.com/ticket/2752) if (!this.length) { log('ajaxSubmit: skipping submit process - no element selected'); return this; } var method, action, url, $form = this; if (typeof options == 'function') { options = { success: options }; } method = this.attr('method'); action = this.attr('action'); url = (typeof action === 'string') ? $.trim(action) : ''; url = url || window.location.href || ''; if (url) { // clean url (don't include hash vaue) url = (url.match(/^([^#]+)/)||[])[1]; } options = $.extend(true, { url: url, success: $.ajaxSettings.success, type: method || 'GET', iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank' }, options); // hook for manipulating the form data before it is extracted; // convenient for use with rich editors like tinyMCE or FCKEditor var veto = {}; this.trigger('form-pre-serialize', [this, options, veto]); if (veto.veto) { log('ajaxSubmit: submit vetoed via form-pre-serialize trigger'); return this; } // provide opportunity to alter form data before it is serialized if (options.beforeSerialize && options.beforeSerialize(this, options) === false) { log('ajaxSubmit: submit aborted via beforeSerialize callback'); return this; } var n,v,a = this.formToArray(options.semantic); if (options.data) { options.extraData = options.data; for (n in options.data) { if( $.isArray(options.data[n]) ) { for (var k in options.data[n]) { a.push( { name: n, value: options.data[n][k] } ); } } else { v = options.data[n]; v = $.isFunction(v) ? v() : v; // if value is fn, invoke it a.push( { name: n, value: v } ); } } } // give pre-submit callback an opportunity to abort the submit if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) { log('ajaxSubmit: submit aborted via beforeSubmit callback'); return this; } // fire vetoable 'validate' event this.trigger('form-submit-validate', [a, this, options, veto]); if (veto.veto) { log('ajaxSubmit: submit vetoed via form-submit-validate trigger'); return this; } var q = $.param(a); if (options.type.toUpperCase() == 'GET') { options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q; options.data = null; // data is null for 'get' } else { options.data = q; // data is the query string for 'post' } var callbacks = []; if (options.resetForm) { callbacks.push(function() { $form.resetForm(); }); } if (options.clearForm) { callbacks.push(function() { $form.clearForm(); }); } // perform a load on the target only if dataType is not provided if (!options.dataType && options.target) { var oldSuccess = options.success || function(){}; callbacks.push(function(data) { var fn = options.replaceTarget ? 'replaceWith' : 'html'; $(options.target)[fn](data).each(oldSuccess, arguments); }); } else if (options.success) { callbacks.push(options.success); } options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg var context = options.context || options; // jQuery 1.4+ supports scope context for (var i=0, max=callbacks.length; i < max; i++) { callbacks[i].apply(context, [data, status, xhr || $form, $form]); } }; // are there files to upload? var fileInputs = $('input:file', this).length > 0; var mp = 'multipart/form-data'; var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp); // options.iframe allows user to force iframe mode // 06-NOV-09: now defaulting to iframe mode if file input is detected if (options.iframe !== false && (fileInputs || options.iframe || multipart)) { // hack to fix Safari hang (thanks to Tim Molendijk for this) // see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d if (options.closeKeepAlive) { $.get(options.closeKeepAlive, function() { fileUpload(a); }); } else { fileUpload(a); } } else { // IE7 massage (see issue 57) if ($.browser.msie && method == 'get') { var ieMeth = $form[0].getAttribute('method'); if (typeof ieMeth === 'string') options.type = ieMeth; } $.ajax(options); } // fire 'notify' event this.trigger('form-submit-notify', [this, options]); return this; // private function for handling file uploads (hat tip to YAHOO!) function fileUpload(a) { var form = $form[0], el, i, s, g, id, $io, io, xhr, sub, n, timedOut, timeoutHandle; var useProp = !!$.fn.prop; if (a) { // ensure that every serialized input is still enabled for (i=0; i < a.length; i++) { el = $(form[a[i].name]); el[ useProp ? 'prop' : 'attr' ]('disabled', false); } } if ($(':input[name=submit],:input[id=submit]', form).length) { // if there is an input with a name or id of 'submit' then we won't be // able to invoke the submit fn on the form (at least not x-browser) alert('Error: Form elements must not have name or id of "submit".'); return; } s = $.extend(true, {}, $.ajaxSettings, options); s.context = s.context || s; id = 'jqFormIO' + (new Date().getTime()); if (s.iframeTarget) { $io = $(s.iframeTarget); n = $io.attr('name'); if (n == null) $io.attr('name', id); else id = n; } else { $io = $('<iframe name="' + id + '" src="'+ s.iframeSrc +'" />'); $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' }); } io = $io[0]; xhr = { // mock object aborted: 0, responseText: null, responseXML: null, status: 0, statusText: 'n/a', getAllResponseHeaders: function() {}, getResponseHeader: function() {}, setRequestHeader: function() {}, abort: function(status) { var e = (status === 'timeout' ? 'timeout' : 'aborted'); log('aborting upload... ' + e); this.aborted = 1; $io.attr('src', s.iframeSrc); // abort op in progress xhr.error = e; s.error && s.error.call(s.context, xhr, e, status); g && $.event.trigger("ajaxError", [xhr, s, e]); s.complete && s.complete.call(s.context, xhr, e); } }; g = s.global; // trigger ajax global events so that activity/block indicators work like normal if (g && ! $.active++) { $.event.trigger("ajaxStart"); } if (g) { $.event.trigger("ajaxSend", [xhr, s]); } if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) { if (s.global) { $.active--; } return; } if (xhr.aborted) { return; } // add submitting element to data if we know it sub = form.clk; if (sub) { n = sub.name; if (n && !sub.disabled) { s.extraData = s.extraData || {}; s.extraData[n] = sub.value; if (sub.type == "image") { s.extraData[n+'.x'] = form.clk_x; s.extraData[n+'.y'] = form.clk_y; } } } var CLIENT_TIMEOUT_ABORT = 1; var SERVER_ABORT = 2; function getDoc(frame) { var doc = frame.contentWindow ? frame.contentWindow.document : frame.contentDocument ? frame.contentDocument : frame.document; return doc; } // take a breath so that pending repaints get some cpu time before the upload starts function doSubmit() { // make sure form attrs are set var t = $form.attr('target'), a = $form.attr('action'); // update form attrs in IE friendly way form.setAttribute('target',id); if (!method) { form.setAttribute('method', 'POST'); } if (a != s.url) { form.setAttribute('action', s.url); } // ie borks in some cases when setting encoding if (! s.skipEncodingOverride && (!method || /post/i.test(method))) { $form.attr({ encoding: 'multipart/form-data', enctype: 'multipart/form-data' }); } // support timout if (s.timeout) { timeoutHandle = setTimeout(function() { timedOut = true; cb(CLIENT_TIMEOUT_ABORT); }, s.timeout); } // look for server aborts function checkState() { try { var state = getDoc(io).readyState; log('state = ' + state); if (state.toLowerCase() == 'uninitialized') setTimeout(checkState,50); } catch(e) { log('Server abort: ' , e, ' (', e.name, ')'); cb(SERVER_ABORT); timeoutHandle && clearTimeout(timeoutHandle); timeoutHandle = undefined; } } // add "extra" data to form if provided in options var extraInputs = []; try { if (s.extraData) { for (var n in s.extraData) { extraInputs.push( $('<input type="hidden" name="'+n+'" />').attr('value',s.extraData[n]) .appendTo(form)[0]); } } if (!s.iframeTarget) { // add iframe to doc and submit the form $io.appendTo('body'); io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false); } setTimeout(checkState,15); form.submit(); } finally { // reset attrs and remove "extra" input elements form.setAttribute('action',a); if(t) { form.setAttribute('target', t); } else { $form.removeAttr('target'); } $(extraInputs).remove(); } } if (s.forceSync) { doSubmit(); } else { setTimeout(doSubmit, 10); // this lets dom updates render } var data, doc, domCheckCount = 50, callbackProcessed; function cb(e) { if (xhr.aborted || callbackProcessed) { return; } try { doc = getDoc(io); } catch(ex) { log('cannot access response document: ', ex); e = SERVER_ABORT; } if (e === CLIENT_TIMEOUT_ABORT && xhr) { xhr.abort('timeout'); return; } else if (e == SERVER_ABORT && xhr) { xhr.abort('server abort'); return; } if (!doc || doc.location.href == s.iframeSrc) { // response not received yet if (!timedOut) return; } io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false); var status = 'success', errMsg; try { if (timedOut) { throw 'timeout'; } var isXml = s.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc); log('isXml='+isXml); if (!isXml && window.opera && (doc.body == null || doc.body.innerHTML == '')) { if (--domCheckCount) { // in some browsers (Opera) the iframe DOM is not always traversable when // the onload callback fires, so we loop a bit to accommodate log('requeing onLoad callback, DOM not available'); setTimeout(cb, 250); return; } // let this fall through because server response could be an empty document //log('Could not access iframe DOM after mutiple tries.'); //throw 'DOMException: not available'; } //log('response detected'); var docRoot = doc.body ? doc.body : doc.documentElement; xhr.responseText = docRoot ? docRoot.innerHTML : null; xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc; if (isXml) s.dataType = 'xml'; xhr.getResponseHeader = function(header){ var headers = {'content-type': s.dataType}; return headers[header]; }; // support for XHR 'status' & 'statusText' emulation : if (docRoot) { xhr.status = Number( docRoot.getAttribute('status') ) || xhr.status; xhr.statusText = docRoot.getAttribute('statusText') || xhr.statusText; } var dt = s.dataType || ''; var scr = /(json|script|text)/.test(dt.toLowerCase()); if (scr || s.textarea) { // see if user embedded response in textarea var ta = doc.getElementsByTagName('textarea')[0]; if (ta) { xhr.responseText = ta.value; // support for XHR 'status' & 'statusText' emulation : xhr.status = Number( ta.getAttribute('status') ) || xhr.status; xhr.statusText = ta.getAttribute('statusText') || xhr.statusText; } else if (scr) { // account for browsers injecting pre around json response var pre = doc.getElementsByTagName('pre')[0]; var b = doc.getElementsByTagName('body')[0]; if (pre) { xhr.responseText = pre.textContent ? pre.textContent : pre.innerHTML; } else if (b) { xhr.responseText = b.innerHTML; } } } else if (s.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) { xhr.responseXML = toXml(xhr.responseText); } try { data = httpData(xhr, s.dataType, s); } catch (e) { status = 'parsererror'; xhr.error = errMsg = (e || status); } } catch (e) { log('error caught: ',e); status = 'error'; xhr.error = errMsg = (e || status); } if (xhr.aborted) { log('upload aborted'); status = null; } if (xhr.status) { // we've set xhr.status status = (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) ? 'success' : 'error'; } // ordering of these callbacks/triggers is odd, but that's how $.ajax does it if (status === 'success') { s.success && s.success.call(s.context, data, 'success', xhr); g && $.event.trigger("ajaxSuccess", [xhr, s]); } else if (status) { if (errMsg == undefined) errMsg = xhr.statusText; s.error && s.error.call(s.context, xhr, status, errMsg); g && $.event.trigger("ajaxError", [xhr, s, errMsg]); } g && $.event.trigger("ajaxComplete", [xhr, s]); if (g && ! --$.active) { $.event.trigger("ajaxStop"); } s.complete && s.complete.call(s.context, xhr, status); callbackProcessed = true; if (s.timeout) clearTimeout(timeoutHandle); // clean up setTimeout(function() { if (!s.iframeTarget) $io.remove(); xhr.responseXML = null; }, 100); } var toXml = $.parseXML || function(s, doc) { // use parseXML if available (jQuery 1.5+) if (window.ActiveXObject) { doc = new ActiveXObject('Microsoft.XMLDOM'); doc.async = 'false'; doc.loadXML(s); } else { doc = (new DOMParser()).parseFromString(s, 'text/xml'); } return (doc && doc.documentElement && doc.documentElement.nodeName != 'parsererror') ? doc : null; }; var parseJSON = $.parseJSON || function(s) { return window['eval']('(' + s + ')'); }; var httpData = function( xhr, type, s ) { // mostly lifted from jq1.4.4 var ct = xhr.getResponseHeader('content-type') || '', xml = type === 'xml' || !type && ct.indexOf('xml') >= 0, data = xml ? xhr.responseXML : xhr.responseText; if (xml && data.documentElement.nodeName === 'parsererror') { $.error && $.error('parsererror'); } if (s && s.dataFilter) { data = s.dataFilter(data, type); } if (typeof data === 'string') { if (type === 'json' || !type && ct.indexOf('json') >= 0) { data = parseJSON(data); } else if (type === "script" || !type && ct.indexOf("javascript") >= 0) { $.globalEval(data); } } return data; }; } }; /** * ajaxForm() provides a mechanism for fully automating form submission. * * The advantages of using this method instead of ajaxSubmit() are: * * 1: This method will include coordinates for <input type="image" /> elements (if the element * is used to submit the form). * 2. This method will include the submit element's name/value data (for the element that was * used to submit the form). * 3. This method binds the submit() method to the form for you. * * The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely * passes the options argument along after properly binding events for submit elements and * the form itself. */ $.fn.ajaxForm = function(options) { // in jQuery 1.3+ we can fix mistakes with the ready state if (this.length === 0) { var o = { s: this.selector, c: this.context }; if (!$.isReady && o.s) { log('DOM not ready, queuing ajaxForm'); $(function() { $(o.s,o.c).ajaxForm(options); }); return this; } // is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready() log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)')); return this; } return this.ajaxFormUnbind().bind('submit.form-plugin', function(e) { if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed e.preventDefault(); $(this).ajaxSubmit(options); } }).bind('click.form-plugin', function(e) { var target = e.target; var $el = $(target); if (!($el.is(":submit,input:image"))) { // is this a child element of the submit el? (ex: a span within a button) var t = $el.closest(':submit'); if (t.length == 0) { return; } target = t[0]; } var form = this; form.clk = target; if (target.type == 'image') { if (e.offsetX != undefined) { form.clk_x = e.offsetX; form.clk_y = e.offsetY; } else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin var offset = $el.offset(); form.clk_x = e.pageX - offset.left; form.clk_y = e.pageY - offset.top; } else { form.clk_x = e.pageX - target.offsetLeft; form.clk_y = e.pageY - target.offsetTop; } } // clear form vars setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100); }); }; // ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm $.fn.ajaxFormUnbind = function() { return this.unbind('submit.form-plugin click.form-plugin'); }; /** * formToArray() gathers form element data into an array of objects that can * be passed to any of the following ajax functions: $.get, $.post, or load. * Each object in the array has both a 'name' and 'value' property. An example of * an array for a simple login form might be: * * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ] * * It is this array that is passed to pre-submit callback functions provided to the * ajaxSubmit() and ajaxForm() methods. */ $.fn.formToArray = function(semantic) { var a = []; if (this.length === 0) { return a; } var form = this[0]; var els = semantic ? form.getElementsByTagName('*') : form.elements; if (!els) { return a; } var i,j,n,v,el,max,jmax; for(i=0, max=els.length; i < max; i++) { el = els[i]; n = el.name; if (!n) { continue; } if (semantic && form.clk && el.type == "image") { // handle image inputs on the fly when semantic == true if(!el.disabled && form.clk == el) { a.push({name: n, value: $(el).val()}); a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y}); } continue; } v = $.fieldValue(el, true); if (v && v.constructor == Array) { for(j=0, jmax=v.length; j < jmax; j++) { a.push({name: n, value: v[j]}); } } else if (v !== null && typeof v != 'undefined') { a.push({name: n, value: v}); } } if (!semantic && form.clk) { // input type=='image' are not found in elements array! handle it here var $input = $(form.clk), input = $input[0]; n = input.name; if (n && !input.disabled && input.type == 'image') { a.push({name: n, value: $input.val()}); a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y}); } } return a; }; /** * Serializes form data into a 'submittable' string. This method will return a string * in the format: name1=value1&amp;name2=value2 */ $.fn.formSerialize = function(semantic) { //hand off to jQuery.param for proper encoding return $.param(this.formToArray(semantic)); }; /** * Serializes all field elements in the jQuery object into a query string. * This method will return a string in the format: name1=value1&amp;name2=value2 */ $.fn.fieldSerialize = function(successful) { var a = []; this.each(function() { var n = this.name; if (!n) { return; } var v = $.fieldValue(this, successful); if (v && v.constructor == Array) { for (var i=0,max=v.length; i < max; i++) { a.push({name: n, value: v[i]}); } } else if (v !== null && typeof v != 'undefined') { a.push({name: this.name, value: v}); } }); //hand off to jQuery.param for proper encoding return $.param(a); }; /** * Returns the value(s) of the element in the matched set. For example, consider the following form: * * <form><fieldset> * <input name="A" type="text" /> * <input name="A" type="text" /> * <input name="B" type="checkbox" value="B1" /> * <input name="B" type="checkbox" value="B2"/> * <input name="C" type="radio" value="C1" /> * <input name="C" type="radio" value="C2" /> * </fieldset></form> * * var v = $(':text').fieldValue(); * // if no values are entered into the text inputs * v == ['',''] * // if values entered into the text inputs are 'foo' and 'bar' * v == ['foo','bar'] * * var v = $(':checkbox').fieldValue(); * // if neither checkbox is checked * v === undefined * // if both checkboxes are checked * v == ['B1', 'B2'] * * var v = $(':radio').fieldValue(); * // if neither radio is checked * v === undefined * // if first radio is checked * v == ['C1'] * * The successful argument controls whether or not the field element must be 'successful' * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls). * The default value of the successful argument is true. If this value is false the value(s) * for each element is returned. * * Note: This method *always* returns an array. If no valid value can be determined the * array will be empty, otherwise it will contain one or more values. */ $.fn.fieldValue = function(successful) { for (var val=[], i=0, max=this.length; i < max; i++) { var el = this[i]; var v = $.fieldValue(el, successful); if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) { continue; } v.constructor == Array ? $.merge(val, v) : val.push(v); } return val; }; /** * Returns the value of the field element. */ $.fieldValue = function(el, successful) { var n = el.name, t = el.type, tag = el.tagName.toLowerCase(); if (successful === undefined) { successful = true; } if (successful && (!n || el.disabled || t == 'reset' || t == 'button' || (t == 'checkbox' || t == 'radio') && !el.checked || (t == 'submit' || t == 'image') && el.form && el.form.clk != el || tag == 'select' && el.selectedIndex == -1)) { return null; } if (tag == 'select') { var index = el.selectedIndex; if (index < 0) { return null; } var a = [], ops = el.options; var one = (t == 'select-one'); var max = (one ? index+1 : ops.length); for(var i=(one ? index : 0); i < max; i++) { var op = ops[i]; if (op.selected) { var v = op.value; if (!v) { // extra pain for IE... v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value; } if (one) { return v; } a.push(v); } } return a; } return $(el).val(); }; /** * Clears the form data. Takes the following actions on the form's input fields: * - input text fields will have their 'value' property set to the empty string * - select elements will have their 'selectedIndex' property set to -1 * - checkbox and radio inputs will have their 'checked' property set to false * - inputs of type submit, button, reset, and hidden will *not* be effected * - button elements will *not* be effected */ $.fn.clearForm = function() { return this.each(function() { $('input,select,textarea', this).clearFields(); }); }; /** * Clears the selected form elements. */ $.fn.clearFields = $.fn.clearInputs = function() { var re = /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i; // 'hidden' is not in this list return this.each(function() { var t = this.type, tag = this.tagName.toLowerCase(); if (re.test(t) || tag == 'textarea') { this.value = ''; } else if (t == 'checkbox' || t == 'radio') { this.checked = false; } else if (tag == 'select') { this.selectedIndex = -1; } }); }; /** * Resets the form data. Causes all form elements to be reset to their original value. */ $.fn.resetForm = function() { return this.each(function() { // guard against an input with the name of 'reset' // note that IE reports the reset function as an 'object' if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) { this.reset(); } }); }; /** * Enables or disables any matching elements. */ $.fn.enable = function(b) { if (b === undefined) { b = true; } return this.each(function() { this.disabled = !b; }); }; /** * Checks/unchecks any matching checkboxes or radio buttons and * selects/deselects and matching option elements. */ $.fn.selected = function(select) { if (select === undefined) { select = true; } return this.each(function() { var t = this.type; if (t == 'checkbox' || t == 'radio') { this.checked = select; } else if (this.tagName.toLowerCase() == 'option') { var $sel = $(this).parent('select'); if (select && $sel[0] && $sel[0].type == 'select-one') { // deselect all other options $sel.find('option').selected(false); } this.selected = select; } }); }; // helper fn for console logging function log() { var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,''); if (window.console && window.console.log) { window.console.log(msg); } else if (window.opera && window.opera.postError) { window.opera.postError(msg); } }; })(jQuery);
JavaScript
function search() { var temp = document.getElementById('choose_category'); var category = temp.value; var temp = document.getElementById('choose_location'); var location = temp.value; $.ajax({ url : base_url + "alternatives/sort/"+category + "/" + location, type : 'post', dataType : 'json', success : function (response) { alternatives = response; curr_page = 1; per_page = 8; num_pages = Math.ceil(alternatives.length / per_page); if(num_pages == 0){ num_pages = 1; } makePaginator(); DisplayPage(curr_page); positionPaginator(); $(".resize-200").load(function(){ resize($(this), 200); }); replaceIdByName(); replaceIdByPic(); } }); }
JavaScript
function submitwant() { cat = document.getElementById('input_category_id'); desc = document.getElementById('textfield'); $.ajax({ url : base_url + "wants/submitwant", type : 'post', data : { category : cat.value, desc : desc.value, }, dataType : 'json', success : function (response) { window.location.reload(); } }); } function submitsearch() { c = document.getElementById('category_id'); s = document.getElementById('searchfield'); f = document.getElementById('filter'); $.ajax({ url : base_url+ "wants/search_result", type : 'post', data : { category : c.value, search : s.value, filter : f.value, }, dataType : 'json', success : function (response) { searchresults = response; curr_page = 1; per_page = 9; num_pages = Math.ceil(searchresults.length / per_page); if(num_pages == 0){ num_pages = 1; } makePaginator(); DisplayPage(curr_page); positionPaginator(); replaceIdByName(); replaceIdByPic(); } }); } var selectedWant = -1; function help(want) { selectedWant = want; $.ajax({ url : "wants/getrelatedoffers/", type : 'post', data : { want_id : want, }, dataType : 'json', success : function(response) { html = ''; if (response.length == 0){ html = '<div class="medium-text">You have no related offer to suggest.</div>'; } else { html= '<div id="offers-popup"><span class="medium-text">Select an existing offer</span><br />'; html+= '<select id="offerselect">'; for (var i = 0; i< response.length;i++) { html+= '<option value='+response[i].offer_id+'>'+response[i].item_title+'</option>'; } html+= '</select>'; html+= '<div id="submit-button-popup"><a href="Javascript:void(0);" onclick = "offersuggest()" ></a></div><br />'; html+= '</div>'; } var $dialog = $(html) .dialog({ height: 210, width: 550, modal: 'true', title : 'Offer Suggestion', buttons : { 'Close' : function() { $(this).dialog('close'); } } }); } }); } function offersuggest() { var $dialog = $('<div></div>') .html('<span class="medium-text">Are you sure you want to suggest this offer?</span>') .dialog({ modal: 'true', title : 'Confirm Suggestion', buttons : { 'Yes' : function() { $.ajax({ url : "wants/offersuggest/", type : 'post', data : { offer_id : $('#offerselect').val(), want_id : selectedWant, }, success : function(response) { $('#offers-popup').html('<span class="medium-text">A notification has been sent to the person. Thanks for your help!</span>'); } }); $(this).dialog('close'); }, 'No' : function() { $(this).dialog('close'); }, } }); } function deletewant(want) { var $dialog = $('<div></div>') .html('<span class="medium-text">Are you sure you want to delete this?</span>') .dialog({ modal: 'true', title : 'Delete', buttons : { 'Yes' : function() { $.ajax({ url : "wants/delete/", type : 'post', data : { want_id : want, }, success : function(response) { window.location.reload(); $(this).dialog('close'); } }); }, 'No' : function() { $(this).dialog('close'); }, } }); }
JavaScript
var curr_page = 1; var per_page = 10; var num_pages = Math.ceil(searchresults.length / per_page); if(num_pages == 0){ num_pages = 1; } function makePaginator(){ $("#paginator").paginate({ count: num_pages, start: curr_page, display: 5, border: true, border_color: '#CD9F33', text_color: '#6F4632', background_color: '#FAF2E1', border_hover_color: '#B18110', text_hover_color: '#6F4632', background_hover_color: '#DCC388', images: false, mouse: 'press', onChange: function(page){ DisplayPage(page); positionPaginator(); replaceIdByName(); replaceIdByPic(); } }); } function DisplayPage(page){ var html = ''; num = 0; curr_page = page; html += '<ul class="wants-list">'; for (var i = 0; i < per_page; i++){ var counter = ((page - 1) * per_page) + i; if (typeof(searchresults[counter]) == "undefined"){ if(html == '<ul class="wants-list">'){ html += '<br /><span class="medium-text">No wants found. <br /><br />Do you have anything that you want?</span>'; } break; } html += '<li>'; html += '<div class="single-want normal-text">'; html += '<div style="float: left width=80% margin: 10px; padding: 5px;"><a href="profile/' + searchresults[counter].fb_id+ '"><span class="get-fb-name">'+searchresults[counter].fb_id+'</span></a><span class="small-text"> ('+categories[searchresults[counter].category_id]+')</span>: ' + searchresults[counter].description.substr(0, 350); + '</div>'; if(current_user == searchresults[counter].fb_id){ html += '<div id="delete-button" style="float:right; margin-right: 5%"><a href="Javascript:void(0);" onclick = "deletewant('+searchresults[counter].want_id+')" ></a></div>'; } else{ html += '<div id="help-button" style="float:right; margin-right: 5%"><a href="Javascript:void(0);" onclick = "help('+searchresults[counter].want_id+')" ></a></div>'; } html += '</div>'; html += '<div style="clear:both"></div>'; html += '</li>'; } html += '</ul>'; $("#wants-results").html(html); } function positionPaginator(){ var width = $('#wants-container').width(); var length = num_pages > 5 ? 5 : num_pages; var actual = 60 + 60 + 25 * num_pages; $('#paginator').css('margin-left', (width - actual) / 2); } $(function(){ makePaginator(); DisplayPage(curr_page); positionPaginator(); });
JavaScript
(function($) { $.fn.paginate = function(options) { var opts = $.extend({}, $.fn.paginate.defaults, options); return this.each(function() { $this = $(this); var o = $.meta ? $.extend({}, opts, $this.data()) : opts; var selectedpage = o.start; $.fn.draw(o,$this,selectedpage); }); }; var outsidewidth_tmp = 0; var insidewidth = 0; var bName = navigator.appName; var bVer = navigator.appVersion; if(bVer.indexOf('MSIE 7.0') > 0) var ver = "ie7"; $.fn.paginate.defaults = { count : 5, start : 12, display : 5, border : true, border_color : '#fff', text_color : '#8cc59d', background_color : 'black', border_hover_color : '#fff', text_hover_color : '#fff', background_hover_color : '#fff', rotate : true, images : true, mouse : 'slide', onChange : function(){return false;} }; $.fn.draw = function(o,obj,selectedpage){ if(o.display > o.count) o.display = o.count; $this.empty(); if(o.images){ var spreviousclass = 'jPag-sprevious-img'; var previousclass = 'jPag-previous-img'; var snextclass = 'jPag-snext-img'; var nextclass = 'jPag-next-img'; } else{ var spreviousclass = 'jPag-sprevious'; var previousclass = 'jPag-previous'; var snextclass = 'jPag-snext'; var nextclass = 'jPag-next'; } var _first = $(document.createElement('a')).addClass('jPag-first').html('First'); if(o.rotate){ if(o.images) var _rotleft = $(document.createElement('span')).addClass(spreviousclass); else var _rotleft = $(document.createElement('span')).addClass(spreviousclass).html('&laquo;'); } var _divwrapleft = $(document.createElement('div')).addClass('jPag-control-back'); _divwrapleft.append(_first).append(_rotleft); var _ulwrapdiv = $(document.createElement('div')).css('overflow','hidden'); var _ul = $(document.createElement('ul')).addClass('jPag-pages') var c = (o.display - 1) / 2; var first = selectedpage - c; var selobj; for(var i = 0; i < o.count; i++){ var val = i+1; if(val == selectedpage){ var _obj = $(document.createElement('li')).html('<span class="jPag-current">'+val+'</span>'); selobj = _obj; _ul.append(_obj); } else{ var _obj = $(document.createElement('li')).html('<a>'+ val +'</a>'); _ul.append(_obj); } } _ulwrapdiv.append(_ul); if(o.rotate){ if(o.images) var _rotright = $(document.createElement('span')).addClass(snextclass); else var _rotright = $(document.createElement('span')).addClass(snextclass).html('&raquo;'); } var _last = $(document.createElement('a')).addClass('jPag-last').html('Last'); var _divwrapright = $(document.createElement('div')).addClass('jPag-control-front'); _divwrapright.append(_rotright).append(_last); //append all: $this.addClass('jPaginate').append(_divwrapleft).append(_ulwrapdiv).append(_divwrapright); if(!o.border){ if(o.background_color == 'none') var a_css = {'color':o.text_color}; else var a_css = {'color':o.text_color,'background-color':o.background_color}; if(o.background_hover_color == 'none') var hover_css = {'color':o.text_hover_color}; else var hover_css = {'color':o.text_hover_color,'background-color':o.background_hover_color}; } else{ if(o.background_color == 'none') var a_css = {'color':o.text_color,'border':'1px solid '+o.border_color}; else var a_css = {'color':o.text_color,'background-color':o.background_color,'border':'1px solid '+o.border_color}; if(o.background_hover_color == 'none') var hover_css = {'color':o.text_hover_color,'border':'1px solid '+o.border_hover_color}; else var hover_css = {'color':o.text_hover_color,'background-color':o.background_hover_color,'border':'1px solid '+o.border_hover_color}; } $.fn.applystyle(o,$this,a_css,hover_css,_first,_ul,_ulwrapdiv,_divwrapright); //calculate width of the ones displayed: var outsidewidth = outsidewidth_tmp - _first.parent().width() -3; if(ver == 'ie7'){ _ulwrapdiv.css('width',outsidewidth+72+'px'); _divwrapright.css('left',outsidewidth_tmp+6+72+'px'); } else{ _ulwrapdiv.css('width',outsidewidth+'px'); _divwrapright.css('left',outsidewidth_tmp+6+'px'); } if(o.rotate){ _rotright.hover( function() { thumbs_scroll_interval = setInterval( function() { var left = _ulwrapdiv.scrollLeft() + 1; _ulwrapdiv.scrollLeft(left); }, 20 ); }, function() { clearInterval(thumbs_scroll_interval); } ); _rotleft.hover( function() { thumbs_scroll_interval = setInterval( function() { var left = _ulwrapdiv.scrollLeft() - 1; _ulwrapdiv.scrollLeft(left); }, 20 ); }, function() { clearInterval(thumbs_scroll_interval); } ); if(o.mouse == 'press'){ _rotright.mousedown( function() { thumbs_mouse_interval = setInterval( function() { var left = _ulwrapdiv.scrollLeft() + 5; _ulwrapdiv.scrollLeft(left); }, 20 ); } ).mouseup( function() { clearInterval(thumbs_mouse_interval); } ); _rotleft.mousedown( function() { thumbs_mouse_interval = setInterval( function() { var left = _ulwrapdiv.scrollLeft() - 5; _ulwrapdiv.scrollLeft(left); }, 20 ); } ).mouseup( function() { clearInterval(thumbs_mouse_interval); } ); } else{ _rotleft.click(function(e){ var width = outsidewidth - 10; var left = _ulwrapdiv.scrollLeft() - width; _ulwrapdiv.animate({scrollLeft: left +'px'}); }); _rotright.click(function(e){ var width = outsidewidth - 10; var left = _ulwrapdiv.scrollLeft() + width; _ulwrapdiv.animate({scrollLeft: left +'px'}); }); } } //first and last: _first.click(function(e){ _ulwrapdiv.animate({scrollLeft: '0px'}); _ulwrapdiv.find('li').eq(0).click(); }); _last.click(function(e){ _ulwrapdiv.animate({scrollLeft: insidewidth +'px'}); _ulwrapdiv.find('li').eq(o.count - 1).click(); }); //click a page _ulwrapdiv.find('li').click(function(e){ selobj.html('<a>'+selobj.find('.jPag-current').html()+'</a>'); var currval = $(this).find('a').html(); $(this).html('<span class="jPag-current">'+currval+'</span>'); selobj = $(this); $.fn.applystyle(o,$(this).parent().parent().parent(),a_css,hover_css,_first,_ul,_ulwrapdiv,_divwrapright); var left = (this.offsetLeft) / 2; var left2 = _ulwrapdiv.scrollLeft() + left; var tmp = left - (outsidewidth / 2); if(ver == 'ie7') _ulwrapdiv.animate({scrollLeft: left + tmp - _first.parent().width() + 52 + 'px'}); else _ulwrapdiv.animate({scrollLeft: left + tmp - _first.parent().width() + 'px'}); o.onChange(currval); }); var last = _ulwrapdiv.find('li').eq(o.start-1); last.attr('id','tmp'); var left = document.getElementById('tmp').offsetLeft / 2; last.removeAttr('id'); var tmp = left - (outsidewidth / 2); if(ver == 'ie7') _ulwrapdiv.animate({scrollLeft: left + tmp - _first.parent().width() + 52 + 'px'}); else _ulwrapdiv.animate({scrollLeft: left + tmp - _first.parent().width() + 'px'}); } $.fn.applystyle = function(o,obj,a_css,hover_css,_first,_ul,_ulwrapdiv,_divwrapright){ obj.find('a').css(a_css); obj.find('span.jPag-current').css(hover_css); obj.find('a').hover( function(){ $(this).css(hover_css); }, function(){ $(this).css(a_css); } ); obj.css('padding-left',_first.parent().width() + 5 +'px'); insidewidth = 0; obj.find('li').each(function(i,n){ if(i == (o.display-1)){ outsidewidth_tmp = this.offsetLeft + this.offsetWidth ; } insidewidth += this.offsetWidth; }) _ul.css('width',insidewidth + 4 +'px'); } })(jQuery);
JavaScript
function cancel_offer(id, status) { switch(status) { case "Available": var $dialog = $('<div></div>') .html('There may be people interested in your item. Are you sure you want to remove this offer?') .dialog({ modal: 'true', title : 'Remove Offer', buttons : { 'Yes' : function() { $.ajax({ url : "home/remove_offer/", type : 'post', data : { status : 'available', offer_id : id, }, success : function(response) { removeOffer(id); } }); $(this).dialog('close'); }, 'No' : function() { $(this).dialog('close'); } } }); break; case "Reserved": var $dialog = $('<div></div>') .html('You have already reserved your item to someone. Are you sure you want to reject your reservation?') .dialog({ modal: 'true', title : 'Cancel Offer', buttons : { 'Yes' : function() { $.ajax({ url : "home/remove_offer/", type : 'post', data : { status : 'reserved', offer_id : id, }, success : function(response) { $("#offer_"+id+"_status").text("Status : Available"); } }); $(this).dialog('close'); }, 'No' : function() { $(this).dialog('close'); } } }); break; default: } } function cancel_request(id, status) { switch(status) { case "Pending": var $dialog = $('<div></div>') .html('Are you sure you want to remove this request?') .dialog({ modal: 'true', title : 'Remove Request', buttons : { 'Yes' : function() { $.ajax({ url : "home/remove_request/", type : 'post', data : { status : 'pending', offer_id : id, }, success : function(response) { removeRequest(id); } }); $(this).dialog('close'); }, 'No' : function() { $(this).dialog('close'); } } }); break; case "Offered to you": var $dialog = $('<div></div>') .html("This item has been offered to you. Are you sure you don't want it anymore?") .dialog({ modal: 'true', title : 'Cancel Request', buttons : { 'Yes' : function() { $.ajax({ url : "home/remove_request/", type : 'post', data : { status : 'offeredtoyou', offer_id : id, }, success : function(response) { removeRequest(id); } }); $(this).dialog('close'); }, 'No' : function() { $(this).dialog('close'); } } }); break; case "Offered to someone else": var $dialog = $('<div></div>') .html("You may still get this item if the offer does not go through. Are you sure you don't want it anymore?") .dialog({ modal: 'true', title : 'Remove Request', buttons : { 'Yes' : function() { $.ajax({ url : "home/remove_request/", type : 'post', data : { status : 'offeredtosomeoneelse', offer_id : id, }, success : function(response) { removeRequest(id); } }); $(this).dialog('close'); }, 'No' : function() { $(this).dialog('close'); } } }); break; default: } }
JavaScript
$(function() { $( "#tabs" ).tabs(); });
JavaScript
function submitsearch() { c = document.getElementById('category_id'); s = document.getElementById('searchfield'); sb = document.getElementById('sort_by'); p = document.getElementById('price'); show = document.getElementById('show'); prefer = document.getElementById('preference'); $.ajax({ url : base_url+ "browse/search_result", type : 'post', data : { category : c.value, search : s.value, sort_by : sb.value, show : show.value, price : p.value, preference : prefer.checked, }, dataType : 'json', success : function (response) { searchresults = response; curr_page = 1; per_page = 16; num_pages = Math.ceil(searchresults.length / per_page); if(num_pages == 0){ num_pages = 1; } makePaginator(); DisplayPage(curr_page); positionPaginator(); $(".resize-150").load(function(){ resize($(this), 150); }); replaceIdByName(); replaceIdByPic(); } }); }
JavaScript
$(document).ready(function() { $('#userfile').live('change', function() { $("#image_preview").html(''); $("#image_preview").html('<img src="../resources/loader.gif" alt="Uploading...."/>'); $("#offer-form").ajaxForm({ target: '#image_preview' }).submit(); }); });
JavaScript
function give_offer(offer, fb_id) { var $dialog = $('<div></div>') .html('Are you sure you want to give this offer to this person?') .dialog({ modal: 'true', title : 'Give Offer', buttons : { 'Yes' : function() { $.ajax({ url : "giveoffer/", type : 'post', data : { offer_id : offer, fb : fb_id, }, success : function(response) { window.location.reload(); } }); }, 'No' : function() { $(this).dialog('close'); } } }); } function reject_requester(offer) { var $dialog = $('<div></div>') .html('Are you sure you want to cancel your reservation of your item to this person?') .dialog({ modal: 'true', title : 'Cancel reservation', buttons : { 'Yes' : function() { $.ajax({ url : "rejectrequester/", type : 'post', data : { offer_id : offer, }, success : function(response) { window.location.reload(); } }); }, 'No' : function() { $(this).dialog('close'); } } }); } function accept_offer(offer) { var $dialog = $('<div></div>') .html('Are you sure you have received the item and want to close this transaction?') .dialog({ modal: 'true', title : 'Accept Request', buttons : { 'Yes' : function() { $.ajax({ url : "acceptoffer/", type : 'post', data : { offer_id : offer, }, success : function(response) { window.location.reload(); } }); }, 'No' : function() { $(this).dialog('close'); } } }); } function cancel_accepted_offer(offer) { var $dialog = $('<div></div>') .html('This item has been offered to you. Are you sure you want to reject it?') .dialog({ modal: 'true', title : 'Cancel Request', buttons : { 'Yes' : function() { $.ajax({ url : "canceloffer/", type : 'post', data : { status : 'accepted', offer_id : offer, }, success : function(response) { window.location.reload(); } }); }, 'No' : function() { $(this).dialog('close'); } } }); } function cancel_pending_offer(offer) { var $dialog = $('<div></div>') .html('Are you sure you want to cancel this request?') .dialog({ modal: 'true', title : 'Cancel Request', buttons : { 'Yes' : function() { $.ajax({ url : "canceloffer/", type : 'post', data : { status : 'pending', offer_id : offer, }, success : function(response) { window.location.reload(); } }); }, 'No' : function() { $(this).dialog('close'); } } }); } function request_offer(offer, status) { switch(status) { case "Available": var $dialog = $('<div></div>') .html('Are you sure you want to make an request for this offer?') .dialog({ modal: 'true', title : 'Request Item', buttons : { 'Yes' : function() { $.ajax({ url : "requestoffer/", type : 'post', data : { status : 'available', offer_id : offer, }, success : function(response) { window.location.reload(); } }); }, 'No' : function() { $(this).dialog('close'); } } }); break; case "Reserved": var $dialog = $('<div></div>') .html('This item has been reserved to someone else. Are you sure you want to make a request for it?') .dialog({ modal: 'true', title : 'Request Item', buttons : { 'Yes' : function() { $.ajax({ url : "requestoffer/", type : 'post', data : { status : 'reserved', offer_id : offer, }, success : function(response) { window.location.reload(); } }); }, 'No' : function() { $(this).dialog('close'); } } }); break; default: } } var lasttimestamp; function submitComment(id, fb_id) { var commentText = document.getElementById('comment-field'); $.ajax({ url : "submitcomment/", type : 'post', data : { last_timestamp : lasttimestamp, offer_id : id, comment : commentText.value, }, dataType : 'json', success : function(response) { html = ''; for(var i=0;i<response.length;i++) { html += '<div class="single-comment-container" id = "comment_' + response[i].chat_id + '">'; html += '<div class="facebook-info">'; html += '<span class="get-fb-pic">' + response[i].poster_fb_id + '</span>'; html += '</div>'; html += '<div class="comment-content">'; html += '<div class = "datetime small-text">'+response[i].date_created+'</div>'; html += '<span class="get-fb-name">'+response[i].poster_fb_id+'</span> says: <br />'; html += '<div class = "message">'+response[i].message.replace(/\n/g, '<br />');+'</div>'; if(response[i].poster_fb_id == fb_id){ html+= '<br /><a class = "action-button action-delete" href = "Javascript:void(0);" onclick="deleteComment('+response[i].chat_id+ ')" /></a>'; } html += '</div>'; html += '<div style="clear: both"></div>'; html += '</div>'; } if (response) lasttimestamp = response[response.length-1].date_created; $('.new-comment').before(html); replaceIdByName(); replaceIdByPic(); } }); } function deleteComment(id) { var $dialog = $('<div></div>') .html('Are you sure you want to delete this comment?') .dialog({ modal: 'true', title : 'Delete Comment', buttons : { 'Yes' : function() { $.ajax({ url : "deletecomment/"+id, type : 'post', data : { chat_id : id, }, success : function (response) { $("#comment_"+id).hide(); } }); $(this).dialog('close'); }, 'No' : function() { $(this).dialog('close'); } } }); } function shareFB(base_url) { FB.ui( { method: 'feed', name: offer.item_title, link: base_url + 'itemdescription/' + offer.offer_id, picture: base_url + 'resources/offer_images_thumbnail/' + offer.item_pic, caption: 'I am offering this item up for grabs. Head over to The Trove for a look!', description: 'Description: ' + offer.item_desc, }, function(response) { if (response && response.post_id) { // Post published } else { // Post not published } } ); }
JavaScript
function replaceIdByName() { $(".get-fb-name").each(function(index, domEle) { var link = "/" + $(this).html(); FB.api(link, function(response) { // Update the names $(domEle).html(response.name); $(domEle).show(); }); }); } function replaceIdByPic() { $(".get-fb-pic").each(function(index, domEle) { if ($(this).html().charAt(0) != '<') { $(domEle).html("<img src='https://graph.facebook.com/" + $(this).html() + "/picture'/>"); $(domEle).show(); } }); $(".get-fb-pic-normal").each(function(index, domEle) { $(domEle).html("<img src='https://graph.facebook.com/" + $(this).html() + "/picture?type=normal'>"); $(domEle).show(); }); $(".get-fb-pic-large").each(function(index, domEle) { $(domEle).html("<img src='https://graph.facebook.com/" + $(this).html() + "/picture?type=large'>"); $(domEle).show(); }); } function resize(element, size){ element.hide(); console.log("resized"); var height = element.height(); var width = element.width(); if(height > width){ element.css('height', size + 'px'); element.css('width', ''); element.css('margin-top', 0); if(element.height() < size){ element.css('margin-top', ((size - element.height()) / 2)); } } else{ element.css('width', size + 'px'); element.css('height', ''); element.css('margin-top', 0); if(element.height() < size){ element.css('margin-top', ((size - element.height()) / 2)); } } element.show(); } function resizePictures() { $(".resize-100").each(function(index, domEle) { resize($(this), 100); }); $(".resize-150").each(function(index, domEle) { resize($(this), 150); }); $(".resize-200").each(function(index, domEle) { resize($(this), 200); }); } function initiateFeedbackform() { $(function(){ $('#contactable').contactable({ subject: 'A Feedback Message for The Trove', url : 'home/send_email', }); }); } window.onload = function(){ initiateFeedbackform(); replaceIdByName(); replaceIdByPic(); resizePictures(); }
JavaScript
var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-26642138-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();
JavaScript
// categories is a variable containing all the category available in the database //var category_preference = new Array (); // category object function category (category_id, category_name) { this.category_id = category_id; this.category_name = category_name; } // category sorting function function sort_cat(a,b) { return a.category_name > b.category_name; } // check whether a sub category is alr in the sub category preference. // return true if alr existed, and false otherwise. function exist_category(cat) { var flag = false; for (var i=0; i < category_preference.length; ++i) { if (category_preference[i].category_id == cat.category_id) { flag = true; break; } } return flag; } // add new category function add_category() { var chosen_cat = document.getElementById("choose_category"); var new_category = new category (categories[chosen_cat.value-1].category_id, categories[chosen_cat.value-1].category_name); if (exist_category(new_category) == false) { category_preference.push(new_category); category_preference.sort(sort_cat); display_category(); } update_category(); } // display the sub category container function display_category() { var category_container = document.getElementById("category_container"); while (category_container.hasChildNodes()) { category_container.removeChild(category_container.lastChild); } for (var i=0; i < category_preference.length; ++i) { var newdiv = document.createElement('div'); newdiv.setAttribute('id','category_' + category_preference[i].category_id); var cancel = document.createElement('a'); cancel.setAttribute('href','Javascript:void(0);'); cancel.setAttribute('id','cancel_'+i); cancel.setAttribute('onclick','remove_category(' + category_preference[i].category_id + ')'); cancel.innerHTML = "Remove"; newdiv.appendChild(cancel); var text = document.createElement('span'); text.setAttribute('class', 'normal-text'); text.innerHTML = "&nbsp-- " + category_preference[i].category_name; newdiv.appendChild(text); var text = document.createElement('span'); text.setAttribute('class', 'normal-text'); text.innerHTML = "&nbsp-- " + category_preference[i].category_name; newdiv.appendChild(text); category_container.appendChild(newdiv); } } // remove the corresponding category when a cancel is click function remove_category(no) { var category_container = document.getElementById("category_container"); var category = document.getElementById('category_' + no); for (var i=0; i < category_preference.length; ++i) { if (category_preference[i].category_id == no) { category_preference.splice(i,1); break; } } category_container.removeChild(category); update_category(); } // Update the category list input form to send to the sever; function update_category(){ var category_list = document.getElementById("category_list"); category_list.value = category_array_to_string(category_preference); } // Convert an array of category to string (only keep the category_id) function category_array_to_string(a){ var str = "[" ; for (var i=0; i < a.length-1; ++i) { str += '{"category_id":"' + a[i].category_id + '"},' ; } if (a.length > 0) { str += '{"category_id":"' + a[a.length-1].category_id + '"}' ; } str += "]"; return str; } $(function() { display_category(); update_category(); });
JavaScript
// Set star image when mouse hovers $('.ratings_stars').hover( // Handles the mouseover function() { $(this).prevAll().andSelf().addClass('ratings_over'); $(this).nextAll().removeClass('ratings_vote'); }, // Handles the mouseout function() { $(this).prevAll().andSelf().removeClass('ratings_over'); set_votes(); } ); // Click handler $('.ratings_stars').bind('click', function() { var star = this; var widget = $(this).parent(); var condition = document.getElementById('item_condition'); condition.value = $(star).attr('class').charAt(5); set_votes() ; }); //Display the star using the condition function set_votes() { var condition = document.getElementById('item_condition').value; $('.rate_widget').find('.star_' + condition).prevAll().andSelf().addClass('ratings_vote'); $('.rate_widget').find('.star_' + condition).nextAll().removeClass('ratings_vote'); } $(function(){ set_votes(); });
JavaScript
//Display the star using the condition function set_votes() { var condition = document.getElementById('item_condition').value; $('.rate_widget').find('.star_' + condition).prevAll().andSelf().addClass('ratings_vote'); $('.rate_widget').find('.star_' + condition).nextAll().removeClass('ratings_vote'); } $(function(){ set_votes(); });
JavaScript
var notifications_per_page = 12; var num_pages = Math.ceil(notifications.length / notifications_per_page); var default_page = 1; if(num_pages == 0){ num_pages = 1; } function date_format(date){ return date.substr(8, 2) + "/" + date.substr(5, 2) + "/" + date.substr(0, 4); } function displayPage(page){ var html = '<ul>'; var is_new = ''; for (var i = 0; i < notifications_per_page; i++){ var counter = ((page - 1) * notifications_per_page) + i; if (typeof(notifications[counter]) == "undefined"){ if(html == '<ul>'){ html = '<br /><span class="medium-text">No Notifications found!<br /><br /></span>'; } break; } var date = date_format(notifications[counter].date_created.substr(0, 10)); if(is_new != date){ html += '</ul>'; html += '<span class="medium-text">' + date + '</span><br />'; html += '<ul>'; is_new = date; } html += '<li class="normal-text">'; if(notifications[counter].is_new == 1){ html += '<span style="color: red;"> New! </span>&nbsp&nbsp'; } html += notifications[counter].message; html += '</li>'; } html += '</ul>'; $("#notification-list").html(html); } $("#paginator").paginate({ count: num_pages, start: default_page, display: 5, border: true, border_color: '#CD9F33', text_color: '#6F4632', background_color: '#FAF2E1', border_hover_color: '#B18110', text_hover_color: '#6F4632', background_hover_color: '#DCC388', images: false, mouse: 'press', onChange: function(page){ displayPage(page); positionPaginator(); replaceIdByName(); replaceIdByPic(); } }); function positionPaginator(){ var width = $('#notification-grid').width(); var length = num_pages > 5 ? 5 : num_pages; var actual = 60 + 60 + 25 * num_pages; $('#paginator').css('margin-left', (width - actual) / 2); } $(function(){ displayPage(default_page); positionPaginator(); });
JavaScript
var offer_curr_page = 1; var offers_per_page = 3; var offers_num_pages = Math.ceil(offers.length / offers_per_page); if(offers_num_pages == 0){ offers_num_pages = 1; } var request_curr_page = 1; var requests_per_page = 3; var requests_num_pages = Math.ceil(requests.length / requests_per_page); if(requests_num_pages == 0){ requests_num_pages = 1; } function editPageHeight(){ var tmp = (requests_num > offers_num) ? requests_num : offers_num; if (tmp < 1){ tmp = 1; } $("#requests-grid").height(120 + (tmp * 170)); $("#offers-grid").height(120 + (tmp * 170)); $("#requests-container").height((tmp * 170)); $("#offers-container").height((tmp * 170)); $("#vertical-bar").height(120 + (tmp * 170)); } function makeRequestsPaginator(){ $("#requests-paginator").paginate({ count: requests_num_pages, start: request_curr_page, display: 5, border: true, border_color: '#CD9F33', text_color: '#6F4632', background_color: '#FAF2E1', border_hover_color: '#B18110', text_hover_color: '#6F4632', background_hover_color: '#DCC388', images: false, mouse: 'press', onChange: function(page){ requestsDisplayPage(page); positionRequestsPaginator(); $(".resize-150").load(function(){ resize($(this), 150); }); editPageHeight(); requesttriggerTooltip(); replaceIdByName(); replaceIdByPic(); } }); } function requestsDisplayPage(page){ var html = ''; requests_num = 0; request_curr_page = page; for (var i = 0; i < requests_per_page; i++){ var counter = ((page - 1) * requests_per_page) + i; if (typeof(requests[counter]) == "undefined"){ if(html == ''){ html += '<br /><span class="medium-text">No requests found. <br /><br /><a href="browse/">Browse </a> for new items now!</span>'; } break; } requests_num++; html += '<div class="item-container">'; html += '<div class="img-container"><a href="itemdescription/' + requests[counter].offer_id + '"><img class="resize-150" src="resources/offer_images_thumbnail/' + requests[counter].item_pic + '" title="'+requests[counter].item_title+'"/></a></div>'; html += '<div class="cnt-container normal-text">'; html += '<span class="medium-text"><a href="itemdescription/'+ requests[counter].offer_id + '">' + requests[counter].item_title.substr(0, 20); if (requests[counter].item_title.length > 20){ html += '...'; } html += '</a></span><br />'; html += 'Status: ' + requests[counter].status + '<br />'; html += ' Owner: <span class="get-fb-name normal-text">' + requests[counter].owner + '</span><br /><br />'; html += '<div class="cancel-button"><a href="JavaScript:void(0);" onclick = "cancel_request('+ requests[counter].offer_id +',\''+requests[counter].status+'\')"></a></div>'; html += '<div class="request-trigger"><img src = "resources/frame/info.gif" width="30px" height="30px" /></div>'; html += '<div class="request-tooltip normal-text">'; html += '<span class="normal-text">' + requests[counter].item_title + '</span><br /><br />'; html += 'Category: '+ requests[counter].category_name + ' - ' + requests[counter].sub_category_name + '<br /><br />'; html += 'Description: ' + requests[counter].item_desc+'</div>'; html += '</div>'; html += '<div style="clear: both;"></div>'; html += '</div>'; html += '</div>'; } $("#requests-container").html(html); } function removeRequest(id){ for (var i = 0; i < requests.length; i++){ if(requests[i].offer_id == id){ requests.splice(i, 1); requests_num_pages = Math.ceil(requests.length / requests_per_page); if(requests_num_pages == 0){ requests_num_pages = 1; } while(request_curr_page > requests_num_pages){ request_curr_page--; } makeRequestsPaginator(); requestsDisplayPage(request_curr_page); positionRequestsPaginator(); $(".resize-150").load(function(){ resize($(this), 150); }); editPageHeight(); requesttriggerTooltip(); replaceIdByName(); replaceIdByPic(); break; } } } function positionRequestsPaginator(){ var width = $('#requests-container').width(); var length = requests_num_pages > 5 ? 5 : requests_num_pages; var actual = 60 + 60 + 25 * requests_num_pages; $('#requests-paginator').css('margin-left', (width - actual) / 2); } function makeOffersPaginator(){ $("#offers-paginator").paginate({ count: offers_num_pages, start: offer_curr_page, display: 5, border: true, border_color: '#CD9F33', text_color: '#6F4632', background_color: '#FAF2E1', border_hover_color: '#B18110', text_hover_color: '#6F4632', background_hover_color: '#DCC388', images: false, mouse: 'press', onChange: function(page){ offersDisplayPage(page); positionOffersPaginator(); $(".resize-150").load(function(){ resize($(this), 150); }); editPageHeight(); offertriggerTooltip(); replaceIdByName(); replaceIdByPic(); } }); } function offersDisplayPage(page){ var html = ''; offers_num = 0; offer_curr_page = page; for (var i = 0; i < offers_per_page; i++){ var counter = ((page - 1) * offers_per_page) + i; if (typeof(offers[counter]) == "undefined"){ if(html == ''){ html += '<br /><span class="medium-text">Do you have stuff hidden under your bed? <br /><br /><a href="offerform/0">Create </a> a new offer now!</span>'; } break; } offers_num++; html += '<div class="item-container">'; html += '<div class="img-container"><a href="itemdescription/' + offers[counter].offer_id + '"><img class="resize-150" src="resources/offer_images_thumbnail/' + offers[counter].item_pic + '" title="'+offers[counter].item_title+'"/></a></div>'; html += '<div class="cnt-container normal-text">'; html += '<span class="medium-text"><a href="itemdescription/'+ offers[counter].offer_id + '">' + offers[counter].item_title.substr(0, 20); if(offers[counter].item_title.length > 20){ html += '...'; } html += '</a></span><br />'; html += 'Status: ' + offers[counter].status + '<br />'; html += '<br /><br />'; html += '<div class="remove-button"><a href="JavaScript:void(0);" onclick = "cancel_offer('+ offers[counter].offer_id +',\''+offers[counter].status+'\')"></a></div>'; html += '<div class="offer-trigger"><img src = "resources/frame/info.gif" width="30px" height="30px" /></div>'; html += '<div class="offer-tooltip normal-text">'; html += '<span class="normal-text">' + offers[counter].item_title + '</span><br /><br />'; html += 'Category: '+ offers[counter].category_name + ' - ' + offers[counter].sub_category_name + '<br /><br />'; html += 'Description: ' + offers[counter].item_desc+'</div>'; html += '</div>'; html += '<div style="clear: both;"></div>'; html += '</div>'; html += '</div>'; } $("#offers-container").html(html); } function removeOffer(id){ for (var i = 0; i < offers.length; i++){ if(offers[i].offer_id == id){ offers.splice(i, 1); offers_num_pages = Math.ceil(offers.length / offers_per_page); if(offers_num_pages == 0){ offers_num_pages = 1; } while(offer_curr_page > offers_num_pages){ offer_curr_page--; } makeOffersPaginator(); offersDisplayPage(offer_curr_page); positionOffersPaginator(); $(".resize-150").load(function(){ resize($(this), 150); }); editPageHeight(); offertriggerTooltip(); replaceIdByName(); replaceIdByPic(); break; } } } function positionOffersPaginator(){ var width = $('#offers-container').width(); var length = offers_num_pages > 5 ? 5 : offers_num_pages; var actual = 60 + 60 + 25 * length; $('#offers-paginator').css('margin-left', (width - actual) / 2); } function offertriggerTooltip(){ $('.offer-trigger').tooltip({ effect: 'fade', position: 'bottom center', opacity: 0.90, tipClass: 'offer-tooltip', offset: [-180, -960], }); } function requesttriggerTooltip(){ $('.request-trigger').tooltip({ effect: 'fade', position: 'bottom center', opacity: 0.90, tipClass: 'request-tooltip', }); } $(function(){ makeRequestsPaginator(); makeOffersPaginator(); requestsDisplayPage(request_curr_page); offersDisplayPage(offer_curr_page); positionRequestsPaginator(); positionOffersPaginator(); editPageHeight(); offertriggerTooltip(); requesttriggerTooltip(); });
JavaScript
<script> alert('123'); </script>
JavaScript
/******************************************************************** * openWYSIWYG v1.47 Copyright (c) 2006 openWebWare.com * Contact us at devs@openwebware.com * This copyright notice MUST stay intact for use. * * $Id: wysiwyg.js,v 1.22 2007/09/08 21:45:57 xhaggi Exp $ * $Revision: 1.22 $ * * An open source WYSIWYG editor for use in web based applications. * For full source code and docs, visit http://www.openwebware.com * * This library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License along * with this library; if not, write to the Free Software Foundation, Inc., 59 * Temple Place, Suite 330, Boston, MA 02111-1307 USA ********************************************************************/ var WYSIWYG = { /** * Settings class, holds all customizeable properties */ Settings: function() { // Images Directory this.ImagesDir = "images/"; // Popups Directory this.PopupsDir = "popups/"; // CSS Directory File this.CSSFile = "styles/wysiwyg.css"; // Default WYSIWYG width and height (use px or %) this.Width = "500px"; this.Height = "200px"; // Default stylesheet of the WYSIWYG editor window this.DefaultStyle = "font-family: Arial; font-size: 12px; background-color: #FFFFFF"; // Stylesheet if editor is disabled this.DisabledStyle = "font-family: Arial; font-size: 12px; background-color: #EEEEEE"; // Width + Height of the preview window this.PreviewWidth = 500; this.PreviewHeight = 400; // Confirmation message if you strip any HTML added by word this.RemoveFormatConfMessage = "Clean HTML inserted by MS Word ?"; // Nofication if browser is not supported by openWYSIWYG, leave it blank for no message output. this.NoValidBrowserMessage = "openWYSIWYG does not support your browser."; // Anchor path to strip, leave it blank to ignore // or define auto to strip the path where the editor is placed // (only IE) this.AnchorPathToStrip = "auto"; // Image path to strip, leave it blank to ignore // or define auto to strip the path where the editor is placed // (only IE) this.ImagePathToStrip = "auto"; // Enable / Disable the custom context menu this.ContextMenu = true; // Enabled the status bar update. Within the status bar // node tree of the actually selected element will build this.StatusBarEnabled = true; // If enabled than the capability of the IE inserting line breaks will be inverted. // Normal: ENTER = <p> , SHIFT + ENTER = <br> // Inverted: ENTER = <br>, SHIFT + ENTER = <p> this.InvertIELineBreaks = false; // Replace line breaks with <br> tags this.ReplaceLineBreaks = false; // Page that opened the WYSIWYG (Used for the return command) this.Opener = "admin.asp"; // Insert image implementation this.ImagePopupFile = ""; this.ImagePopupWidth = 0; this.ImagePopupHeight = 0; // Holds the available buttons displayed // on the toolbar of the editor this.Toolbar = new Array(); this.Toolbar[0] = new Array( "font", "fontsize", "headings", "bold", "italic", "underline", "strikethrough", "seperator", "forecolor", "backcolor", "seperator", "justifyfull", "justifyleft", "justifycenter", "justifyright", "seperator", "unorderedlist", "orderedlist", "outdent", "indent" ); this.Toolbar[1] = new Array( "save", // "return", // return button disabled by default "seperator", "subscript", "superscript", "seperator", "cut", "copy", "paste", "removeformat", "seperator", "undo", "redo", "seperator", "inserttable", "insertimage", "createlink", "seperator", "preview", "print", "seperator", "viewSource", "maximize", "seperator", "help" ); // DropDowns this.DropDowns = new Array(); // Fonts this.DropDowns['font'] = { id: "fonts", command: "FontName", label: "<font style=\"font-family:{value};font-size:12px;\">{value}</font>", width: "90px", elements: new Array( "Arial", "Sans Serif", "Tahoma", "Verdana", "Courier New", "Georgia", "Times New Roman", "Impact", "Comic Sans MS" ) }; // Font sizes this.DropDowns['fontsize'] = { id: "fontsizes", command: "FontSize", label: "<font size=\"{value}\">Size {value}</font>", width: "54px", elements: new Array( "1", "2", "3", "4", "5", "6", "7" ) }; // Headings this.DropDowns['headings'] = { id: "headings", command: "FormatBlock", label: "<{value} style=\"margin:0px;text-decoration:none;font-family:Arial\">{value}</{value}>", width: "74px", elements: new Array( "H1", "H2", "H3", "H4", "H5", "H6" ) }; // Add the given element to the defined toolbar // on the defined position this.addToolbarElement = function(element, toolbar, position) { if(element != "seperator") {this.removeToolbarElement(element);} if(this.Toolbar[toolbar-1] == null) { this.Toolbar[toolbar-1] = new Array(); } this.Toolbar[toolbar-1].splice(position+1, 1, element); }; // Remove an element from the toolbar this.removeToolbarElement = function(element) { if(element == "seperator") {return;} // do not remove seperators for(var i=0;i<this.Toolbar.length;i++) { if(this.Toolbar[i]) { var toolbar = this.Toolbar[i]; for(var j=0;j<toolbar.length;j++) { if(toolbar[j] != null && toolbar[j] == element) { this.Toolbar[i].splice(j,1); } } } } }; // clear all or a given toolbar this.clearToolbar = function(toolbar) { if(typeof toolbar == "undefined") { this.Toolbar = new Array(); } else { this.Toolbar[toolbar+1] = new Array(); } }; }, /* ---------------------------------------------------------------------- *\ !! Do not change something below or you know what you are doning !! \* ---------------------------------------------------------------------- */ // List of available block formats (not in use) //BlockFormats: new Array("Address", "Bulleted List", "Definition", "Definition Term", "Directory List", "Formatted", "Heading 1", "Heading 2", "Heading 3", "Heading 4", "Heading 5", "Heading 6", "Menu List", "Normal", "Numbered List"), // List of available actions and their respective ID and images ToolbarList: { //Name buttonID buttonTitle buttonImage buttonImageRollover "bold": ['Bold', 'Bold', 'bold.gif', 'bold_on.gif'], "italic": ['Italic', 'Italic', 'italics.gif', 'italics_on.gif'], "underline": ['Underline', 'Underline', 'underline.gif', 'underline_on.gif'], "strikethrough": ['Strikethrough', 'Strikethrough', 'strikethrough.gif', 'strikethrough_on.gif'], "seperator": ['', '', 'seperator.gif', 'seperator.gif'], "subscript": ['Subscript', 'Subscript', 'subscript.gif', 'subscript_on.gif'], "superscript": ['Superscript', 'Superscript', 'superscript.gif', 'superscript_on.gif'], "justifyleft": ['Justifyleft', 'Justifyleft', 'justify_left.gif', 'justify_left_on.gif'], "justifycenter": ['Justifycenter', 'Justifycenter', 'justify_center.gif', 'justify_center_on.gif'], "justifyright": ['Justifyright', 'Justifyright', 'justify_right.gif', 'justify_right_on.gif'], "justifyfull": ['Justifyfull', 'Justifyfull', 'justify_justify.gif', 'justify_justify_on.gif'], "unorderedlist": ['InsertUnorderedList', 'Insert Unordered List', 'list_unordered.gif', 'list_unordered_on.gif'], "orderedlist": ['InsertOrderedList', 'Insert Ordered List', 'list_ordered.gif', 'list_ordered_on.gif'], "outdent": ['Outdent', 'Outdent', 'indent_left.gif', 'indent_left_on.gif'], "indent": ['Indent', 'Indent', 'indent_right.gif', 'indent_right_on.gif'], "cut": ['Cut', 'Cut', 'cut.gif', 'cut_on.gif'], "copy": ['Copy', 'Copy', 'copy.gif', 'copy_on.gif'], "paste": ['Paste', 'Paste', 'paste.gif', 'paste_on.gif'], "forecolor": ['ForeColor', 'Fore Color', 'forecolor.gif', 'forecolor_on.gif'], "backcolor": ['BackColor', 'Back Color', 'backcolor.gif', 'backcolor_on.gif'], "undo": ['Undo', 'Undo', 'undo.gif', 'undo_on.gif'], "redo": ['Redo', 'Redo', 'redo.gif', 'redo_on.gif'], "inserttable": ['InsertTable', 'Insert Table', 'insert_table.gif', 'insert_table_on.gif'], "insertimage": ['InsertImage', 'Insert Image', 'insert_picture.gif', 'insert_picture_on.gif'], "createlink": ['CreateLink', 'Create Link', 'insert_hyperlink.gif', 'insert_hyperlink_on.gif'], "viewSource": ['ViewSource', 'View Source', 'view_source.gif', 'view_source_on.gif'], "viewText": ['ViewText', 'View Text', 'view_text.gif', 'view_text_on.gif'], "help": ['Help', 'Help', 'help.gif', 'help_on.gif'], "fonts": ['Fonts', 'Select Font', 'select_font.gif', 'select_font_on.gif'], "fontsizes": ['Fontsizes', 'Select Size', 'select_size.gif', 'select_size_on.gif'], "headings": ['Headings', 'Select Size', 'select_heading.gif', 'select_heading_on.gif'], "preview": ['Preview', 'Preview', 'preview.gif', 'preview_on.gif'], "print": ['Print', 'Print', 'print.gif', 'print_on.gif'], "removeformat": ['RemoveFormat', 'Strip Word HTML', 'remove_format.gif', 'remove_format_on.gif'], "delete": ['Delete', 'Delete', 'delete.gif', 'delete_on.gif'], "save": ['Save', 'Save document', 'save.gif', 'save_on.gif'], "return": ['Return', 'Return without saving', 'return.gif', 'return_on.gif'], "maximize": ['Maximize', 'Maximize the editor', 'maximize.gif', 'maximize_on.gif'] }, // stores the different settings for each textarea // the textarea identifier is used to store the settings object config: new Array(), // Create viewTextMode global variable and set to 0 // enabling all toolbar commands while in HTML mode viewTextMode: new Array(), // maximized maximized: new Array(), /** * Get the range of the given selection * * @param {Selection} sel Selection object * @return {Range} Range object */ getRange: function(sel) { return sel.createRange ? sel.createRange() : sel.getRangeAt(0); }, /** * Return the editor div element * * @param {String} n Editor identifier * @return {HtmlDivElement} Iframe object */ getEditorDiv: function(n) { return $("wysiwyg_div_" + n); }, /** * Return the editor table element * * @param {String} n Editor identifier * @return {HtmlTableElement} Iframe object */ getEditorTable: function(n) { return $("wysiwyg_table_" + n); }, /** * Get the iframe object of the WYSIWYG editor * * @param {String} n Editor identifier * @return {HtmlIframeElement} Iframe object */ getEditor: function(n) { return $("wysiwyg" + n); }, /** * Get editors window element * * @param {String} n Editor identifier * @return {HtmlWindowElement} Html window object */ getEditorWindow: function(n) { return this.getEditor(n).contentWindow; }, /** * Attach the WYSIWYG editor to the given textarea element * * @param {String} id Textarea identifier (all = all textareas) * @param {Settings} settings the settings which will be applied to the textarea */ attach: function(id, settings) { if(id != "all") { this.setSettings(id, settings); WYSIWYG_Core.includeCSS(this.config[id].CSSFile); WYSIWYG_Core.addEvent(window, "load", function generateEditor() {WYSIWYG._generate(id, settings);}); } else { WYSIWYG_Core.addEvent(window, "load", function generateEditor() {WYSIWYG.attachAll(settings);}); } }, /** * Attach the WYSIWYG editor to all textarea elements * * @param {Settings} settings Settings to customize the look and feel */ attachAll: function(settings) { var areas = document.getElementsByTagName("textarea"); for(var i=0;i<areas.length;i++) { var id = areas[i].getAttribute("id"); if(id == null || id == "") continue; this.setSettings(id, settings); WYSIWYG_Core.includeCSS(this.config[id].CSSFile); WYSIWYG._generate(id, settings); } }, /** * Display an iframe instead of the textarea. * It's used as textarea replacement to display HTML. * * @param id Textarea identifier (all = all textareas) * @param settings the settings which will be applied to the textarea */ display: function(id, settings) { if(id != "all") { this.setSettings(id, settings); WYSIWYG_Core.includeCSS(this.config[id].CSSFile); WYSIWYG_Core.addEvent(window, "load", function displayIframe() {WYSIWYG._display(id, settings);}); } else { WYSIWYG_Core.addEvent(window, "load", function displayIframe() {WYSIWYG.displayAll(settings);}); } }, /** * Display an iframe instead of the textarea. * It's apply the iframe to all textareas found in the current document. * * @param settings Settings to customize the look and feel */ displayAll: function(settings) { var areas = document.getElementsByTagName("textarea"); for(var i=0;i<areas.length;i++) { var id = areas[i].getAttribute("id"); if(id == null || id == "") continue; this.setSettings(id, settings); WYSIWYG_Core.includeCSS(this.config[id].CSSFile); WYSIWYG._display(id, settings); } }, /** * Set settings in config array, use the textarea id as identifier * * @param n Textarea identifier (all = all textareas) * @param settings the settings which will be applied to the textarea */ setSettings: function(n, settings) { if(typeof(settings) != "object") { this.config[n] = new this.Settings(); } else { this.config[n] = settings; } }, /** * Insert or modify an image * * @param {String} src Source of the image * @param {Integer} width Width * @param {Integer} height Height * @param {String} align Alignment of the image * @param {String} border Border size * @param {String} alt Alternativ Text * @param {Integer} hspace Horizontal Space * @param {Integer} vspace Vertical Space * @param {String} n The editor identifier (the textarea's ID) */ insertImage: function(src, width, height, align, border, alt, hspace, vspace, n) { // get editor var doc = this.getEditorWindow(n).document; // get selection and range var sel = this.getSelection(n); var range = this.getRange(sel); // the current tag of range var img = this.findParent("img", range); // element is not a link var update = (img == null) ? false : true; if(!update) { img = doc.createElement("img"); } // set the attributes WYSIWYG_Core.setAttribute(img, "src", src); WYSIWYG_Core.setAttribute(img, "style", "width:" + width + ";height:" + height); if(align != "") { WYSIWYG_Core.setAttribute(img, "align", align); } else { img.removeAttribute("align"); } WYSIWYG_Core.setAttribute(img, "border", border); WYSIWYG_Core.setAttribute(img, "alt", alt); WYSIWYG_Core.setAttribute(img, "hspace", hspace); WYSIWYG_Core.setAttribute(img, "vspace", vspace); img.removeAttribute("width"); img.removeAttribute("height"); // on update exit here if(update) { return; } // Check if IE or Mozilla (other) if (WYSIWYG_Core.isMSIE) { range.pasteHTML(img.outerHTML); } else { this.insertNodeAtSelection(img, n); } }, /** * Insert or modify a link * * @param {String} href The url of the link * @param {String} target Target of the link * @param {String} style Stylesheet of the link * @param {String} styleClass Stylesheet class of the link * @param {String} name Name attribute of the link * @param {String} n The editor identifier (the textarea's ID) */ insertLink: function(href, target, style, styleClass, name, n) { // get editor var doc = this.getEditorWindow(n).document; // get selection and range var sel = this.getSelection(n); var range = this.getRange(sel); var lin = null; // get element from selection if(WYSIWYG_Core.isMSIE) { if(sel.type == "Control" && range.length == 1) { range = this.getTextRange(range(0)); range.select(); } } // find a as parent element lin = this.findParent("a", range); // check if parent is found var update = (lin == null) ? false : true; if(!update) { lin = doc.createElement("a"); } // set the attributes WYSIWYG_Core.setAttribute(lin, "href", href); WYSIWYG_Core.setAttribute(lin, "class", styleClass); WYSIWYG_Core.setAttribute(lin, "className", styleClass); WYSIWYG_Core.setAttribute(lin, "target", target); WYSIWYG_Core.setAttribute(lin, "name", name); WYSIWYG_Core.setAttribute(lin, "style", style); // on update exit here if(update) { return; } // Check if IE or Mozilla (other) if (WYSIWYG_Core.isMSIE) { range.select(); lin.innerHTML = range.htmlText; range.pasteHTML(lin.outerHTML); } else { var node = range.startContainer; var pos = range.startOffset; if(node.nodeType != 3) { node = node.childNodes[pos]; } if(node.tagName) lin.appendChild(node); else lin.innerHTML = sel; this.insertNodeAtSelection(lin, n); } }, /** * Strips any HTML added by word * * @param {String} n The editor identifier (the textarea's ID) */ removeFormat: function(n) { if ( !confirm(this.config[n].RemoveFormatConfMessage) ) { return; } var doc = this.getEditorWindow(n).document; var str = doc.body.innerHTML; str = str.replace(/<span([^>])*>(&nbsp;)*\s*<\/span>/gi, ''); str = str.replace(/<span[^>]*>/gi, ''); str = str.replace(/<\/span[^>]*>/gi, ''); str = str.replace(/<p([^>])*>(&nbsp;)*\s*<\/p>/gi, ''); str = str.replace(/<p[^>]*>/gi, ''); str = str.replace(/<\/p[^>]*>/gi, ''); str = str.replace(/<h([^>])[0-9]>(&nbsp;)*\s*<\/h>/gi, ''); str = str.replace(/<h[^>][0-9]>/gi, ''); str = str.replace(/<\/h[^>][0-9]>/gi, ''); str = str.replace (/<B [^>]*>/ig, '<b>'); // var repl_i1 = /<I[^>]*>/ig; // str = str.replace (repl_i1, '<i>'); str = str.replace (/<DIV[^>]*>/ig, ''); str = str.replace (/<\/DIV>/gi, ''); str = str.replace (/<[\/\w?]+:[^>]*>/ig, ''); str = str.replace (/(&nbsp;){2,}/ig, '&nbsp;'); str = str.replace (/<STRONG>/ig, ''); str = str.replace (/<\/STRONG>/ig, ''); str = str.replace (/<TT>/ig, ''); str = str.replace (/<\/TT>/ig, ''); str = str.replace (/<FONT [^>]*>/ig, ''); str = str.replace (/<\/FONT>/ig, ''); str = str.replace (/STYLE=\"[^\"]*\"/ig, ''); str = str.replace(/<([\w]+) class=([^ |>]*)([^>]*)/gi, '<$1$3'); str = str.replace(/<([\w]+) style="([^"]*)"([^>]*)/gi, '<$1$3'); str = str.replace(/width=([^ |>]*)([^>]*)/gi, ''); str = str.replace(/classname=([^ |>]*)([^>]*)/gi, ''); str = str.replace(/align=([^ |>]*)([^>]*)/gi, ''); str = str.replace(/valign=([^ |>]*)([^>]*)/gi, ''); str = str.replace(/<\\?\??xml[^>]>/gi, ''); str = str.replace(/<\/?\w+:[^>]*>/gi, ''); str = str.replace(/<st1:.*?>/gi, ''); str = str.replace(/o:/gi, ''); str = str.replace(/<!--([^>])*>(&nbsp;)*\s*<\/-->/gi, ''); str = str.replace(/<!--[^>]*>/gi, ''); str = str.replace(/<\/--[^>]*>/gi, ''); doc.body.innerHTML = str; }, /** * Display an iframe instead of the textarea. * * @private * @param {String} n The editor identifier (the textarea's ID) * @param {Object} settings Object which holds the settings */ _display: function(n, settings) { // Get the textarea element var textarea = $(n); // Validate if textarea exists if(textarea == null) { alert("No textarea found with the given identifier (ID: " + n + ")."); return; } // Validate browser compatiblity if(!WYSIWYG_Core.isBrowserCompatible()) { if(this.config[n].NoValidBrowserMessage != "") { alert(this.config[n].NoValidBrowserMessage); } return; } // Load settings in config array, use the textarea id as identifier if(typeof(settings) != "object") { this.config[n] = new this.Settings(); } else { this.config[n] = settings; } // Hide the textarea textarea.style.display = "none"; // Override the width and height of the editor with the // size given by the style attributes width and height if(textarea.style.width) { this.config[n].Width = textarea.style.width; } if(textarea.style.height) { this.config[n].Height = textarea.style.height } // determine the width + height var currentWidth = this.config[n].Width; var currentHeight = this.config[n].Height; // Calculate the width + height of the editor var ifrmWidth = "100%"; var ifrmHeight = "100%"; if(currentWidth.search(/%/) == -1) { ifrmWidth = currentWidth; ifrmHeight = currentHeight; } // Create iframe which will be used for rich text editing var iframe = '<table cellpadding="0" cellspacing="0" border="0" style="width:' + currentWidth + '; height:' + currentHeight + ';" class="tableTextareaEditor"><tr><td valign="top">\n' + '<iframe frameborder="0" id="wysiwyg' + n + '" class="iframeText" style="width:' + ifrmWidth + ';height:' + ifrmHeight + ';"></iframe>\n' + '</td></tr></table>\n'; // Insert after the textArea both toolbar one and two textarea.insertAdjacentHTML("afterEnd", iframe); // Pass the textarea's existing text over to the content variable var content = textarea.value; var doc = this.getEditorWindow(n).document; // Replace all \n with <br> if(this.config[n].ReplaceLineBreaks) { content = content.replace(/(\r\n)|(\n)/ig, "<br>"); } // Write the textarea's content into the iframe doc.open(); doc.write(content); doc.close(); // Set default style of the editor window WYSIWYG_Core.setAttribute(doc.body, "style", this.config[n].DefaultStyle); }, /** * Replace the given textarea with wysiwyg editor * * @private * @param {String} n The editor identifier (the textarea's ID) * @param {Object} settings Object which holds the settings */ _generate: function(n, settings) { // Get the textarea element var textarea = $(n); // Validate if textarea exists if(textarea == null) { alert("No textarea found with the given identifier (ID: " + n + ")."); return; } // Validate browser compatiblity if(!WYSIWYG_Core.isBrowserCompatible()) { if(this.config[n].NoValidBrowserMessage != "") { alert(this.config[n].NoValidBrowserMessage); } return; } // Hide the textarea textarea.style.display = 'none'; // Override the width and height of the editor with the // size given by the style attributes width and height if(textarea.style.width) { this.config[n].Width = textarea.style.width; } if(textarea.style.height) { this.config[n].Height = textarea.style.height } // determine the width + height var currentWidth = this.config[n].Width; var currentHeight = this.config[n].Height; // Calculate the width + height of the editor var toolbarWidth = currentWidth; var ifrmWidth = "100%"; var ifrmHeight = "100%"; if(currentWidth.search(/%/) == -1) { toolbarWidth = currentWidth.replace(/px/gi, ""); toolbarWidth = (parseFloat(toolbarWidth) + 2) + "px"; ifrmWidth = currentWidth; ifrmHeight = currentHeight; } // Generate the WYSIWYG Table // This table holds the toolbars and the iframe as the editor var editor = ""; editor += '<div id="wysiwyg_div_' + n + '" style="width:' + currentWidth +';">'; editor += '<table border="0" cellpadding="0" cellspacing="0" class="tableTextareaEditor" id="wysiwyg_table_' + n + '" style="width:' + currentWidth + '; height:' + currentHeight + ';">'; editor += '<tr><td style="height:22px;vertical-align:top;">'; // Output all command buttons that belong to toolbar one for (var j = 0; j < this.config[n].Toolbar.length;j++) { if(this.config[n].Toolbar[j] && this.config[n].Toolbar[j].length > 0) { var toolbar = this.config[n].Toolbar[j]; // Generate WYSIWYG toolbar one editor += '<table border="0" cellpadding="0" cellspacing="0" class="toolbar1" style="width:100%;" id="toolbar' + j + '_' + n + '">'; editor += '<tr><td style="width:6px;"><img src="' + this.config[n].ImagesDir + 'seperator2.gif" alt="" hspace="3"></td>'; // Interate over the toolbar element for (var i = 0; i < toolbar.length;i++) { var id = toolbar[i]; if (toolbar[i]) { if(typeof (this.config[n].DropDowns[id]) != "undefined") { var dropdown = this.config[n].DropDowns[id]; editor += '<td style="width: ' + dropdown.width + ';">'; // write the drop down content editor += this.writeDropDown(n, id); editor += '</td>'; } else { // Get the values of the Button from the global ToolbarList object var buttonObj = this.ToolbarList[toolbar[i]]; if(buttonObj) { var buttonID = buttonObj[0]; var buttonTitle = buttonObj[1]; var buttonImage = this.config[n].ImagesDir + buttonObj[2]; var buttonImageRollover = this.config[n].ImagesDir + buttonObj[3]; if (toolbar[i] == "seperator") { editor += '<td style="width: 12px;" align="center">'; editor += '<img src="' + buttonImage + '" border=0 unselectable="on" width="2" height="18" hspace="2" unselectable="on">'; editor += '</td>'; } // View Source button else if (toolbar[i] == "viewSource"){ editor += '<td style="width: 22px;">'; editor += '<span id="HTMLMode' + n + '"><img src="' + buttonImage + '" border="0" unselectable="on" title="' + buttonTitle + '" id="' + buttonID + '" class="buttonEditor" onmouseover="this.className=\'buttonEditorOver\'; this.src=\'' + buttonImageRollover + '\';" onmouseout="this.className=\'buttonEditor\'; this.src=\'' + buttonImage + '\';" onclick="WYSIWYG.execCommand(\'' + n + '\', \'' + buttonID + '\');" unselectable="on" width="20" height="20"></span>'; editor += '<span id="textMode' + n + '"><img src="' + this.config[n].ImagesDir + 'view_text.gif" border="0" unselectable="on" title="viewText" id="ViewText" class="buttonEditor" onmouseover="this.className=\'buttonEditorOver\'; this.src=\'' + this.config[n].ImagesDir + 'view_text_on.gif\';" onmouseout="this.className=\'buttonEditor\'; this.src=\'' + this.config[n].ImagesDir + 'view_text.gif\';" onclick="WYSIWYG.execCommand(\'' + n + '\',\'ViewText\');" unselectable="on" width="20" height="20"></span>'; editor += '</td>'; } else { editor += '<td style="width: 22px;">'; editor += '<img src="' + buttonImage + '" border=0 unselectable="on" title="' + buttonTitle + '" id="' + buttonID + '" class="buttonEditor" onmouseover="this.className=\'buttonEditorOver\'; this.src=\'' + buttonImageRollover + '\';" onmouseout="this.className=\'buttonEditor\'; this.src=\'' + buttonImage + '\';" onclick="WYSIWYG.execCommand(\'' + n + '\', \'' + buttonID + '\');" unselectable="on" width="20" height="20">'; editor += '</td>'; } } } } } editor += '<td>&nbsp;</td></tr></table>'; } } editor += '</td></tr><tr><td valign="top">\n'; // Create iframe which will be used for rich text editing editor += '<iframe frameborder="0" id="wysiwyg' + n + '" class="iframeText" style="width:100%;height:' + currentHeight + ';"></iframe>\n' + '</td></tr>'; // Status bar HTML code if(this.config[n].StatusBarEnabled) { editor += '<tr><td class="wysiwyg-statusbar" style="height:10px;" id="wysiwyg_statusbar_' + n + '">&nbsp;</td></tr>'; } editor += '</table>'; editor += '</div>'; // Insert the editor after the textarea textarea.insertAdjacentHTML("afterEnd", editor); // Hide the "Text Mode" button // Validate if textMode Elements are prensent if($("textMode" + n)) { $("textMode" + n).style.display = 'none'; } // Pass the textarea's existing text over to the content variable var content = textarea.value; var doc = this.getEditorWindow(n).document; // Replace all \n with <br> if(this.config[n].ReplaceLineBreaks) { content = content.replace(/\n\r|\n/ig, "<br>"); } // Write the textarea's content into the iframe doc.open(); doc.write(content); doc.close(); // Make the iframe editable in both Mozilla and IE // Improve compatiblity for IE + Mozilla if (doc.body.contentEditable) { doc.body.contentEditable = true; } else { doc.designMode = "on"; } // Set default font style WYSIWYG_Core.setAttribute(doc.body, "style", this.config[n].DefaultStyle); // Enable table highlighting WYSIWYG_Table.refreshHighlighting(n); // Event Handling // Update the textarea with content in WYSIWYG when user submits form for (var idx=0; idx < document.forms.length; idx++) { WYSIWYG_Core.addEvent(document.forms[idx], "submit", function xxx_aa() { WYSIWYG.updateTextArea(n); }); } // close font selection if mouse moves over the editor window WYSIWYG_Core.addEvent(doc, "mouseover", function xxx_bb() { WYSIWYG.closeDropDowns(n);}); // If it's true invert the line break capability of IE if(this.config[n].InvertIELineBreaks) { WYSIWYG_Core.addEvent(doc, "keypress", function xxx_cc() { WYSIWYG.invertIELineBreakCapability(n); }); } // status bar update if(this.config[n].StatusBarEnabled) { WYSIWYG_Core.addEvent(doc, "mouseup", function xxx_dd() { WYSIWYG.updateStatusBar(n); }); } // custom context menu if(this.config[n].ContextMenu) { WYSIWYG_ContextMenu.init(n); } // init viewTextMode var this.viewTextMode[n] = false; }, /** * Disable the given WYSIWYG Editor Box * * @param {String} n The editor identifier (the textarea's ID) */ disable: function(n) { // get the editor window var editor = this.getEditorWindow(n); // Validate if editor exists if(editor == null) { alert("No editor found with the given identifier (ID: " + n + ")."); return; } if(editor) { // disable design mode or content editable feature if(editor.document.body.contentEditable) { editor.document.body.contentEditable = false; } else { editor.document.designMode = "Off"; } // change the style of the body WYSIWYG_Core.setAttribute(editor.document.body, "style", this.config[n].DisabledStyle); // hide the status bar this.hideStatusBar(n); // hide all toolbars this.hideToolbars(n); } }, /** * Enables the given WYSIWYG Editor Box * * @param {String} n The editor identifier (the textarea's ID) */ enable: function(n) { // get the editor window var editor = this.getEditorWindow(n); // Validate if editor exists if(editor == null) { alert("No editor found with the given identifier (ID: " + n + ")."); return; } if(editor) { // disable design mode or content editable feature if(editor.document.body.contentEditable){ editor.document.body.contentEditable = true; } else { editor.document.designMode = "On"; } // change the style of the body WYSIWYG_Core.setAttribute(editor.document.body, "style", this.config[n].DefaultStyle); // hide the status bar this.showStatusBar(n); // hide all toolbars this.showToolbars(n); } }, /** * Returns the node structure of the current selection as array * * @param {String} n The editor identifier (the textarea's ID) */ getNodeTree: function(n) { var sel = this.getSelection(n); var range = this.getRange(sel); // get element of range var tag = this.getTag(range); if(tag == null) { return; } // get parent of element var node = this.getParent(tag); // init the tree as array with the current selected element var nodeTree = new Array(tag); // get all parent nodes var ii = 1; while(node != null && node.nodeName != "#document") { nodeTree[ii] = node; node = this.getParent(node); ii++; } return nodeTree; }, /** * Removes the current node of the selection * * @param {String} n The editor identifier (the textarea's ID) */ removeNode: function(n) { // get selection and range var sel = this.getSelection(n); var range = this.getRange(sel); // the current tag of range var tag = this.getTag(range); var parent = tag.parentNode; if(tag == null || parent == null) { return; } if(tag.nodeName == "HTML" || tag.nodeName == "BODY") { return; } // copy child elements of the node to the parent element before remove the node var childNodes = new Array(); for(var i=0; i < tag.childNodes.length;i++) childNodes[i] = tag.childNodes[i]; for(var i=0; i < childNodes.length;i++) parent.insertBefore(childNodes[i], tag); // remove node parent.removeChild(tag); // validate if parent is a link and the node is only // surrounded by the link, then remove the link too if(parent.nodeName == "A" && !parent.hasChildNodes()) { if(parent.parentNode) { parent.parentNode.removeChild(parent); } } // update the status bar this.updateStatusBar(n); }, /** * Get the selection of the given editor * * @param {String} n The editor identifier (the textarea's ID) */ getSelection: function(n) { var ifrm = this.getEditorWindow(n); var doc = ifrm.document; var sel = null; if(ifrm.getSelection){ sel = ifrm.getSelection(); } else if (doc.getSelection) { sel = doc.getSelection(); } else if (doc.selection) { sel = doc.selection; } return sel; }, /** * Updates the status bar with the current node tree * * @param {String} n The editor identifier (the textarea's ID) */ updateStatusBar: function(n) { // get the node structure var nodeTree = this.getNodeTree(n); if(nodeTree == null) { return; } // format the output var outputTree = ""; var max = nodeTree.length - 1; for(var i=max;i>=0;i--) { if(nodeTree[i].nodeName != "HTML" && nodeTree[i].nodeName != "BODY") { outputTree += '<a class="wysiwyg-statusbar" href="javascript:WYSIWYG.selectNode(\'' + n + '\',' + i + ');">' + nodeTree[i].nodeName + '</a>'; } else { outputTree += nodeTree[i].nodeName; } if(i > 0) { outputTree += " > "; } } // update the status bar var statusbar = $("wysiwyg_statusbar_" + n); if(statusbar){ statusbar.innerHTML = outputTree; } }, /** * Execute a command on the editor document * * @param {String} command The execCommand (e.g. Bold) * @param {String} n The editor identifier * @param {String} value The value when applicable */ execCommand: function(n, cmd, value) { // When user clicks toolbar button make sure it always targets its respective WYSIWYG this.getEditorWindow(n).focus(); // When in Text Mode these execCommands are enabled var textModeCommands = new Array("ViewText", "Print"); // Check if in Text mode and a disabled command execute var cmdValid = false; for (var i = 0; i < textModeCommands.length; i++) { if (textModeCommands[i] == cmd) { cmdValid = true; } } if(this.viewTextMode[n] && !cmdValid) { alert("You are in TEXT Mode. This feature has been disabled."); return; } // rbg to hex convertion implementation dependents on browser var toHexColor = WYSIWYG_Core.isMSIE ? WYSIWYG_Core._dec_to_rgb : WYSIWYG_Core.toHexColor; // popup screen positions var popupPosition = {left: parseInt(window.screen.availWidth / 3), top: parseInt(window.screen.availHeight / 3)}; // Check the insert image popup implementation var imagePopupFile = this.config[n].PopupsDir + 'insert_image.html'; var imagePopupWidth = 400; var imagePopupHeight = 210; if(typeof this.config[n].ImagePopupFile != "undefined" && this.config[n].ImagePopupFile != "") { imagePopupFile = this.config[n].ImagePopupFile; } if(typeof this.config[n].ImagePopupWidth && this.config[n].ImagePopupWidth > 0) { imagePopupWidth = this.config[n].ImagePopupWidth; } if(typeof this.config[n].ImagePopupHeight && this.config[n].ImagePopupHeight > 0) { imagePopupHeight = this.config[n].ImagePopupHeight; } // switch which action have to do switch(cmd) { case "Maximize": this.maximize(n); break; case "FormatBlock": WYSIWYG_Core.execCommand(n, cmd, "<" + value + ">"); break; // ForeColor and case "ForeColor": var rgb = this.getEditorWindow(n).document.queryCommandValue(cmd); var currentColor = rgb != '' ? toHexColor(this.getEditorWindow(n).document.queryCommandValue(cmd)) : "000000"; window.open(this.config[n].PopupsDir + 'select_color.html?color=' + currentColor + '&command=' + cmd + '&wysiwyg=' + n, 'popup', 'location=0,status=0,scrollbars=0,width=210,height=165,top=' + popupPosition.top + ',left=' + popupPosition.left).focus(); break; // BackColor case "BackColor": var currentColor = toHexColor(this.getEditorWindow(n).document.queryCommandValue(cmd)); window.open(this.config[n].PopupsDir + 'select_color.html?color=' + currentColor + '&command=' + cmd + '&wysiwyg=' + n, 'popup', 'location=0,status=0,scrollbars=0,width=210,height=165,top=' + popupPosition.top + ',left=' + popupPosition.left).focus(); break; // InsertImage case "InsertImage": window.open(imagePopupFile + '?wysiwyg=' + n, 'popup', 'location=0,status=0,scrollbars=0,resizable=0,width=' + imagePopupWidth + ',height=' + imagePopupHeight + ',top=' + popupPosition.top + ',left=' + popupPosition.left).focus(); break; // Remove Image case "RemoveImage": this.removeImage(n); break; // Remove Link case "RemoveLink": this.removeLink(n); break; // Remove a Node case "RemoveNode": this.removeNode(n); break; // Create Link case "CreateLink": window.open(this.config[n].PopupsDir + 'insert_hyperlink.html?wysiwyg=' + n, 'popup', 'location=0,status=0,scrollbars=0,resizable=0,width=350,height=160,top=' + popupPosition.top + ',left=' + popupPosition.left).focus(); break; // InsertTable case "InsertTable": window.open(this.config[n].PopupsDir + 'create_table.html?wysiwyg=' + n, 'popup', 'location=0,status=0,scrollbars=0,resizable=0,width=500,height=260,top=' + popupPosition.top + ',left=' + popupPosition.left).focus(); break; // ViewSource case "ViewSource": this.viewSource(n); break; // ViewText case "ViewText": this.viewText(n); break; // Help case "Help": window.open(this.config[n].PopupsDir + 'about.html?wysiwyg=' + n, 'popup', 'location=0,status=0,scrollbars=0,resizable=0,width=400,height=350,top=' + popupPosition.top + ',left=' + popupPosition.left).focus(); break; // Strip any HTML added by word case "RemoveFormat": this.removeFormat(n); break; // Preview thx to Korvo case "Preview": window.open(this.config[n].PopupsDir + 'preview.html?wysiwyg=' + n,'popup', 'location=0,status=0,scrollbars=1,resizable=1,width=' + this.config[n].PreviewWidth + ',height=' + this.config[n].PreviewHeight + ',top=' + popupPosition.top + ',left=' + popupPosition.left).focus(); break; // Print case "Print": this.print(n); break; // Save case "Save": WYSIWYG.updateTextArea(n); var form = WYSIWYG_Core.findParentNode("FORM", this.getEditor(n)); if(form == null) { alert("Can not submit the content, because no form element found."); return; } form.submit(); break; // Return case "Return": location.replace(this.config[n].Opener); break; default: WYSIWYG_Core.execCommand(n, cmd, value); } // hide node the font + font size selection this.closeDropDowns(n); }, /** * Maximize the editor instance * * @param {String} n The editor identifier */ maximize: function(n) { var divElm = this.getEditorDiv(n); var tableElm = this.getEditorTable(n); var editor = this.getEditor(n); var setting = this.config[n]; var size = WYSIWYG_Core.windowSize(); size.width -= 5; if(this.maximized[n]) { WYSIWYG_Core.setAttribute(divElm, "style", "position:static;z-index:9998;top:0px;left:0px;width:" + setting.Width + ";height:100%;"); WYSIWYG_Core.setAttribute(tableElm, "style", "width:" + setting.Width + ";height:" + setting.Height + ";"); WYSIWYG_Core.setAttribute(editor, "style", "width:100%;height:" + setting.Height + ";"); this.maximized[n] = false; } else { WYSIWYG_Core.setAttribute(divElm, "style", "position:absolute;z-index:9998;top:0px;left:0px;width:" + size.width + "px;height:" + size.height + "px;"); WYSIWYG_Core.setAttribute(tableElm, "style", "width:100%;height:100%;"); WYSIWYG_Core.setAttribute(editor, "style", "width:100%;height:100%;"); this.maximized[n] = true; } }, /** * Insert HTML into WYSIWYG in rich text * * @param {String} html The HTML being inserted (e.g. <b>hello</b>) * @param {String} n The editor identifier */ insertHTML: function(html, n) { if (WYSIWYG_Core.isMSIE) { this.getEditorWindow(n).document.selection.createRange().pasteHTML(html); } else { var span = this.getEditorWindow(n).document.createElement("span"); span.innerHTML = html; this.insertNodeAtSelection(span, n); } }, /* ---------------------------------------------------------------------- *\ Function : insertNodeAtSelection() Description : insert HTML into WYSIWYG in rich text (mozilla) Usage : WYSIWYG.insertNodeAtSelection(insertNode, n) Arguments : insertNode - The HTML being inserted (must be innerHTML inserted within a div element) n - The editor identifier that the HTML will be inserted into (the textarea's ID) \* ---------------------------------------------------------------------- */ insertNodeAtSelection: function(insertNode, n) { // get editor document var doc = this.getEditorWindow(n).document; // get current selection var sel = this.getSelection(n); // get the first range of the selection // (there's almost always only one range) var range = sel.getRangeAt(0); // deselect everything sel.removeAllRanges(); // remove content of current selection from document range.deleteContents(); // get location of current selection var container = range.startContainer; var pos = range.startOffset; // make a new range for the new selection range = doc.createRange(); if (container.nodeType==3 && insertNode.nodeType==3) { // if we insert text in a textnode, do optimized insertion container.insertData(pos, insertNode.data); // put cursor after inserted text range.setEnd(container, pos+insertNode.length); range.setStart(container, pos+insertNode.length); } else { var afterNode; var beforeNode; if (container.nodeType==3) { // when inserting into a textnode // we create 2 new textnodes // and put the insertNode in between var textNode = container; container = textNode.parentNode; var text = textNode.nodeValue; // text before the split var textBefore = text.substr(0,pos); // text after the split var textAfter = text.substr(pos); beforeNode = document.createTextNode(textBefore); afterNode = document.createTextNode(textAfter); // insert the 3 new nodes before the old one container.insertBefore(afterNode, textNode); container.insertBefore(insertNode, afterNode); container.insertBefore(beforeNode, insertNode); // remove the old node container.removeChild(textNode); } else { // else simply insert the node afterNode = container.childNodes[pos]; container.insertBefore(insertNode, afterNode); } try { range.setEnd(afterNode, 0); range.setStart(afterNode, 0); } catch(e) { alert(e); } } sel.addRange(range); }, /** * Prints the content of the WYSIWYG editor area * * @param {String} n The editor identifier (textarea ID) */ print: function(n) { if(document.all && navigator.appVersion.substring(22,23)==4) { var doc = this.getEditorWindow(n).document; doc.focus(); var OLECMDID_PRINT = 6; var OLECMDEXECOPT_DONTPROMPTUSER = 2; var OLECMDEXECOPT_PROMPTUSER = 1; var WebBrowser = '<object id="WebBrowser1" width="0" height="0" classid="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></object>'; doc.body.insertAdjacentHTML('beforeEnd',WebBrowser); WebBrowser.ExecWB(OLECMDID_PRINT, OLECMDEXECOPT_DONTPROMPTUSER); WebBrowser.outerHTML = ''; } else { this.getEditorWindow(n).print(); } }, /** * Writes the content of an drop down * * @param {String} n The editor identifier (textarea ID) * @param {String} id Drop down identifier * @return {String} Drop down HTML */ writeDropDown: function(n, id) { var dropdown = this.config[n].DropDowns[id]; var toolbarObj = this.ToolbarList[dropdown.id]; var image = this.config[n].ImagesDir + toolbarObj[2]; var imageOn = this.config[n].ImagesDir + toolbarObj[3]; dropdown.elements.sort(); var output = ""; output += '<table border="0" cellpadding="0" cellspacing="0"><tr>'; output += '<td onMouseOver="$(\'img_' + dropdown.id + '_' + n + '\').src=\'' + imageOn + '\';" onMouseOut="$(\'img_' + dropdown.id + '_' + n + '\').src=\'' + image + '\';">'; output += '<img src="' + image + '" id="img_' + dropdown.id + '_' + n + '" height="20" onClick="WYSIWYG.openDropDown(\'' + n + '\',\'' + dropdown.id + '\');" unselectable="on" border="0"><br>'; output += '<span id="elm_' + dropdown.id + '_' + n + '" class="dropdown" style="width: 145px;display:none;">'; for (var i = 0; i < dropdown.elements.length;i++) { if (dropdown.elements[i]) { var value = dropdown.elements[i]; var label = dropdown.label.replace(/{value}/gi, value); // output output += '<button type="button" onClick="WYSIWYG.execCommand(\'' + n + '\',\'' + dropdown.command + '\',\'' + value + '\')\;" onMouseOver="this.className=\'mouseOver\'" onMouseOut="this.className=\'mouseOut\'" class="mouseOut" style="width: 120px;">'; output += '<table cellpadding="0" cellspacing="0" border="0"><tr>'; output += '<td align="left">' + label + '</td>'; output += '</tr></table></button><br>'; } } output += '</span></td></tr></table>'; return output; }, /** * Close all drop downs. You can define a exclude dropdown id * * @param {String} n The editor identifier (textarea ID) * @param {String} exid Excluded drop down identifier */ closeDropDowns: function(n, exid) { if(typeof(exid) == "undefined") exid = ""; var dropdowns = this.config[n].DropDowns; for(var id in dropdowns) { var dropdown = dropdowns[id]; if(dropdown.id != exid) { var divId = "elm_" + dropdown.id + "_" + n; if($(divId)) $(divId).style.display = 'none'; } } }, /** * Open a defined drop down * * @param {String} n The editor identifier (textarea ID) * @param {String} id Drop down identifier */ openDropDown: function(n, id) { var divId = "elm_" + id + "_" + n; if($(divId).style.display == "none") { $(divId).style.display = "block"; } else { $(divId).style.display = "none"; } $(divId).style.position = "absolute"; this.closeDropDowns(n, id); }, /** * Shows the HTML source code generated by the WYSIWYG editor * * @param {String} n The editor identifier (textarea ID) */ viewSource: function(n) { // document var doc = this.getEditorWindow(n).document; // Enable table highlighting WYSIWYG_Table.disableHighlighting(n); // View Source for IE if (WYSIWYG_Core.isMSIE) { var iHTML = doc.body.innerHTML; // strip off the absolute urls iHTML = this.stripURLPath(n, iHTML); // replace all decimal color strings with hex decimal color strings iHTML = WYSIWYG_Core.replaceRGBWithHexColor(iHTML); doc.body.innerText = iHTML; } // View Source for Mozilla/Netscape else { // replace all decimal color strings with hex decimal color strings var html = WYSIWYG_Core.replaceRGBWithHexColor(doc.body.innerHTML); html = document.createTextNode(html); doc.body.innerHTML = ""; doc.body.appendChild(html); } // Hide the HTML Mode button and show the Text Mode button // Validate if Elements are present if($('HTMLMode' + n)) { $('HTMLMode' + n).style.display = 'none'; } if($('textMode' + n)) { $('textMode' + n).style.display = 'block'; } // set the font values for displaying HTML source doc.body.style.fontSize = "12px"; doc.body.style.fontFamily = "Courier New"; this.viewTextMode[n] = true; }, /** * Shows the HTML source code generated by the WYSIWYG editor * * @param {String} n The editor identifier (textarea ID) */ viewText: function(n) { // get document var doc = this.getEditorWindow(n).document; // View Text for IE if (WYSIWYG_Core.isMSIE) { var iText = doc.body.innerText; // strip off the absolute urls iText = this.stripURLPath(n, iText); // replace all decimal color strings with hex decimal color strings iText = WYSIWYG_Core.replaceRGBWithHexColor(iText); doc.body.innerHTML = iText; } // View Text for Mozilla/Netscape else { var html = doc.body.ownerDocument.createRange(); html.selectNodeContents(doc.body); // replace all decimal color strings with hex decimal color strings html = WYSIWYG_Core.replaceRGBWithHexColor(html.toString()); doc.body.innerHTML = html; } // Enable table highlighting WYSIWYG_Table.refreshHighlighting(n); // Hide the Text Mode button and show the HTML Mode button // Validate if Elements are present if($('textMode' + n)) { $('textMode' + n).style.display = 'none'; } if($('HTMLMode' + n)) { $('HTMLMode' + n).style.display = 'block'; } // reset the font values (changed) WYSIWYG_Core.setAttribute(doc.body, "style", this.config[n].DefaultStyle); this.viewTextMode[n] = false; }, /* ---------------------------------------------------------------------- *\ Function : stripURLPath() Description : Strips off the defined image and the anchor urls of the given content. It also can strip the document URL automatically if you define auto. Usage : WYSIWYG.stripURLPath(content) Arguments : content - Content on which the stripping applies \* ---------------------------------------------------------------------- */ stripURLPath: function(n, content, exact) { // parameter exact is optional if(typeof exact == "undefined") { exact = true; } var stripImgageUrl = null; var stripAnchorUrl = null; // add url to strip of anchors to array if(this.config[n].AnchorPathToStrip == "auto") { stripAnchorUrl = WYSIWYG_Core.getDocumentUrl(document); } else if(this.config[n].AnchorPathToStrip != "") { stripAnchorUrl = this.config[n].AnchorPathToStrip; } // add strip url of images to array if(this.config[n].ImagePathToStrip == "auto") { stripImgageUrl = WYSIWYG_Core.getDocumentUrl(document); } else if(this.config[n].ImagePathToStrip != "") { stripImgageUrl = this.config[n].ImagePathToStrip; } var url; var regex; var result; // strip url of image path if(stripImgageUrl) { // escape reserved characters to be a valid regex url = WYSIWYG_Core.stringToRegex(WYSIWYG_Core.getDocumentPathOfUrl(stripImgageUrl)); // exact replacing of url. regex: src="<url>" if(exact) { regex = eval("/(src=\")(" + url + ")([^\"]*)/gi"); content = content.replace(regex, "$1$3"); } // not exect replacing of url. regex: <url> else { regex = eval("/(" + url + ")(.+)/gi"); content = content.replace(regex, "$2"); } // strip absolute urls without a heading slash ("images/print.gif") result = WYSIWYG_Core.getDocumentPathOfUrl(stripImgageUrl).match(/.+[\/]{2,3}[^\/]*/,""); if(result) { url = WYSIWYG_Core.stringToRegex(result[0]); // exact replacing of url. regex: src="<url>" if(exact) { regex = eval("/(src=\")(" + url + ")([^\"]*)/gi"); content = content.replace(regex, "$1$3"); } // not exect replacing of url. regex: <url> else { regex = eval("/(" + url + ")(.+)/gi"); content = content.replace(regex, "$2"); } } } // strip url of image path if(stripAnchorUrl) { // escape reserved characters to be a valid regex url = WYSIWYG_Core.stringToRegex(WYSIWYG_Core.getDocumentPathOfUrl(stripAnchorUrl)); // strip absolute urls with a heading slash ("/product/index.html") // exact replacing of url. regex: src="<url>" if(exact) { regex = eval("/(href=\")(" + url + ")([^\"]*)/gi"); content = content.replace(regex, "$1$3"); } // not exect replacing of url. regex: <url> else { regex = eval("/(" + url + ")(.+)/gi"); content = content.replace(regex, "$2"); } // strip absolute urls without a heading slash ("product/index.html") result = WYSIWYG_Core.getDocumentPathOfUrl(stripAnchorUrl).match(/.+[\/]{2,3}[^\/]*/,""); if(result) { url = WYSIWYG_Core.stringToRegex(result[0]); // exact replacing of url. regex: src="<url>" if(exact) { regex = eval("/(href=\")(" + url + ")([^\"]*)/gi"); content = content.replace(regex, "$1$3"); } // not exect replacing of url. regex: <url> else { regex = eval("/(" + url + ")(.+)/gi"); content = content.replace(regex, "$2"); } } // stip off anchor links with #name url = WYSIWYG_Core.stringToRegex(stripAnchorUrl); // exact replacing of url. regex: src="<url>" if(exact) { regex = eval("/(href=\")(" + url + ")(#[^\"]*)/gi"); content = content.replace(regex, "$1$3"); } // not exect replacing of url. regex: <url> else { regex = eval("/(" + url + ")(.+)/gi"); content = content.replace(regex, "$2"); } // stip off anchor links with #name (only for local system) url = WYSIWYG_Core.getDocumentUrl(document); var pos = url.lastIndexOf("/"); if(pos != -1) { url = url.substring(pos + 1, url.length); url = WYSIWYG_Core.stringToRegex(url); // exact replacing of url. regex: src="<url>" if(exact) { regex = eval("/(href=\")(" + url + ")(#[^\"]*)/gi"); content = content.replace(regex, "$1$3"); } // not exect replacing of url. regex: <url> else { regex = eval("/(" + url + ")(.+)/gi"); content = content.replace(regex, "$2"); } } } return content; }, /* ---------------------------------------------------------------------- *\ Function : updateTextArea() Description : Updates the text area value with the HTML source of the WYSIWYG Arguments : n - The editor identifier (the textarea's ID) \* ---------------------------------------------------------------------- */ updateTextArea: function(n) { // on update switch editor back to html mode if(this.viewTextMode[n]) { this.viewText(n); } // get inner HTML var content = this.getEditorWindow(n).document.body.innerHTML; // strip off defined URLs on IE content = this.stripURLPath(n, content); // replace all decimal color strings with hex color strings content = WYSIWYG_Core.replaceRGBWithHexColor(content); // remove line breaks before content will be updated if(this.config[n].ReplaceLineBreaks) { content = content.replace(/(\r\n)|(\n)/ig, ""); } // set content back in textarea $(n).value = content; }, /* ---------------------------------------------------------------------- *\ Function : hideToolbars() Description : Hide all toolbars Usage : WYSIWYG.hideToolbars(n) Arguments : n - The editor identifier (the textarea's ID) \* ---------------------------------------------------------------------- */ hideToolbars: function(n) { for(var i=0;i<this.config[n].Toolbar.length;i++) { var toolbar = $("toolbar" + i + "_" + n); if(toolbar) { toolbar.style.display = "none"; } } }, /* ---------------------------------------------------------------------- *\ Function : showToolbars() Description : Display all toolbars Usage : WYSIWYG.showToolbars(n) Arguments : n - The editor identifier (the textarea's ID) \* ---------------------------------------------------------------------- */ showToolbars: function(n) { for(var i=0;i<this.config[n].Toolbar.length;i++) { var toolbar = $("toolbar" + i + "_" + n); if(toolbar) { toolbar.style.display = ""; } } }, /* ---------------------------------------------------------------------- *\ Function : hideStatusBar() Description : Hide the status bar Usage : WYSIWYG.hideStatusBar(n) Arguments : n - The editor identifier (the textarea's ID) \* ---------------------------------------------------------------------- */ hideStatusBar: function(n) { var statusbar = $('wysiwyg_statusbar_' + n); if(statusbar) { statusbar.style.display = "none"; } }, /* ---------------------------------------------------------------------- *\ Function : showStatusBar() Description : Display the status bar Usage : WYSIWYG.showStatusBar(n) Arguments : n - The editor identifier (the textarea's ID) \* ---------------------------------------------------------------------- */ showStatusBar: function(n) { var statusbar = $('wysiwyg_statusbar_' + n); if(statusbar) { statusbar.style.display = ""; } }, /** * Finds the node with the given tag name in the given range * * @param {String} tagName Parent tag to find * @param {Range} range Current range */ findParent: function(parentTagName, range){ parentTagName = parentTagName.toUpperCase(); var rangeWorking; var elmWorking = null; try { if(!WYSIWYG_Core.isMSIE) { var node = range.startContainer; var pos = range.startOffset; if(node.nodeType != 3) { node = node.childNodes[pos]; } return WYSIWYG_Core.findParentNode(parentTagName, node); } else { elmWorking = (range.length > 0) ? range.item(0): range.parentElement(); elmWorking = WYSIWYG_Core.findParentNode(parentTagName, elmWorking); if(elmWorking != null) return elmWorking; rangeWorking = range.duplicate(); rangeWorking.collapse(true); rangeWorking.moveEnd("character", 1); if (rangeWorking.text.length>0) { while (rangeWorking.compareEndPoints("EndToEnd", range) < 0){ rangeWorking.move("Character"); if (null != this.findParentTag(parentTagName, rangeWorking)){ return this.findParentTag(parentTagName, rangeWorking); } } } return null; } } catch(e) { return null; } }, /** * Get the acutally tag of the given range * * @param {Range} range Current range */ getTag: function(range) { try { if(!WYSIWYG_Core.isMSIE) { var node = range.startContainer; var pos = range.startOffset; if(node.nodeType != 3) { node = node.childNodes[pos]; } if(node.nodeName && node.nodeName.search(/#/) != -1) { return node.parentNode; } return node; } else { if(range.length > 0) { return range.item(0); } else if(range.parentElement()) { return range.parentElement(); } } return null; } catch(e) { return null; } }, /** * Get the parent node of the given node * * @param {DOMElement} element - Element which parent will be returned */ getParent: function(element) { if(element.parentNode) { return element.parentNode; } return null; }, /* ---------------------------------------------------------------------- *\ Function : getTextRange() Description : Get the text range object of the given element Usage : WYSIWYG.getTextRange(element) Arguments : element - An element of which you get the text range object \* ---------------------------------------------------------------------- */ getTextRange: function(element){ var range = element.parentTextEdit.createTextRange(); range.moveToElementText(element); return range; }, /* ---------------------------------------------------------------------- *\ Function : invertIELineBreakCapability() Description : Inverts the line break capability of IE (Thx to richyrich) Normal: ENTER = <p> , SHIFT + ENTER = <br> Inverted: ENTER = <br>, SHIFT + ENTER = <p> Usage : WYSIWYG.invertIELineBreakCapability(n) Arguments : n - The editor identifier (the textarea's ID) \* ---------------------------------------------------------------------- */ invertIELineBreakCapability: function(n) { var editor = this.getEditorWindow(n); var sel; // validate if the press key is the carriage return key if (editor.event.keyCode==13) { if (!editor.event.shiftKey) { sel = this.getRange(this.getSelection(n)); sel.pasteHTML("<br>"); editor.event.cancelBubble = true; editor.event.returnValue = false; sel.select(); sel.moveEnd("character", 1); sel.moveStart("character", 1); sel.collapse(false); return false; } else { sel = this.getRange(this.getSelection(n)); sel.pasteHTML("<p>"); editor.event.cancelBubble = true; editor.event.returnValue = false; sel.select(); sel.moveEnd("character", 1); sel.moveStart("character", 1); sel.collapse(false); return false; } } }, /* ---------------------------------------------------------------------- *\ Function : selectNode() Description : Select a node within the current editor Usage : WYSIWYG.selectNode(n, level) Arguments : n - The editor identifier (the textarea's ID) level - identifies the level of the element which will be selected \* ---------------------------------------------------------------------- */ selectNode: function(n, level) { var sel = this.getSelection(n); var range = this.getRange(sel); var parentnode = this.getTag(range); var i = 0; for (var node=parentnode; (node && (node.nodeType == 1)); node=node.parentNode) { if (i == level) { this.nodeSelection(n, node); } i++; } this.updateStatusBar(n); }, /* ---------------------------------------------------------------------- *\ Function : nodeSelection() Description : Do the node selection Usage : WYSIWYG.nodeSelection(n, node) Arguments : n - The editor identifier (the textarea's ID) node - The node which will be selected \* ---------------------------------------------------------------------- */ nodeSelection: function(n, node) { var doc = this.getEditorWindow(n).document; var sel = this.getSelection(n); var range = this.getRange(sel); if(!WYSIWYG_Core.isMSIE) { if (node.nodeName == "BODY") { range.selectNodeContents(node); } else { range.selectNode(node); } /* if (endNode) { try { range.setStart(node, startOffset); range.setEnd(endNode, endOffset); } catch(e) { } } */ if (sel) { sel.removeAllRanges(); } if (sel) { sel.addRange(range); } } else { // MSIE may not select everything when BODY is selected - // start may be set to first text node instead of first non-text node - // no known workaround if ((node.nodeName == "TABLE") || (node.nodeName == "IMG") || (node.nodeName == "INPUT") || (node.nodeName == "SELECT") || (node.nodeName == "TEXTAREA")) { try { range = doc.body.createControlRange(); range.addElement(node); range.select(); } catch(e) { } } else { range = doc.body.createTextRange(); if (range) { range.collapse(); if (range.moveToElementText) { try { range.moveToElementText(node); range.select(); } catch(e) { try { range = doc.body.createTextRange(); range.moveToElementText(node); range.select(); } catch(e) {} } } else { try { range = doc.body.createTextRange(); range.moveToElementText(node); range.select(); } catch(e) {} } } } } } } /******************************************************************** * openWYSIWYG core functions Copyright (c) 2006 openWebWare.com * Contact us at devs@openwebware.com * This copyright notice MUST stay intact for use. * * $Id: wysiwyg.js,v 1.22 2007/09/08 21:45:57 xhaggi Exp $ ********************************************************************/ var WYSIWYG_Core = { /** * Holds true if browser is MSIE, otherwise false */ isMSIE: navigator.appName == "Microsoft Internet Explorer" ? true : false, /** * Holds true if browser is Firefox (Mozilla) */ isFF: !document.all && document.getElementById && !this.isOpera, /** * Holds true if browser is Opera, otherwise false */ isOpera: navigator.appName == "Opera" ? true : false, /** * Trims whitespaces of the given string * * @param str String * @return Trimmed string */ trim: function(str) { return str.replace(/^\s*|\s*$/g,""); }, /** * Determine if the given parameter is defined * * @param p Parameter * @return true/false dependents on definition of the parameter */ defined: function(p) { return typeof p == "undefined" ? false : true; }, /** * Determine if the browser version is compatible * * @return true/false depending on compatiblity of the browser */ isBrowserCompatible: function() { // Validate browser and compatiblity if ((navigator.userAgent.indexOf('Safari') != -1 ) || !document.getElementById || !document.designMode){ //no designMode (Safari lies) return false; } return true; }, /** * Set the style attribute of the given element. * Private method to solve the IE bug while setting the style attribute. * * @param {DOMElement} node The element on which the style attribute will affect * @param {String} style Stylesheet which will be set */ _setStyleAttribute: function(node, style) { if(style == null) return; var styles = style.split(";"); var pos; for(var i=0;i<styles.length;i++) { var attributes = styles[i].split(":"); if(attributes.length == 2) { try { var attr = WYSIWYG_Core.trim(attributes[0]); while((pos = attr.search(/-/)) != -1) { var strBefore = attr.substring(0, pos); var strToUpperCase = attr.substring(pos + 1, pos + 2); var strAfter = attr.substring(pos + 2, attr.length); attr = strBefore + strToUpperCase.toUpperCase() + strAfter; } var value = WYSIWYG_Core.trim(attributes[1]).toLowerCase(); node.style[attr] = value; } catch (e) { alert(e); } } } }, /** * Fix's the issue while getting the attribute style on IE * It's return an object but we need the style string * * @private * @param {DOMElement} node Node element * @return {String} Stylesheet */ _getStyleAttribute: function(node) { if(this.isMSIE) { return node.style['cssText'].toLowerCase(); } else { return node.getAttribute("style"); } }, /** * Set an attribute's value on the given node element. * * @param {DOMElement} node Node element * @param {String} attr Attribute which is set * @param {String} value Value of the attribute */ setAttribute: function(node, attr, value) { if(value == null || node == null || attr == null) return; if(attr.toLowerCase() == "style") { this._setStyleAttribute(node, value); } else { node.setAttribute(attr, value); } }, /** * Removes an attribute on the given node * * @param {DOMElement} node Node element * @param {String} attr Attribute which will be removed */ removeAttribute: function(node, attr) { node.removeAttribute(attr, false); }, /** * Get the vale of the attribute on the given node * * @param {DOMElement} node Node element * @param {String} attr Attribute which value will be returned */ getAttribute: function(node, attr) { if(node == null || attr == null) return; if(attr.toLowerCase() == "style") { return this._getStyleAttribute(node); } else { return node.getAttribute(attr); } }, /** * Get the path out of an given url * * @param {String} url The url with is used to get the path */ getDocumentPathOfUrl: function(url) { var path = null; // if local file system, convert local url into web url url = url.replace(/file:\/\//gi, "file:///"); url = url.replace(/\\/gi, "\/"); var pos = url.lastIndexOf("/"); if(pos != -1) { path = url.substring(0, pos + 1); } return path; }, /** * Get the documents url, convert local urls to web urls * * @param {DOMElement} doc Document which is used to get the url */ getDocumentUrl: function(doc) { // if local file system, convert local url into web url var url = doc.URL; url = url.replace(/file:\/\//gi, "file:///"); url = url.replace(/\\/gi, "\/"); return url; }, /** * Find a parent node with the given name, of the given start node * * @param {String} tagName - Tag name of the node to find * @param {DOMElement} node - Node element */ findParentNode: function(tagName, node) { while (node.tagName != "HTML") { if (node.tagName == tagName){ return node; } node = node.parentNode; } return null; }, /** * Cancel the given event. * * @param e Event which will be canceled */ cancelEvent: function(e) { if (!e) return false; if (this.isMSIE) { e.returnValue = false; e.cancelBubble = true; } else { e.preventDefault(); e.stopPropagation && e.stopPropagation(); } return false; }, /** * Converts a RGB color string to hex color string. * * @param color RGB color string * @param Hex color string */ toHexColor: function(color) { color = color.replace(/^rgb/g,''); color = color.replace(/\(/g,''); color = color.replace(/\)/g,''); color = color.replace(/ /g,''); color = color.split(','); var r = parseFloat(color[0]).toString(16).toUpperCase(); var g = parseFloat(color[1]).toString(16).toUpperCase(); var b = parseFloat(color[2]).toString(16).toUpperCase(); if (r.length<2) { r='0'+r; } if (g.length<2) { g='0'+g; } if (b.length<2) { b='0'+b; } return r + g + b; }, /** * Converts a decimal color to hex color string. * * @param Decimal color * @param Hex color string */ _dec_to_rgb: function(value) { var hex_string = ""; for (var hexpair = 0; hexpair < 3; hexpair++) { var myByte = value & 0xFF; // get low byte value >>= 8; // drop low byte var nybble2 = myByte & 0x0F; // get low nybble (4 bits) var nybble1 = (myByte >> 4) & 0x0F; // get high nybble hex_string += nybble1.toString(16); // convert nybble to hex hex_string += nybble2.toString(16); // convert nybble to hex } return hex_string.toUpperCase(); }, /** * Replace RGB color strings with hex color strings within a string. * * @param {String} str RGB String * @param {String} Hex color string */ replaceRGBWithHexColor: function(str) { if(str == null) return ""; // find all decimal color strings var matcher = str.match(/rgb\([0-9 ]+,[0-9 ]+,[0-9 ]+\)/gi); if(matcher) { for(var j=0; j<matcher.length;j++) { var regex = eval("/" + WYSIWYG_Core.stringToRegex(matcher[j]) + "/gi"); // replace the decimal color strings with hex color strings str = str.replace(regex, "#" + this.toHexColor(matcher[j])); } } return str; }, /** * Execute the given command on the given editor * * @param n The editor's identifier * @param cmd Command which is execute */ execCommand: function(n, cmd, value) { if(typeof(value) == "undefined") value = null; // firefox BackColor problem fixed if(cmd == 'BackColor' && WYSIWYG_Core.isFF) cmd = 'HiliteColor'; // firefox cut, paste and copy if(WYSIWYG_Core.isFF && (cmd == "Cut" || cmd == "Paste" || cmd == "Copy")) { try { WYSIWYG.getEditorWindow(n).document.execCommand(cmd, false, value); } catch(e) { if(confirm("Copy/Cut/Paste is not available in Mozilla and Firefox\nDo you want more information about this issue?")) { window.open('http://www.mozilla.org/editor/midasdemo/securityprefs.html'); } } } else { WYSIWYG.getEditorWindow(n).document.execCommand(cmd, false, value); } }, /** * Parse a given string to a valid regular expression * * @param {String} string String to be parsed * @return {RegEx} Valid regular expression */ stringToRegex: function(string) { string = string.replace(/\//gi, "\\/"); string = string.replace(/\(/gi, "\\("); string = string.replace(/\)/gi, "\\)"); string = string.replace(/\[/gi, "\\["); string = string.replace(/\]/gi, "\\]"); string = string.replace(/\+/gi, "\\+"); string = string.replace(/\$/gi, "\\$"); string = string.replace(/\*/gi, "\\*"); string = string.replace(/\?/gi, "\\?"); string = string.replace(/\^/gi, "\\^"); string = string.replace(/\\b/gi, "\\\\b"); string = string.replace(/\\B/gi, "\\\\B"); string = string.replace(/\\d/gi, "\\\\d"); string = string.replace(/\\B/gi, "\\\\B"); string = string.replace(/\\D/gi, "\\\\D"); string = string.replace(/\\f/gi, "\\\\f"); string = string.replace(/\\n/gi, "\\\\n"); string = string.replace(/\\r/gi, "\\\\r"); string = string.replace(/\\t/gi, "\\\\t"); string = string.replace(/\\v/gi, "\\\\v"); string = string.replace(/\\s/gi, "\\\\s"); string = string.replace(/\\S/gi, "\\\\S"); string = string.replace(/\\w/gi, "\\\\w"); string = string.replace(/\\W/gi, "\\\\W"); return string; }, /** * Add an event listener * * @param obj Object on which the event will be attached * @param ev Kind of event * @param fu Function which is execute on the event */ addEvent: function(obj, ev, fu) { if (obj.attachEvent) obj.attachEvent("on" + ev, fu); else obj.addEventListener(ev, fu, false); }, /** * Remove an event listener * * @param obj Object on which the event will be attached * @param ev Kind of event * @param fu Function which is execute on the event */ removeEvent: function(obj, ev, fu) { if (obj.attachEvent) obj.detachEvent("on" + ev, fu); else obj.removeEventListener(ev, fu, false); }, /** * Includes a javascript file * * @param file Javascript file path and name */ includeJS: function(file) { var script = document.createElement("script"); this.setAttribute(script, "type", "text/javascript"); this.setAttribute(script, "src", file); var heads = document.getElementsByTagName("head"); for(var i=0;i<heads.length;i++) { heads[i].appendChild(script); } }, /** * Includes a stylesheet file * * @param file Stylesheet file path and name */ includeCSS: function(path) { var link = document.createElement("link"); this.setAttribute(link, "rel", "stylesheet"); this.setAttribute(link, "type", "text/css"); this.setAttribute(link, "href", path); var heads = document.getElementsByTagName("head"); for(var i=0;i<heads.length;i++) { heads[i].appendChild(link); } }, /** * Get the screen position of the given element. * * @param {HTMLObject} elm1 Element which position will be calculate * @param {HTMLObject} elm2 Element which is the last one before calculation stops * @param {Object} Left and top position of the given element */ getElementPosition: function(elm1, elm2) { var top = 0, left = 0; while (elm1 && elm1 != elm2) { left += elm1.offsetLeft; top += elm1.offsetTop; elm1 = elm1.offsetParent; } return {left : left, top : top}; }, /** * Get the window size * @private */ windowSize: function() { if (window.innerWidth) { return {width: window.innerWidth, height: window.innerHeight}; } else if (document.body && document.body.offsetWidth) { return {width: document.body.offsetWidth, height: document.body.offsetHeight}; } else { return {width: 0, height: 0}; } } } /** * Context menu object */ var WYSIWYG_ContextMenu = { html: "", contextMenuDiv: null, /** * Init function * * @param {String} n Editor identifier */ init: function(n) { var doc = WYSIWYG.getEditorWindow(n).document; // create context menu div this.contextMenuDiv = document.createElement("div"); this.contextMenuDiv.className = "wysiwyg-context-menu-div"; this.contextMenuDiv.setAttribute("class", "wysiwyg-context-menu-div"); this.contextMenuDiv.style.display = "none"; this.contextMenuDiv.style.position = "absolute"; this.contextMenuDiv.style.zIndex = 9999; this.contextMenuDiv.style.left = "0"; this.contextMenuDiv.style.top = "0"; this.contextMenuDiv.unselectable = "on"; document.body.insertBefore(this.contextMenuDiv, document.body.firstChild); // bind event listeners WYSIWYG_Core.addEvent(doc, "contextmenu", function context(e) { WYSIWYG_ContextMenu.show(e, n); }); WYSIWYG_Core.addEvent(doc, "click", function context(e) { WYSIWYG_ContextMenu.close(); }); WYSIWYG_Core.addEvent(doc, "keydown", function context(e) { WYSIWYG_ContextMenu.close(); }); WYSIWYG_Core.addEvent(document, "click", function context(e) { WYSIWYG_ContextMenu.close(); }); }, /** * Show the context menu * * @param e Event * @param n Editor identifier */ show: function(e, n) { if(this.contextMenuDiv == null) return false; var ifrm = WYSIWYG.getEditor(n); var doc = WYSIWYG.getEditorWindow(n).document; // set the context menu position var pos = WYSIWYG_Core.getElementPosition(ifrm); var x = WYSIWYG_Core.isMSIE ? pos.left + e.clientX : pos.left + (e.pageX - doc.body.scrollLeft); var y = WYSIWYG_Core.isMSIE ? pos.top + e.clientY : pos.top + (e.pageY - doc.body.scrollTop); this.contextMenuDiv.style.left = x + "px"; this.contextMenuDiv.style.top = y + "px"; this.contextMenuDiv.style.visibility = "visible"; this.contextMenuDiv.style.display = "block"; // call the context menu, mozilla needs some time window.setTimeout("WYSIWYG_ContextMenu.output('" + n + "')", 10); WYSIWYG_Core.cancelEvent(e); return false; }, /** * Output the context menu items * * @param n Editor identifier */ output: function (n) { // get selection var sel = WYSIWYG.getSelection(n); var range = WYSIWYG.getRange(sel); // get current selected node var tag = WYSIWYG.getTag(range); if(tag == null) { return; } // clear context menu this.clear(); // Determine kind of nodes var isImg = (tag.nodeName == "IMG") ? true : false; var isLink = (tag.nodeName == "A") ? true : false; // Selection is an image or selection is a text with length greater 0 var len = 0; if(WYSIWYG_Core.isMSIE) len = (document.selection && range.text) ? range.text.length : 0; else len = range.toString().length; var sel = len != 0 || isImg; // Icons var iconLink = { enabled: WYSIWYG.config[n].ImagesDir + WYSIWYG.ToolbarList["createlink"][3], disabled: WYSIWYG.config[n].ImagesDir + WYSIWYG.ToolbarList["createlink"][2]}; var iconImage = { enabled: WYSIWYG.config[n].ImagesDir + WYSIWYG.ToolbarList["insertimage"][3], disabled: WYSIWYG.config[n].ImagesDir + WYSIWYG.ToolbarList["insertimage"][2]}; var iconDelete = { enabled: WYSIWYG.config[n].ImagesDir + WYSIWYG.ToolbarList["delete"][3], disabled: WYSIWYG.config[n].ImagesDir + WYSIWYG.ToolbarList["delete"][2]}; var iconCopy = { enabled: WYSIWYG.config[n].ImagesDir + WYSIWYG.ToolbarList["copy"][3], disabled: WYSIWYG.config[n].ImagesDir + WYSIWYG.ToolbarList["copy"][2]}; var iconCut = { enabled: WYSIWYG.config[n].ImagesDir + WYSIWYG.ToolbarList["cut"][3], disabled: WYSIWYG.config[n].ImagesDir + WYSIWYG.ToolbarList["cut"][2]}; var iconPaste = { enabled: WYSIWYG.config[n].ImagesDir + WYSIWYG.ToolbarList["paste"][3], disabled: WYSIWYG.config[n].ImagesDir + WYSIWYG.ToolbarList["paste"][2]}; // Create context menu html this.html += '<table class="wysiwyg-context-menu" border="0" cellpadding="0" cellspacing="0">'; // Add items this.addItem(n, 'Copy', iconCopy, 'Copy', sel); this.addItem(n, 'Cut', iconCut, 'Cut', sel); this.addItem(n, 'Paste', iconPaste, 'Paste', true); this.addSeperator(); this.addItem(n, 'InsertImage', iconImage, 'Modify Image Properties...', isImg); this.addItem(n, 'CreateLink', iconLink, 'Create or Modify Link...', sel || isLink); this.addItem(n, 'RemoveNode', iconDelete, 'Remove', true); this.html += '</table>'; this.contextMenuDiv.innerHTML = this.html; }, /** * Close the context menu */ close: function() { this.contextMenuDiv.style.visibility = "hidden"; this.contextMenuDiv.style.display = "none"; }, /** * Clear context menu */ clear: function() { this.contextMenuDiv.innerHTML = ""; this.html = ""; }, /** * Add context menu item * * @param n editor identifier * @param cmd Command * @param icon Icon which is diabled * @param title Title of the item * @param disabled If item is diabled */ addItem: function(n, cmd, icon, title, disabled) { var item = ''; if(disabled) { item += '<tr>'; item += '<td class="icon"><a href="javascript:WYSIWYG.execCommand(\'' + n + '\',\'' + cmd + '\', null);"><img src="' + icon.enabled + '" border="0"></a></td>'; item += '<td onmouseover="this.className=\'mouseover\'" onmouseout="this.className=\'\'" onclick="WYSIWYG.execCommand(\'' + n + '\', \'' + cmd + '\', null);WYSIWYG_ContextMenu.close();"><a href="javascript:void(0);">' + title + '</a></td>'; item += '</tr>'; } else { item += '<tr>'; item += '<td class="icon"><img src="' + icon.disabled + '" border="0"></td>'; item += '<td onmouseover="this.className=\'mouseover\'" onmouseout="this.className=\'\'"><span class="disabled">' + title + '</span></td>'; item += '</tr>'; } this.html += item; }, /** * Add seperator to context menu */ addSeperator: function() { var output = ''; output += '<tr>'; output += '<td colspan="2" style="text-align:center;"><hr size="1" color="#C9C9C9" width="95%"></td>'; output += '</tr>'; this.html += output; } } /** * Table object */ var WYSIWYG_Table = { /** * */ create: function(n, tbl) { // get editor var doc = WYSIWYG.getEditorWindow(n).document; // get selection and range var sel = WYSIWYG.getSelection(n); var range = WYSIWYG.getRange(sel); var table = null; // get element from selection if(WYSIWYG_Core.isMSIE) { if(sel.type == "Control" && range.length == 1) { range = WYSIWYG.getTextRange(range(0)); range.select(); } } // find a parent TABLE element //table = WYSIWYG.findParent("table", range); // check if parent is found //var update = (table == null) ? false : true; //if(!update) table = tbl; table = tbl; // add rows and cols var rows = WYSIWYG_Core.getAttribute(tbl, "tmprows"); var cols = WYSIWYG_Core.getAttribute(tbl, "tmpcols"); WYSIWYG_Core.removeAttribute(tbl, "tmprows"); WYSIWYG_Core.removeAttribute(tbl, "tmpcols"); for(var i=0;i<rows;i++) { var tr = doc.createElement("tr"); for(var j=0;j<cols;j++){ var td = createTD(); tr.appendChild(td); } table.appendChild(tr); } // on update exit here //if(update) { return; } // Check if IE or Mozilla (other) if (WYSIWYG_Core.isMSIE) { range.pasteHTML(table.outerHTML); } else { WYSIWYG.insertNodeAtSelection(table, n); } // refresh table highlighting this.refreshHighlighting(n); // functions function createTD() { var td = doc.createElement("td"); td.innerHTML = "&nbsp;"; return td; } }, /** * Enables the table highlighting * * @param {String} n The editor identifier (the textarea's ID) */ refreshHighlighting: function(n) { var doc = WYSIWYG.getEditorWindow(n).document; var tables = doc.getElementsByTagName("table"); for(var i=0;i<tables.length;i++) { this._enableHighlighting(tables[i]); } var tds = doc.getElementsByTagName("td"); for(var i=0;i<tds.length;i++) { this._enableHighlighting(tds[i]); } }, /** * Enables the table highlighting * * @param {String} n The editor identifier (the textarea's ID) */ disableHighlighting: function(n) { var doc = WYSIWYG.getEditorWindow(n).document; var tables = doc.getElementsByTagName("table"); for(var i=0;i<tables.length;i++) { this._disableHighlighting(tables[i]); } var tds = doc.getElementsByTagName("td"); for(var i=0;i<tds.length;i++) { this._disableHighlighting(tds[i]); } }, /** * @private */ _enableHighlighting: function(node) { var style = WYSIWYG_Core.getAttribute(node, "style"); if(style == null) style = " "; //alert("ENABLE: ELM = " + node.tagName + "; STYLE = " + style); WYSIWYG_Core.removeAttribute(node, "prevstyle"); WYSIWYG_Core.setAttribute(node, "prevstyle", style); WYSIWYG_Core.setAttribute(node, "style", "border:1px dashed #AAAAAA;"); }, /** * @private */ _disableHighlighting: function(node) { var style = WYSIWYG_Core.getAttribute(node, "prevstyle"); //alert("DISABLE: ELM = " + node.tagName + "; STYLE = " + style); // if no prevstyle is defined, the table is not in highlighting mode if(style == null || style == "") { this._enableHighlighting(node); return; } WYSIWYG_Core.removeAttribute(node, "prevstyle"); WYSIWYG_Core.removeAttribute(node, "style"); WYSIWYG_Core.setAttribute(node, "style", style); } } /** * Get an element by it's identifier * * @param id Element identifier */ function $(id) { return document.getElementById(id); } /** * Emulates insertAdjacentHTML(), insertAdjacentText() and * insertAdjacentElement() three functions so they work with Netscape 6/Mozilla * by Thor Larholm me@jscript.dk */ if(typeof HTMLElement!="undefined" && !HTMLElement.prototype.insertAdjacentElement){ HTMLElement.prototype.insertAdjacentElement = function (where,parsedNode) { switch (where){ case 'beforeBegin': this.parentNode.insertBefore(parsedNode,this); break; case 'afterBegin': this.insertBefore(parsedNode,this.firstChild); break; case 'beforeEnd': this.appendChild(parsedNode); break; case 'afterEnd': if (this.nextSibling) { this.parentNode.insertBefore(parsedNode,this.nextSibling); } else { this.parentNode.appendChild(parsedNode); } break; } }; HTMLElement.prototype.insertAdjacentHTML = function (where,htmlStr) { var r = this.ownerDocument.createRange(); r.setStartBefore(this); var parsedHTML = r.createContextualFragment(htmlStr); this.insertAdjacentElement(where,parsedHTML); }; HTMLElement.prototype.insertAdjacentText = function (where,txtStr) { var parsedText = document.createTextNode(txtStr); this.insertAdjacentElement(where,parsedText); }; }
JavaScript
/******************************************************************** * openWYSIWYG settings file Copyright (c) 2006 openWebWare.com * Contact us at devs@openwebware.com * This copyright notice MUST stay intact for use. * * $Id: wysiwyg-settings.js,v 1.4 2007/01/22 23:05:57 xhaggi Exp $ ********************************************************************/ /* * Full featured setup used the openImageLibrary addon */ var full = new WYSIWYG.Settings(); //full.ImagesDir = "images/"; //full.PopupsDir = "popups/"; //full.CSSFile = "styles/wysiwyg.css"; full.Width = "85%"; full.Height = "250px"; // customize toolbar buttons full.addToolbarElement("font", 3, 1); full.addToolbarElement("fontsize", 3, 2); full.addToolbarElement("headings", 3, 3); // openImageLibrary addon implementation full.ImagePopupFile = "addons/imagelibrary/insert_image.php"; full.ImagePopupWidth = 600; full.ImagePopupHeight = 245; /* * Small Setup Example */ var small = new WYSIWYG.Settings(); small.Width = "350px"; small.Height = "100px"; small.DefaultStyle = "font-family: Arial; font-size: 12px; background-color: #AA99AA"; small.Toolbar[0] = new Array("font", "fontsize", "bold", "italic", "underline"); // small setup for toolbar 1 small.Toolbar[1] = ""; // disable toolbar 2 small.StatusBarEnabled = false;
JavaScript
/******************************************************************** * openWYSIWYG popup functions Copyright (c) 2006 openWebWare.com * Contact us at devs@openwebware.com * This copyright notice MUST stay intact for use. * * $Id: wysiwyg-popup.js,v 1.2 2007/01/22 23:45:30 xhaggi Exp $ ********************************************************************/ var WYSIWYG_Popup = { /** * Return the value of an given URL parameter. * * @param param Parameter * @return Value of the given parameter */ getParam: function(param) { var query = window.location.search.substring(1); var parms = query.split('&'); for (var i=0; i<parms.length; i++) { var pos = parms[i].indexOf('='); if (pos > 0) { var key = parms[i].substring(0,pos).toLowerCase(); var val = parms[i].substring(pos+1); if(key == param.toLowerCase()) return val; } } return null; } } // close the popup if the opener does not hold the WYSIWYG object if(!window.opener) window.close(); // bind objects on local vars var WYSIWYG = window.opener.WYSIWYG; var WYSIWYG_Core = window.opener.WYSIWYG_Core; var WYSIWYG_Table = window.opener.WYSIWYG_Table;
JavaScript
/******************************************************************** * openWYSIWYG color chooser Copyright (c) 2006 openWebWare.com * Contact us at devs@openwebware.com * This copyright notice MUST stay intact for use. * * $Id: wysiwyg-color.js,v 1.1 2007/01/29 19:19:49 xhaggi Exp $ ********************************************************************/ function WYSIWYG_Color() { // colors var COLORS = new Array( "#000000","#993300","#333300","#003300","#003366","#000080", "#333399","#333333","#800000","#FF6600","#808000","#008000", "#008080","#0000FF","#666699","#808080","#FF0000","#FF9900", "#99CC00","#339966","#33CCCC","#3366FF","#800080","#999999", "#FF00FF","#FFCC00","#FFFF00","#00FF00","#00CCFF","#993366", "#C0C0C0","#FF99CC","#FFCC99","#FFFF99","#CCFFCC","#CCFFFF", "#99CCFF","#666699","#777777","#999999","#EEEEEE","#FFFFFF" ); // div id of the color table var CHOOSER_DIV_ID = "colorpicker-div"; /** * Init the color picker */ this.init = function() { var div = document.createElement("DIV"); div.id = CHOOSER_DIV_ID; div.style.position = "absolute"; div.style.visibility = "hidden"; document.body.appendChild(div); }; /** * Open the color chooser to choose a color. * * @param {String} element Element identifier */ this.choose = function(element) { var div = document.getElementById(CHOOSER_DIV_ID); if(div == null) { alert("Initialisation of color picker failed."); return; } // writes the content of the color picker write(element); // Display color picker var x = window.event.clientX + document.body.scrollLeft; var y = window.event.clientY + document.body.scrollTop; var winsize = windowSize(); if(x + div.offsetWidth > winsize.width) x = winsize.width - div.offsetWidth - 5; if(y + div.offsetHeight > winsize.height) y = winsize.height - div.offsetHeight - 5; div.style.left = x + "px"; div.style.top = y + "px"; div.style.visibility = "visible"; }; /** * Set the color in the given field * * @param {String} n Element identifier * @param {String} color HexColor String */ this.select = function(n, color) { var div = document.getElementById(CHOOSER_DIV_ID); var elm = document.getElementById(n); elm.value = color; elm.style.color = color; elm.style.backgroundColor = color; div.style.visibility = "hidden"; } /** * Write the color table * @param {String} n Element identifier * @private */ function write(n) { var div = document.getElementById(CHOOSER_DIV_ID); var output = ""; output += '<table border="1" cellpadding="0" cellspacing="0" class="wysiwyg-color-picker-table"><tr>'; for(var i = 0; i < COLORS.length;i++) { var color = COLORS[i]; output += '<td class="selectColorBorder" '; output += 'onmouseover="this.className=\'selectColorOn\';" '; output += 'onmouseout="this.className=\'selectColorOff\';" '; output += 'onclick="WYSIWYG_ColorInst.select(\'' + n + '\', \'' + color + '\');"> '; output += '<div style="background-color:' + color + ';" class="wysiwyg-color-picker-div">&nbsp;</div> '; output += '</td>'; if(((i+1) % Math.round(Math.sqrt(COLORS.length))) == 0) { output += "</tr><tr>"; } } output += '</tr></table>'; // write to div element div.innerHTML = output; }; /** * Set the window.event on Mozilla Browser * @private */ function _event_tracker(event) { if (!document.all && document.getElementById) { window.event = event; } } document.onmousedown = _event_tracker; /** * Get the window size * @private */ function windowSize() { if (window.innerWidth) { return {width: window.innerWidth, height: window.innerHeight}; } else if (document.body && document.body.offsetWidth) { return {width: document.body.offsetWidth, height: document.body.offsetHeight}; } else { return {width: 0, height: 0}; } } } var WYSIWYG_ColorInst = new WYSIWYG_Color();
JavaScript
<script> function abc() { alert('123'); } </script>
JavaScript
/* Copyright (c) 2007 Paul Bakaus (paul.bakaus@googlemail.com) and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net) * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses. * * $LastChangedDate: 2007-10-06 20:11:15 +0200 (Sa, 06 Okt 2007) $ * $Rev: 3581 $ * * Version: @VERSION * * Requires: jQuery 1.2+ */ (function($){ $.dimensions = { version: '@VERSION' }; // Create innerHeight, innerWidth, outerHeight and outerWidth methods $.each( [ 'Height', 'Width' ], function(i, name){ // innerHeight and innerWidth $.fn[ 'inner' + name ] = function() { if (!this[0]) return; var torl = name == 'Height' ? 'Top' : 'Left', // top or left borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right return num( this, name.toLowerCase() ) + num(this, 'padding' + torl) + num(this, 'padding' + borr); }; // outerHeight and outerWidth $.fn[ 'outer' + name ] = function(options) { if (!this[0]) return; var torl = name == 'Height' ? 'Top' : 'Left', // top or left borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right options = $.extend({ margin: false }, options || {}); return num( this, name.toLowerCase() ) + num(this, 'border' + torl + 'Width') + num(this, 'border' + borr + 'Width') + num(this, 'padding' + torl) + num(this, 'padding' + borr) + (options.margin ? (num(this, 'margin' + torl) + num(this, 'margin' + borr)) : 0); }; }); // Create scrollLeft and scrollTop methods $.each( ['Left', 'Top'], function(i, name) { $.fn[ 'scroll' + name ] = function(val) { if (!this[0]) return; return val != undefined ? // Set the scroll offset this.each(function() { this == window || this == document ? window.scrollTo( name == 'Left' ? val : $(window)[ 'scrollLeft' ](), name == 'Top' ? val : $(window)[ 'scrollTop' ]() ) : this[ 'scroll' + name ] = val; }) : // Return the scroll offset this[0] == window || this[0] == document ? self[ (name == 'Left' ? 'pageXOffset' : 'pageYOffset') ] || $.boxModel && document.documentElement[ 'scroll' + name ] || document.body[ 'scroll' + name ] : this[0][ 'scroll' + name ]; }; }); $.fn.extend({ position: function() { var left = 0, top = 0, elem = this[0], offset, parentOffset, offsetParent, results; if (elem) { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); parentOffset = offsetParent.offset(); // Subtract element margins offset.top -= num(elem, 'marginTop'); offset.left -= num(elem, 'marginLeft'); // Add offsetParent borders parentOffset.top += num(offsetParent, 'borderTopWidth'); parentOffset.left += num(offsetParent, 'borderLeftWidth'); // Subtract the two offsets results = { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left }; } return results; }, offsetParent: function() { var offsetParent = this[0].offsetParent; while ( offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && $.css(offsetParent, 'position') == 'static') ) offsetParent = offsetParent.offsetParent; return $(offsetParent); } }); function num(el, prop) { return parseInt($.css(el.jquery?el[0]:el,prop))||0; }; })(jQuery);
JavaScript
// JavaScript Document /*! Copyright (c) 2009 Brandon Aaron (http://brandonaaron.net) * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses. * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers. * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix. * * Version: 3.0.2 * * Requires: 1.2.2+ */ (function($) { var types = ['DOMMouseScroll', 'mousewheel']; $.event.special.mousewheel = { setup: function() { if ( this.addEventListener ) for ( var i=types.length; i; ) this.addEventListener( types[--i], handler, false ); else this.onmousewheel = handler; }, teardown: function() { if ( this.removeEventListener ) for ( var i=types.length; i; ) this.removeEventListener( types[--i], handler, false ); else this.onmousewheel = null; } }; $.fn.extend({ mousewheel: function(fn) { return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel"); }, unmousewheel: function(fn) { return this.unbind("mousewheel", fn); } }); function handler(event) { var args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true; event = $.event.fix(event || window.event); event.type = "mousewheel"; if ( event.wheelDelta ) delta = event.wheelDelta/120; if ( event.detail ) delta = -event.detail/3; // Add events and delta to the front of the arguments args.unshift(event, delta); return $.event.handle.apply(this, args); } })(jQuery); /** * @version $Id: $Revision * @package jquery * @subpackage lofslidernews * @copyright Copyright (C) JAN 2010 LandOfCoder.com <@emai:landofcoder@gmail.com>. All rights reserved. * @website http://landofcoder.com * @license This plugin is dual-licensed under the GNU General Public License and the MIT License */ // JavaScript Document (function($) { $.fn.lofJSidernews = function( settings ) { return this.each(function() { // get instance of the lofSiderNew. new $.lofSidernews( this, settings ); }); } $.lofSidernews = function( obj, settings ){ this.settings = { direction : '', mainItemSelector : 'li', navInnerSelector : 'ul', navSelector : 'li' , navigatorEvent : 'click', wapperSelector: '.lof-main-wapper', interval : 4000, auto : true, // whether to automatic play the slideshow maxItemDisplay : 3, startItem : 0, navPosition : 'vertical', navigatorHeight : 100, navigatorWidth : 310, duration : 600, navItemsSelector : '.lof-navigator li', navOuterSelector : '.lof-navigator-outer' , isPreloaded : true, easing : 'easeInOutQuad' } $.extend( this.settings, settings ||{} ); this.nextNo = null; this.previousNo = null; this.maxWidth = this.settings.mainWidth || 600; this.wrapper = $( obj ).find( this.settings.wapperSelector ); this.slides = this.wrapper.find( this.settings.mainItemSelector ); if( !this.wrapper.length || !this.slides.length ) return ; // set width of wapper if( this.settings.maxItemDisplay > this.slides.length ){ this.settings.maxItemDisplay = this.slides.length; } this.currentNo = isNaN(this.settings.startItem)||this.settings.startItem > this.slides.length?0:this.settings.startItem; this.navigatorOuter = $( obj ).find( this.settings.navOuterSelector ); this.navigatorItems = $( obj ).find( this.settings.navItemsSelector ) ; this.navigatorInner = this.navigatorOuter.find( this.settings.navInnerSelector ); if( this.settings.navPosition == 'horizontal' ){ this.navigatorInner.width( this.slides.length * this.settings.navigatorWidth ); this.navigatorOuter.width( this.settings.maxItemDisplay * this.settings.navigatorWidth ); this.navigatorOuter.height( this.settings.navigatorHeight ); } else { this.navigatorInner.height( this.slides.length * this.settings.navigatorHeight ); this.navigatorOuter.height( this.settings.maxItemDisplay * this.settings.navigatorHeight ); this.navigatorOuter.width( this.settings.navigatorWidth ); } this.navigratorStep = this.__getPositionMode( this.settings.navPosition ); this.directionMode = this.__getDirectionMode(); if( this.settings.direction == 'opacity') { this.wrapper.addClass( 'lof-opacity' ); $(this.slides).css('opacity',0).eq(this.currentNo).css('opacity',1); } else { this.wrapper.css({'left':'-'+this.currentNo*this.maxSize+'px', 'width':( this.maxWidth ) * this.slides.length } ); } if( this.settings.isPreloaded ) { this.preLoadImage( this.onComplete ); } else { this.onComplete(); } } $.lofSidernews.fn = $.lofSidernews.prototype; $.lofSidernews.fn.extend = $.lofSidernews.extend = $.extend; $.lofSidernews.fn.extend({ startUp:function( obj, wrapper ) { seft = this; this.navigatorItems.each( function(index, item ){ $(item).click( function(){ seft.jumping( index, true ); seft.setNavActive( index, item ); } ); $(item).css( {'height': seft.settings.navigatorHeight, 'width': seft.settings.navigatorWidth} ); }) this.registerWheelHandler( this.navigatorOuter, this ); this.setNavActive(this.currentNo ); if( this.settings.buttons && typeof (this.settings.buttons) == "object" ){ this.registerButtonsControl( 'click', this.settings.buttons, this ); } if( this.settings.auto ) this.play( this.settings.interval,'next', true ); return this; }, onComplete:function(){ setTimeout( function(){ $('.preload').fadeOut( 900 ); }, 400 ); this.startUp( ); }, preLoadImage:function( callback ){ var self = this; var images = this.wrapper.find( 'img' ); var count = 0; images.each( function(index,image){ if( !image.complete ){ image.onload =function(){ count++; if( count >= images.length ){ self.onComplete(); } } image.onerror =function(){ count++; if( count >= images.length ){ self.onComplete(); } } }else { count++; if( count >= images.length ){ self.onComplete(); } } } ); }, navivationAnimate:function( currentIndex ) { if (currentIndex <= this.settings.startItem || currentIndex - this.settings.startItem >= this.settings.maxItemDisplay-1) { this.settings.startItem = currentIndex - this.settings.maxItemDisplay+2; if (this.settings.startItem < 0) this.settings.startItem = 0; if (this.settings.startItem >this.slides.length-this.settings.maxItemDisplay) { this.settings.startItem = this.slides.length-this.settings.maxItemDisplay; } } this.navigatorInner.stop().animate( eval('({'+this.navigratorStep[0]+':-'+this.settings.startItem*this.navigratorStep[1]+'})'), {duration:500, easing:'easeInOutQuad'} ); }, setNavActive:function( index, item ){ if( (this.navigatorItems) ){ this.navigatorItems.removeClass( 'active' ); $(this.navigatorItems.get(index)).addClass( 'active' ); this.navivationAnimate( this.currentNo ); } }, __getPositionMode:function( position ){ if( position == 'horizontal' ){ return ['left', this.settings.navigatorWidth]; } return ['top', this.settings.navigatorHeight]; }, __getDirectionMode:function(){ switch( this.settings.direction ){ case 'opacity': this.maxSize=0; return ['opacity','opacity']; default: this.maxSize=this.maxWidth; return ['left','width']; } }, registerWheelHandler:function( element, obj ){ element.bind('mousewheel', function(event, delta ) { var dir = delta > 0 ? 'Up' : 'Down', vel = Math.abs(delta); if( delta > 0 ){ obj.previous( true ); } else { obj.next( true ); } return false; }); }, registerButtonsControl:function( eventHandler, objects, self ){ for( var action in objects ){ switch (action.toString() ){ case 'next': objects[action].click( function() { self.next( true) } ); break; case 'previous': objects[action].click( function() { self.previous( true) } ); break; } } return this; }, onProcessing:function( manual, start, end ){ this.previousNo = this.currentNo + (this.currentNo>0 ? -1 : this.slides.length-1); this.nextNo = this.currentNo + (this.currentNo < this.slides.length-1 ? 1 : 1- this.slides.length); return this; }, finishFx:function( manual ){ if( manual ) this.stop(); if( manual && this.settings.auto ){ this.play( this.settings.interval,'next', true ); } this.setNavActive( this.currentNo ); }, getObjectDirection:function( start, end ){ return eval("({'"+this.directionMode[0]+"':-"+(this.currentNo*start)+"})"); }, fxStart:function( index, obj, currentObj ){ if( this.settings.direction == 'opacity' ) { $(this.slides).stop().animate({opacity:0}, {duration: this.settings.duration, easing:this.settings.easing} ); $(this.slides).eq(index).stop().animate( {opacity:1}, {duration: this.settings.duration, easing:this.settings.easing} ); }else { this.wrapper.stop().animate( obj, {duration: this.settings.duration, easing:this.settings.easing} ); } return this; }, jumping:function( no, manual ){ this.stop(); if( this.currentNo == no ) return; var obj = eval("({'"+this.directionMode[0]+"':-"+(this.maxSize*no)+"})"); this.onProcessing( null, manual, 0, this.maxSize ) .fxStart( no, obj, this ) .finishFx( manual ); this.currentNo = no; }, next:function( manual , item){ this.currentNo += (this.currentNo < this.slides.length-1) ? 1 : (1 - this.slides.length); this.onProcessing( item, manual, 0, this.maxSize ) .fxStart( this.currentNo, this.getObjectDirection(this.maxSize ), this ) .finishFx( manual ); }, previous:function( manual, item ){ this.currentNo += this.currentNo > 0 ? -1 : this.slides.length - 1; this.onProcessing( item, manual ) .fxStart( this.currentNo, this.getObjectDirection(this.maxSize ), this ) .finishFx( manual ); }, play:function( delay, direction, wait ){ this.stop(); if(!wait){ this[direction](false); } var self = this; this.isRun = setTimeout(function() { self[direction](true); }, delay); }, stop:function(){ if (this.isRun == null) return; clearTimeout(this.isRun); this.isRun = null; } }) })(jQuery)
JavaScript
/* * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/ * * Uses the built in easing capabilities added In jQuery 1.1 * to offer multiple easing options * * TERMS OF USE - jQuery Easing * * Open source under the BSD License. * * Copyright © 2008 George McGinley Smith * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the author nor the names of contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */ // t: current time, b: begInnIng value, c: change In value, d: duration jQuery.easing['jswing'] = jQuery.easing['swing']; jQuery.extend( jQuery.easing, { def: 'easeOutQuad', swing: function (x, t, b, c, d) { //alert(jQuery.easing.default); return jQuery.easing[jQuery.easing.def](x, t, b, c, d); }, easeInQuad: function (x, t, b, c, d) { return c*(t/=d)*t + b; }, easeOutQuad: function (x, t, b, c, d) { return -c *(t/=d)*(t-2) + b; }, easeInOutQuad: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t + b; return -c/2 * ((--t)*(t-2) - 1) + b; }, easeInCubic: function (x, t, b, c, d) { return c*(t/=d)*t*t + b; }, easeOutCubic: function (x, t, b, c, d) { return c*((t=t/d-1)*t*t + 1) + b; }, easeInOutCubic: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t + b; return c/2*((t-=2)*t*t + 2) + b; }, easeInQuart: function (x, t, b, c, d) { return c*(t/=d)*t*t*t + b; }, easeOutQuart: function (x, t, b, c, d) { return -c * ((t=t/d-1)*t*t*t - 1) + b; }, easeInOutQuart: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t*t + b; return -c/2 * ((t-=2)*t*t*t - 2) + b; }, easeInQuint: function (x, t, b, c, d) { return c*(t/=d)*t*t*t*t + b; }, easeOutQuint: function (x, t, b, c, d) { return c*((t=t/d-1)*t*t*t*t + 1) + b; }, easeInOutQuint: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b; return c/2*((t-=2)*t*t*t*t + 2) + b; }, easeInSine: function (x, t, b, c, d) { return -c * Math.cos(t/d * (Math.PI/2)) + c + b; }, easeOutSine: function (x, t, b, c, d) { return c * Math.sin(t/d * (Math.PI/2)) + b; }, easeInOutSine: function (x, t, b, c, d) { return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b; }, easeInExpo: function (x, t, b, c, d) { return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b; }, easeOutExpo: function (x, t, b, c, d) { return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b; }, easeInOutExpo: function (x, t, b, c, d) { if (t==0) return b; if (t==d) return b+c; if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b; return c/2 * (-Math.pow(2, -10 * --t) + 2) + b; }, easeInCirc: function (x, t, b, c, d) { return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b; }, easeOutCirc: function (x, t, b, c, d) { return c * Math.sqrt(1 - (t=t/d-1)*t) + b; }, easeInOutCirc: function (x, t, b, c, d) { if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b; return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b; }, easeInElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; }, easeOutElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b; }, easeInOutElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5); if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b; }, easeInBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; return c*(t/=d)*t*((s+1)*t - s) + b; }, easeOutBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; }, easeInOutBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b; return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; }, easeInBounce: function (x, t, b, c, d) { return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b; }, easeOutBounce: function (x, t, b, c, d) { if ((t/=d) < (1/2.75)) { return c*(7.5625*t*t) + b; } else if (t < (2/2.75)) { return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b; } else if (t < (2.5/2.75)) { return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b; } else { return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b; } }, easeInOutBounce: function (x, t, b, c, d) { if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b; return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b; } }); /* * * TERMS OF USE - EASING EQUATIONS * * Open source under the BSD License. * * Copyright © 2001 Robert Penner * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the author nor the names of contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */
JavaScript
/***************************************************************************** Copyright (C) 2006 Nick Baicoianu This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *****************************************************************************/ //constructor for the main Epoch class (ENGLISH VERSION) function Epoch(name,mode,targetelement,multiselect,minYear,maxYear) { this.state = 0; this.name = name; this.curDate = new Date(); this.mode = mode; this.selectMultiple = (multiselect == true); //'false' is not true or not set at all //the various calendar variables //this.selectedDate = this.curDate; this.selectedDates = new Array(); this.calendar; this.calHeading; this.calCells; this.rows; this.cols; this.cells = new Array(); //The controls this.monthSelect; this.yearSelect; //standard initializations this.mousein = false; this.calConfig(minYear,maxYear); this.setDays(); this.displayYear = this.displayYearInitial; this.displayMonth = this.displayMonthInitial; this.createCalendar(); //create the calendar DOM element and its children, and their related objects if(this.mode == 'popup' && targetelement && targetelement.type == 'text') //if the target element has been set to be an input text box { this.tgt = targetelement; this.calendar.style.position = 'absolute'; this.topOffset = this.tgt.offsetHeight; // the vertical distance (in pixels) to display the calendar from the Top of its input element this.leftOffset = 0; // the horizontal distance (in pixels) to display the calendar from the Left of its input element this.calendar.style.top = this.getTop(targetelement) + this.topOffset + 'px'; this.calendar.style.left = this.getLeft(targetelement) + this.leftOffset + 'px'; document.body.appendChild(this.calendar); this.tgt.calendar = this; this.tgt.onfocus = function () {this.calendar.show();}; //the calendar will popup when the input element is focused this.tgt.onblur = function () {if(!this.calendar.mousein){this.calendar.hide();}}; //the calendar will popup when the input element is focused } else { this.container = targetelement; this.container.appendChild(this.calendar); } this.state = 2; //0: initializing, 1: redrawing, 2: finished! this.visible ? this.show() : this.hide(); } //----------------------------------------------------------------------------- Epoch.prototype.calConfig = function (minYear,maxYear) //PRIVATE: initialize calendar variables { //this.mode = 'flat'; //can be 'flat' or 'popup' this.displayYearInitial = this.curDate.getFullYear(); //the initial year to display on load this.displayMonthInitial = this.curDate.getMonth(); //the initial month to display on load (0-11) this.rangeYearLower = minYear; this.rangeYearUpper = maxYear; this.minDate = new Date(minYear,0,1); this.maxDate = new Date(maxYear,0,1); this.startDay = 0; // the day the week will 'start' on: 0(Sun) to 6(Sat) this.showWeeks = true; //whether the week numbers will be shown this.selCurMonthOnly = false; //allow user to only select dates in the currently displayed month this.clearSelectedOnChange = true; //whether to clear all selected dates when changing months //flat mode-only settings: //this.selectMultiple = true; //whether the user can select multiple dates (flat mode only) switch(this.mode) //set the variables based on the calendar mode { case 'popup': //popup options this.visible = false; break; case 'flat': this.visible = true; break; } this.setLang(); }; //----------------------------------------------------------------------------- Epoch.prototype.setLang = function() //all language settings for Epoch are made here. Check Date.dateFormat() for the Date object's language settings { this.daylist = new Array('Su','Mo','Tu','We','Th','Fr','Sa','Su','Mo','Tu','We','Th','Fr','Sa'); /*<lang:en>*/ this.months_sh = new Array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'); this.monthup_title = 'Go to the next month'; this.monthdn_title = 'Go to the previous month'; this.clearbtn_caption = 'Clear'; this.clearbtn_title = 'Clears any dates selected on the calendar'; this.maxrange_caption = 'This is the maximum range'; }; //----------------------------------------------------------------------------- Epoch.prototype.getTop = function (element) //PRIVATE: returns the absolute Top value of element, in pixels { var oNode = element; var iTop = 0; while(oNode.tagName != 'BODY') { iTop += oNode.offsetTop; oNode = oNode.offsetParent; } return iTop; }; //----------------------------------------------------------------------------- Epoch.prototype.getLeft = function (element) //PRIVATE: returns the absolute Left value of element, in pixels { var oNode = element; var iLeft = 0; while(oNode.tagName != 'BODY') { iLeft += oNode.offsetLeft; oNode = oNode.offsetParent; } return iLeft; }; //----------------------------------------------------------------------------- Epoch.prototype.show = function () //PUBLIC: displays the calendar { this.calendar.style.display = 'block'; this.visible = true; }; //----------------------------------------------------------------------------- Epoch.prototype.hide = function () //PUBLIC: Hides the calendar { this.calendar.style.display = 'none'; this.visible = false; }; //----------------------------------------------------------------------------- Epoch.prototype.toggle = function () //PUBLIC: Toggles (shows/hides) the calendar depending on its current state { if(this.visible) { this.hide(); } else { this.show(); } }; //----------------------------------------------------------------------------- Epoch.prototype.setDays = function () //PRIVATE: initializes the standard Gregorian Calendar parameters { this.daynames = new Array(); var j=0; for(var i=this.startDay; i< this.startDay + 7;i++) { this.daynames[j++] = this.daylist[i]; } this.monthDayCount = new Array(31,((this.curDate.getFullYear() - 2000) % 4 ? 28 : 29),31,30,31,30,31,31,30,31,30,31); }; //----------------------------------------------------------------------------- Epoch.prototype.setClass = function (element,className) //PRIVATE: sets the CSS class of the element, W3C & IE { element.setAttribute('class',className); element.setAttribute('className',className); //<iehack> }; //----------------------------------------------------------------------------- Epoch.prototype.createCalendar = function () //PRIVATE: creates the full DOM implementation of the calendar { var tbody, tr, td; this.calendar = document.createElement('table'); this.calendar.setAttribute('id',this.name+'_calendar'); this.setClass(this.calendar,'calendar'); //to prevent IE from selecting text when clicking on the calendar this.calendar.onselectstart = function() {return false;}; this.calendar.ondrag = function() {return false;}; tbody = document.createElement('tbody'); //create the Main Calendar Heading tr = document.createElement('tr'); td = document.createElement('td'); td.appendChild(this.createMainHeading()); tr.appendChild(td); tbody.appendChild(tr); //create the calendar Day Heading tr = document.createElement('tr'); td = document.createElement('td'); td.appendChild(this.createDayHeading()); tr.appendChild(td); tbody.appendChild(tr); //create the calendar Day Cells tr = document.createElement('tr'); td = document.createElement('td'); td.setAttribute('id',this.name+'_cell_td'); this.calCellContainer = td; //used as a handle for manipulating the calendar cells as a whole td.appendChild(this.createCalCells()); tr.appendChild(td); tbody.appendChild(tr); //create the calendar footer tr = document.createElement('tr'); td = document.createElement('td'); td.appendChild(this.createFooter()); tr.appendChild(td); tbody.appendChild(tr); //add the tbody element to the main calendar table this.calendar.appendChild(tbody); //and add the onmouseover events to the calendar table this.calendar.owner = this; this.calendar.onmouseover = function() {this.owner.mousein = true;}; this.calendar.onmouseout = function() {this.owner.mousein = false;}; }; //----------------------------------------------------------------------------- Epoch.prototype.createMainHeading = function () //PRIVATE: Creates the primary calendar heading, with months & years { //create the containing <div> element var container = document.createElement('div'); container.setAttribute('id',this.name+'_mainheading'); this.setClass(container,'mainheading'); //create the child elements and other variables this.monthSelect = document.createElement('select'); this.yearSelect = document.createElement('select'); var monthDn = document.createElement('input'), monthUp = document.createElement('input'); var opt, i; //fill the month select box for(i=0;i<12;i++) { opt = document.createElement('option'); opt.setAttribute('value',i); if(this.state == 0 && this.displayMonth == i) { opt.setAttribute('selected','selected'); } opt.appendChild(document.createTextNode(this.months_sh[i])); this.monthSelect.appendChild(opt); } //and fill the year select box for(i=this.rangeYearLower;i<=this.rangeYearUpper;i++) { opt = document.createElement('option'); opt.setAttribute('value',i); if(this.state == 0 && this.displayYear == i) { opt.setAttribute('selected','selected'); } opt.appendChild(document.createTextNode(i)); this.yearSelect.appendChild(opt); } //add the appropriate children for the month buttons monthUp.setAttribute('type','button'); monthUp.setAttribute('value','>'); monthUp.setAttribute('title',this.monthup_title); monthDn.setAttribute('type','button'); monthDn.setAttribute('value','<'); monthDn.setAttribute('title',this.monthdn_title); this.monthSelect.owner = this.yearSelect.owner = monthUp.owner = monthDn.owner = this; //hack to allow us to access this calendar in the events (<fix>??) //assign the event handlers for the controls monthUp.onmouseup = function () {this.owner.nextMonth();}; monthDn.onmouseup = function () {this.owner.prevMonth();}; this.monthSelect.onchange = function() { this.owner.displayMonth = this.value; this.owner.displayYear = this.owner.yearSelect.value; this.owner.goToMonth(this.owner.displayYear,this.owner.displayMonth); }; this.yearSelect.onchange = function() { this.owner.displayMonth = this.owner.monthSelect.value; this.owner.displayYear = this.value; this.owner.goToMonth(this.owner.displayYear,this.owner.displayMonth); }; //and finally add the elements to the containing div container.appendChild(monthDn); container.appendChild(this.monthSelect); container.appendChild(this.yearSelect); container.appendChild(monthUp); return container; }; //----------------------------------------------------------------------------- Epoch.prototype.createFooter = function () //PRIVATE: creates the footer of the calendar - goes under the calendar cells { var container = document.createElement('div'); var clearSelected = document.createElement('input'); clearSelected.setAttribute('type','button'); clearSelected.setAttribute('value',this.clearbtn_caption); clearSelected.setAttribute('title',this.clearbtn_title); clearSelected.owner = this; clearSelected.onclick = function() { this.owner.resetSelections(false);}; container.appendChild(clearSelected); return container; }; //----------------------------------------------------------------------------- Epoch.prototype.resetSelections = function (returnToDefaultMonth) //PRIVATE: reset the calendar's selection variables to defaults { this.selectedDates = new Array(); this.rows = new Array(false,false,false,false,false,false,false); this.cols = new Array(false,false,false,false,false,false,false); if(this.tgt) //if there is a target element, clear it too { this.tgt.value = ''; if(this.mode == 'popup') {//hide the calendar if in popup mode this.hide(); } } if(returnToDefaultMonth == true) { this.goToMonth(this.displayYearInitial,this.displayMonthInitial); } else { this.reDraw(); } }; //----------------------------------------------------------------------------- Epoch.prototype.createDayHeading = function () //PRIVATE: creates the heading containing the day names { //create the table element this.calHeading = document.createElement('table'); this.calHeading.setAttribute('id',this.name+'_caldayheading'); this.setClass(this.calHeading,'caldayheading'); var tbody,tr,td; tbody = document.createElement('tbody'); tr = document.createElement('tr'); this.cols = new Array(false,false,false,false,false,false,false); //if we're showing the week headings, create an empty <td> for filler if(this.showWeeks) { td = document.createElement('td'); td.setAttribute('class','wkhead'); td.setAttribute('className','wkhead'); //<iehack> tr.appendChild(td); } //populate the day titles for(var dow=0;dow<7;dow++) { td = document.createElement('td'); td.appendChild(document.createTextNode(this.daynames[dow])); if(this.selectMultiple) { //if selectMultiple is true, assign the cell a CalHeading Object to handle all events td.headObj = new CalHeading(this,td,(dow + this.startDay < 7 ? dow + this.startDay : dow + this.startDay - 7)); } tr.appendChild(td); } tbody.appendChild(tr); this.calHeading.appendChild(tbody); return this.calHeading; }; //----------------------------------------------------------------------------- Epoch.prototype.createCalCells = function () //PRIVATE: creates the table containing the calendar day cells { this.rows = new Array(false,false,false,false,false,false); this.cells = new Array(); var row = -1, totalCells = (this.showWeeks ? 48 : 42); var beginDate = new Date(this.displayYear,this.displayMonth,1); var endDate = new Date(this.displayYear,this.displayMonth,this.monthDayCount[this.displayMonth]); var sdt = new Date(beginDate); sdt.setDate(sdt.getDate() + (this.startDay - beginDate.getDay()) - (this.startDay - beginDate.getDay() > 0 ? 7 : 0) ); //create the table element this.calCells = document.createElement('table'); this.calCells.setAttribute('id',this.name+'_calcells'); this.setClass(this.calCells,'calcells'); var tbody,tr,td; tbody = document.createElement('tbody'); for(var i=0;i<totalCells;i++) { if(this.showWeeks) //if we are showing the week headings { if(i % 8 == 0) { row++; tr = document.createElement('tr'); td = document.createElement('td'); if(this.selectMultiple) { //if selectMultiple is enabled, create the associated weekObj objects td.weekObj = new WeekHeading(this,td,sdt.getWeek(),row) } else //otherwise just set the class of the td for consistent look { td.setAttribute('class','wkhead'); td.setAttribute('className','wkhead'); //<iehack> } td.appendChild(document.createTextNode(sdt.getWeek())); tr.appendChild(td); i++; } } else if(i % 7 == 0) //otherwise, new row every 7 cells { row++; tr = document.createElement('tr'); } //create the day cells td = document.createElement('td'); td.appendChild(document.createTextNode(sdt.getDate()));// +' ' +sdt.getUeDay())); var cell = new CalCell(this,td,sdt,row); this.cells.push(cell); td.cellObj = cell; sdt.setDate(sdt.getDate() + 1); //increment the date tr.appendChild(td); tbody.appendChild(tr); } this.calCells.appendChild(tbody); this.reDraw(); return this.calCells; }; //----------------------------------------------------------------------------- Epoch.prototype.reDraw = function () //PRIVATE: reapplies all the CSS classes for the calendar cells, usually called after chaning their state { this.state = 1; var i,j; for(i=0;i<this.cells.length;i++) { this.cells[i].selected = false; } for(i=0;i<this.cells.length;i++) { for(j=0;j<this.selectedDates.length;j++) { //if the cell's date is in the selectedDates array, set its selected property to true if(this.cells[i].date.getUeDay() == this.selectedDates[j].getUeDay() ) { this.cells[i].selected = true; } } this.cells[i].setClass(); } //alert(this.selectedDates); this.state = 2; }; //----------------------------------------------------------------------------- Epoch.prototype.deleteCells = function () //PRIVATE: removes the calendar cells from the DOM (does not delete the cell objects associated with them { this.calCellContainer.removeChild(this.calCellContainer.firstChild); //get a handle on the cell table (optional - for less indirection) this.cells = new Array(); //reset the cells array }; //----------------------------------------------------------------------------- Epoch.prototype.goToMonth = function (year,month) //PUBLIC: sets the calendar to display the requested month/year { this.monthSelect.value = this.displayMonth = month; this.yearSelect.value = this.displayYear = year; this.deleteCells(); this.calCellContainer.appendChild(this.createCalCells()); }; //----------------------------------------------------------------------------- Epoch.prototype.nextMonth = function () //PUBLIC: go to the next month. if the month is december, go to january of the next year { //increment the month/year values, provided they're within the min/max ranges if(this.monthSelect.value < 11) { this.monthSelect.value++; } else { if(this.yearSelect.value < this.rangeYearUpper) { this.monthSelect.value = 0; this.yearSelect.value++; } else { alert(this.maxrange_caption); } } //assign the currently displaying month/year values this.displayMonth = this.monthSelect.value; this.displayYear = this.yearSelect.value; //and refresh the calendar for the new month/year this.deleteCells(); this.calCellContainer.appendChild(this.createCalCells()); }; //----------------------------------------------------------------------------- Epoch.prototype.prevMonth = function () //PUBLIC: go to the previous month. if the month is january, go to december of the previous year { //increment the month/year values, provided they're within the min/max ranges if(this.monthSelect.value > 0) this.monthSelect.value--; else { if(this.yearSelect.value > this.rangeYearLower) { this.monthSelect.value = 11; this.yearSelect.value--; } else { alert(this.maxrange_caption); } } //assign the currently displaying month/year values this.displayMonth = this.monthSelect.value; this.displayYear = this.yearSelect.value; //and refresh the calendar for the new month/year this.deleteCells(); this.calCellContainer.appendChild(this.createCalCells()); }; //----------------------------------------------------------------------------- Epoch.prototype.addZero = function (vNumber) //PRIVATE: pads a 2 digit number with a leading zero { return ((vNumber < 10) ? '0' : '') + vNumber; }; //----------------------------------------------------------------------------- Epoch.prototype.addDates = function (dates,redraw) //PUBLIC: adds the array "dates" to the calendars selectedDates array (no duplicate dates) and redraws the calendar { var j,in_sd; for(var i=0;i<dates.length;i++) { in_sd = false; for(j=0;j<this.selectedDates.length;j++) { if(dates[i].getUeDay() == this.selectedDates[j].getUeDay()) { in_sd = true; break; } } if(!in_sd) { //if the date isn't already in the array, add it! this.selectedDates.push(dates[i]); } } if(redraw != false) {//redraw the calendar if "redraw" is false or undefined this.reDraw(); } }; //----------------------------------------------------------------------------- Epoch.prototype.removeDates = function (dates,redraw) //PUBLIC: adds the dates to the calendars selectedDates array and redraws the calendar { var j; for(var i=0;i<dates.length;i++) { for(j=0;j<this.selectedDates.length;j++) { if(dates[i].getUeDay() == this.selectedDates[j].getUeDay()) { //search for the dates in the selectedDates array, removing them if the dates match this.selectedDates.splice(j,1); } } } if(redraw != false) { //redraw the calendar if "redraw" is false or undefined this.reDraw(); } }; //----------------------------------------------------------------------------- Epoch.prototype.outputDate = function (vDate, vFormat) //PUBLIC: outputs a date in the appropriate format (DEPRECATED) { var vDay = this.addZero(vDate.getDate()); var vMonth = this.addZero(vDate.getMonth() + 1); var vYearLong = this.addZero(vDate.getFullYear()); var vYearShort = this.addZero(vDate.getFullYear().toString().substring(3,4)); var vYear = (vFormat.indexOf('yyyy') > -1 ? vYearLong : vYearShort); var vHour = this.addZero(vDate.getHours()); var vMinute = this.addZero(vDate.getMinutes()); var vSecond = this.addZero(vDate.getSeconds()); return vFormat.replace(/dd/g, vDay).replace(/mm/g, vMonth).replace(/y{1,4}/g, vYear).replace(/hh/g, vHour).replace(/nn/g, vMinute).replace(/ss/g, vSecond); }; //----------------------------------------------------------------------------- Epoch.prototype.updatePos = function (target) //PUBLIC: moves the calendar's position to target's location (popup mode only) { this.calendar.style.top = this.getTop(target) + this.topOffset + 'px' this.calendar.style.left = this.getLeft(target) + this.leftOffset + 'px' } //----------------------------------------------------------------------------- /*****************************************************************************/ function CalHeading(owner,tableCell,dow) { this.owner = owner; this.tableCell = tableCell; this.dayOfWeek = dow; //the event handlers this.tableCell.onclick = this.onclick; } //----------------------------------------------------------------------------- CalHeading.prototype.onclick = function () { //reduce indirection: var owner = this.headObj.owner; var sdates = owner.selectedDates; var cells = owner.cells; owner.cols[this.headObj.dayOfWeek] = !owner.cols[this.headObj.dayOfWeek]; for(var i=0;i<cells.length;i++) //cycle through all the cells in the calendar, selecting all cells with the same dayOfWeek as this heading { if(cells[i].dayOfWeek == this.headObj.dayOfWeek && (!owner.selCurMonthOnly || cells[i].date.getMonth() == owner.displayMonth && cells[i].date.getFullYear() == owner.displayYear)) //if the cell's DoW matches, with other conditions { if(owner.cols[this.headObj.dayOfWeek]) //if selecting, add the cell's date to the selectedDates array { if(owner.selectedDates.arrayIndex(cells[i].date) == -1) { //if the date isn't already in the array sdates.push(cells[i].date); } } else //otherwise, remove it { for(var j=0;j<sdates.length;j++) { if(cells[i].dayOfWeek == sdates[j].getDay()) { sdates.splice(j,1); //remove dates that are within the displaying month/year that have the same day of week as the day cell break; } } } cells[i].selected = owner.cols[this.headObj.dayOfWeek]; } } owner.reDraw(); }; /*****************************************************************************/ function WeekHeading(owner,tableCell,week,row) { this.owner = owner; this.tableCell = tableCell; this.week = week; this.tableRow = row; this.tableCell.setAttribute('class','wkhead'); this.tableCell.setAttribute('className','wkhead'); //<iehack> //the event handlers this.tableCell.onclick = this.onclick; } //----------------------------------------------------------------------------- WeekHeading.prototype.onclick = function () { //reduce indirection: var owner = this.weekObj.owner; var cells = owner.cells; var sdates = owner.selectedDates; var i,j; owner.rows[this.weekObj.tableRow] = !owner.rows[this.weekObj.tableRow]; for(i=0;i<cells.length;i++) { if(cells[i].tableRow == this.weekObj.tableRow) { if(owner.rows[this.weekObj.tableRow] && (!owner.selCurMonthOnly || cells[i].date.getMonth() == owner.displayMonth && cells[i].date.getFullYear() == owner.displayYear)) //match all cells in the current row, with option to restrict to current month only { if(owner.selectedDates.arrayIndex(cells[i].date) == -1) {//if the date isn't already in the array sdates.push(cells[i].date); } } else //otherwise, remove it { for(j=0;j<sdates.length;j++) { if(sdates[j].getTime() == cells[i].date.getTime()) //this.weekObj.tableRow && sdates[j].getMonth() == owner.displayMonth && sdates[j].getFullYear() == owner.displayYear) { sdates.splice(j,1); //remove dates that are within the displaying month/year that have the same day of week as the day cell break; } } } } } owner.reDraw(); }; /*****************************************************************************/ //----------------------------------------------------------------------------- function CalCell(owner,tableCell,dateObj,row) { this.owner = owner; //used primarily for event handling this.tableCell = tableCell; //the link to this cell object's table cell in the DOM this.cellClass; //the CSS class of the cell this.selected = false; //whether the cell is selected (and is therefore stored in the owner's selectedDates array) this.date = new Date(dateObj); this.dayOfWeek = this.date.getDay(); this.week = this.date.getWeek(); this.tableRow = row; //assign the event handlers for the table cell element this.tableCell.onclick = this.onclick; this.tableCell.onmouseover = this.onmouseover; this.tableCell.onmouseout = this.onmouseout; //and set the CSS class of the table cell this.setClass(); } //----------------------------------------------------------------------------- CalCell.prototype.onmouseover = function () //replicate CSS :hover effect for non-supporting browsers <iehack> { this.setAttribute('class',this.cellClass + ' hover'); this.setAttribute('className',this.cellClass + ' hover'); }; //----------------------------------------------------------------------------- CalCell.prototype.onmouseout = function () //replicate CSS :hover effect for non-supporting browsers <iehack> { this.cellObj.setClass(); }; //----------------------------------------------------------------------------- CalCell.prototype.onclick = function () { //reduce indirection: var cell = this.cellObj; var owner = cell.owner; if(!owner.selCurMonthOnly || cell.date.getMonth() == owner.displayMonth && cell.date.getFullYear() == owner.displayYear) { if(owner.selectMultiple == true) //if we can select multiple cells simultaneously, add the currently selected cell's date to the selectedDates array { if(!cell.selected) //if this cell has been selected { if(owner.selectedDates.arrayIndex(cell.date) == -1) { owner.selectedDates.push(cell.date); } } else { var tmp = owner.selectedDates; // to reduce indirection //if the cell has been deselected, remove it from the owner calendar's selectedDates array for(var i=0;i<tmp.length;i++) { if(tmp[i].getUeDay() == cell.date.getUeDay()) { tmp.splice(i,1); } } } } else //if we can only select one cell at a time { owner.selectedDates = new Array(cell.date); if(owner.tgt) //if there is a target element to place the value in, do so { owner.tgt.value = owner.selectedDates[0].dateFormat(); if(owner.mode == 'popup') { owner.hide(); } } } owner.reDraw(); //redraw the calendar cell styles to reflect the changes } }; //----------------------------------------------------------------------------- CalCell.prototype.setClass = function () //private: sets the CSS class of the cell based on the specified criteria { if(this.selected) { this.cellClass = 'cell_selected'; } else if(this.owner.displayMonth != this.date.getMonth() ) { this.cellClass = 'notmnth'; } else if(this.date.getDay() > 0 && this.date.getDay() < 6) { this.cellClass = 'wkday'; } else { this.cellClass = 'wkend'; } if(this.date.getFullYear() == this.owner.curDate.getFullYear() && this.date.getMonth() == this.owner.curDate.getMonth() && this.date.getDate() == this.owner.curDate.getDate()) { this.cellClass = this.cellClass + ' curdate'; } this.tableCell.setAttribute('class',this.cellClass); this.tableCell.setAttribute('className',this.cellClass); //<iehack> }; /*****************************************************************************/ Date.prototype.getDayOfYear = function () //returns the day of the year for this date { return parseInt((this.getTime() - new Date(this.getFullYear(),0,1).getTime())/86400000 + 1); }; //----------------------------------------------------------------------------- Date.prototype.getWeek = function () //returns the day of the year for this date { return parseInt((this.getTime() - new Date(this.getFullYear(),0,1).getTime())/604800000 + 1); }; /*function getISOWeek() { var newYear = new Date(this.getFullYear(),0,1); var modDay = newYear.getDay(); if (modDay == 0) modDay=6; else modDay--; var daynum = ((Date.UTC(this.getFullYear(),this.getMonth(),this.getDate(),0,0,0) - Date.UTC(this.getFullYear()),0,1,0,0,0)) /1000/60/60/24) + 1; if (modDay < 4 ) { var weeknum = Math.floor((daynum+modDay-1)/7)+1; } else { var weeknum = Math.floor((daynum+modDay-1)/7); if (weeknum == 0) { year--; var prevNewYear = new Date(this.getFullYear(),0,1); var prevmodDay = prevNewYear.getDay(); if (prevmodDay == 0) prevmodDay = 6; else prevmodDay--; if (prevmodDay < 4) weeknum = 53; else weeknum = 52; } } return + weeknum; }*/ //----------------------------------------------------------------------------- Date.prototype.getUeDay = function () //returns the number of DAYS since the UNIX Epoch - good for comparing the date portion { return parseInt(Math.floor((this.getTime() - this.getTimezoneOffset() * 60000)/86400000)); //must take into account the local timezone }; //----------------------------------------------------------------------------- Date.prototype.dateFormat = function(format) { if(!format) { // the default date format to use - can be customized to the current locale format = 'm/d/Y'; } LZ = function(x) {return(x < 0 || x > 9 ? '' : '0') + x}; var MONTH_NAMES = new Array('January','February','March','April','May','June','July','August','September','October','November','December','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'); var DAY_NAMES = new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sun','Mon','Tue','Wed','Thu','Fri','Sat'); format = format + ""; var result=""; var i_format=0; var c=""; var token=""; var y=this.getFullYear().toString(); var M=this.getMonth()+1; var d=this.getDate(); var E=this.getDay(); var H=this.getHours(); var m=this.getMinutes(); var s=this.getSeconds(); var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k; // Convert real this parts into formatted versions var value = new Object(); //if (y.length < 4) {y=''+(y-0+1900);} value['Y'] = y.toString(); value['y'] = y.substring(2); value['n'] = M; value['m'] = LZ(M); value['F'] = MONTH_NAMES[M-1]; value['M'] = MONTH_NAMES[M+11]; value['j'] = d; value['d'] = LZ(d); value['D'] = DAY_NAMES[E+7]; value['l'] = DAY_NAMES[E]; value['G'] = H; value['H'] = LZ(H); if (H==0) {value['g']=12;} else if (H>12){value['g']=H-12;} else {value['g']=H;} value['h']=LZ(value['g']); if (H > 11) {value['a']='pm'; value['A'] = 'PM';} else { value['a']='am'; value['A'] = 'AM';} value['i']=LZ(m); value['s']=LZ(s); //construct the result string while (i_format < format.length) { c=format.charAt(i_format); token=""; while ((format.charAt(i_format)==c) && (i_format < format.length)) { token += format.charAt(i_format++); } if (value[token] != null) { result=result + value[token]; } else { result=result + token; } } return result; }; /*****************************************************************************/ Array.prototype.arrayIndex = function(searchVal,startIndex) //similar to array.indexOf() - created to fix IE deficiencies { startIndex = (startIndex != null ? startIndex : 0); //default startIndex to 0, if not set for(var i=startIndex;i<this.length;i++) { if(searchVal == this[i]) { return i; } } return -1; }; /*****************************************************************************/
JavaScript
/* * jQuery-lazyload-any v0.1.6 * https://github.com/emn178/jquery-lazyload-any * * Copyright 2014, emn178@gmail.com * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ ;(function($, window, document, undefined) { var KEY = 'jquery-lazyload-any'; var EVENT = 'appear'; var SELECTOR_KEY = KEY + '-' + EVENT; var SELECTOR = ':' + SELECTOR_KEY; $.expr[':'][SELECTOR_KEY] = function(element) { return !!$(element).data(SELECTOR_KEY); }; function test() { var element = $(this); if(element.is(':visible') && visible(element)) element.trigger(EVENT); } function visible(element) { var rect = element[0].getBoundingClientRect(); var x1 = y1 = -element.data(KEY).threshold; var y2 = screenHeight - y1; var x2 = screenWidth - x1; return (rect.top >= y1 && rect.top <= y2 || rect.bottom >= y1 && rect.bottom <= y2) && (rect.left >= x1 && rect.left <= x2 || rect.right >= x1 && rect.right <= x2); } var screenHeight, screenWidth; function resize() { screenHeight = window.innerHeight || document.documentElement.clientHeight; screenWidth = window.innerWidth || document.documentElement.clientWidth; scroll(); } function scroll() { $(SELECTOR).each(test); } function show() { var element = $(this); var options = element.data(KEY); element.off(options.trigger); var comment = element.contents().filter(function() { return this.nodeType === 8; }).get(0); var newElement = $(comment && comment.data.trim()); element.replaceWith(newElement); if($.isFunction(options.load)) options.load.call(newElement, newElement); } $.fn.lazyload = function(options) { var opts = { threshold: 0, trigger: EVENT }; $.extend(opts, options); var trigger = opts.trigger.split(' '); this.data(SELECTOR_KEY, $.inArray(EVENT, trigger) != -1); this.data(KEY, opts); this.on(opts.trigger, show); this.each(test); }; $(document).ready(function() { $(window).on('resize', resize); $(window).on('scroll', scroll); resize(); }); })(jQuery, window, document);
JavaScript
/* * Treeview 1.5pre - jQuery plugin to hide and show branches of a tree * * http://bassistance.de/jquery-plugins/jquery-plugin-treeview/ * http://docs.jquery.com/Plugins/Treeview * * Copyright (c) 2007 Jörn Zaefferer * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Revision: $Id: jquery.treeview.js 5759 2008-07-01 07:50:28Z joern.zaefferer $ * */ ;(function($) { // TODO rewrite as a widget, removing all the extra plugins $.extend($.fn, { swapClass: function(c1, c2) { var c1Elements = this.filter('.' + c1); this.filter('.' + c2).removeClass(c2).addClass(c1); c1Elements.removeClass(c1).addClass(c2); return this; }, replaceClass: function(c1, c2) { return this.filter('.' + c1).removeClass(c1).addClass(c2).end(); }, hoverClass: function(className) { className = className || "hover"; return this.hover(function() { $(this).addClass(className); }, function() { $(this).removeClass(className); }); }, heightToggle: function(animated, callback) { animated ? this.animate({ height: "toggle" }, animated, callback) : this.each(function(){ jQuery(this)[ jQuery(this).is(":hidden") ? "show" : "hide" ](); if(callback) callback.apply(this, arguments); }); }, heightHide: function(animated, callback) { if (animated) { this.animate({ height: "hide" }, animated, callback); } else { this.hide(); if (callback) this.each(callback); } }, prepareBranches: function(settings) { if (!settings.prerendered) { // mark last tree items this.filter(":last-child:not(ul)").addClass(CLASSES.last); // collapse whole tree, or only those marked as closed, anyway except those marked as open this.filter((settings.collapsed ? "" : "." + CLASSES.closed) + ":not(." + CLASSES.open + ")").find(">ul").hide(); } // return all items with sublists return this.filter(":has(>ul)"); }, applyClasses: function(settings, toggler) { // TODO use event delegation this.filter(":has(>ul):not(:has(>a))").find(">span").unbind("click.treeview").bind("click.treeview", function(event) { // don't handle click events on children, eg. checkboxes if ( this == event.target ) toggler.apply($(this).next()); }).add( $("a", this) ).hoverClass(); if (!settings.prerendered) { // handle closed ones first this.filter(":has(>ul:hidden)") .addClass(CLASSES.expandable) .replaceClass(CLASSES.last, CLASSES.lastExpandable); // handle open ones this.not(":has(>ul:hidden)") .addClass(CLASSES.collapsable) .replaceClass(CLASSES.last, CLASSES.lastCollapsable); // create hitarea if not present var hitarea = this.find("div." + CLASSES.hitarea); if (!hitarea.length) hitarea = this.prepend("<div class=\"" + CLASSES.hitarea + "\"/>").find("div." + CLASSES.hitarea); hitarea.removeClass().addClass(CLASSES.hitarea).each(function() { var classes = ""; $.each($(this).parent().attr("class").split(" "), function() { classes += this + "-hitarea "; }); $(this).addClass( classes ); }) } // apply event to hitarea this.find("div." + CLASSES.hitarea).click( toggler ); }, treeview: function(settings) { settings = $.extend({ cookieId: "treeview" }, settings); if ( settings.toggle ) { var callback = settings.toggle; settings.toggle = function() { return callback.apply($(this).parent()[0], arguments); }; } // factory for treecontroller function treeController(tree, control) { // factory for click handlers function handler(filter) { return function() { // reuse toggle event handler, applying the elements to toggle // start searching for all hitareas toggler.apply( $("div." + CLASSES.hitarea, tree).filter(function() { // for plain toggle, no filter is provided, otherwise we need to check the parent element return filter ? $(this).parent("." + filter).length : true; }) ); return false; }; } // click on first element to collapse tree $("a:eq(0)", control).click( handler(CLASSES.collapsable) ); // click on second to expand tree $("a:eq(1)", control).click( handler(CLASSES.expandable) ); // click on third to toggle tree $("a:eq(2)", control).click( handler() ); } // handle toggle event function toggler() { $(this) .parent() // swap classes for hitarea .find(">.hitarea") .swapClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea ) .swapClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea ) .end() // swap classes for parent li .swapClass( CLASSES.collapsable, CLASSES.expandable ) .swapClass( CLASSES.lastCollapsable, CLASSES.lastExpandable ) // find child lists .find( ">ul" ) // toggle them .heightToggle( settings.animated, settings.toggle ); if ( settings.unique ) { $(this).parent() .siblings() // swap classes for hitarea .find(">.hitarea") .replaceClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea ) .replaceClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea ) .end() .replaceClass( CLASSES.collapsable, CLASSES.expandable ) .replaceClass( CLASSES.lastCollapsable, CLASSES.lastExpandable ) .find( ">ul" ) .heightHide( settings.animated, settings.toggle ); } } this.data("toggler", toggler); function serialize() { function binary(arg) { return arg ? 1 : 0; } var data = []; branches.each(function(i, e) { data[i] = $(e).is(":has(>ul:visible)") ? 1 : 0; }); $.cookie(settings.cookieId, data.join(""), settings.cookieOptions ); } function deserialize() { var stored = $.cookie(settings.cookieId); if ( stored ) { var data = stored.split(""); branches.each(function(i, e) { $(e).find(">ul")[ parseInt(data[i]) ? "show" : "hide" ](); }); } } // add treeview class to activate styles this.addClass("treeview"); // prepare branches and find all tree items with child lists var branches = this.find("li").prepareBranches(settings); switch(settings.persist) { case "cookie": var toggleCallback = settings.toggle; settings.toggle = function() { serialize(); if (toggleCallback) { toggleCallback.apply(this, arguments); } }; deserialize(); break; case "location": var current = this.find("a").filter(function() { return this.href.toLowerCase() == location.href.toLowerCase(); }); if ( current.length ) { // TODO update the open/closed classes var items = current.addClass("selected").parents("ul, li").add( current.next() ).show(); if (settings.prerendered) { // if prerendered is on, replicate the basic class swapping items.filter("li") .swapClass( CLASSES.collapsable, CLASSES.expandable ) .swapClass( CLASSES.lastCollapsable, CLASSES.lastExpandable ) .find(">.hitarea") .swapClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea ) .swapClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea ); } } break; } branches.applyClasses(settings, toggler); // if control option is set, create the treecontroller and show it if ( settings.control ) { treeController(this, settings.control); $(settings.control).show(); } return this; } }); // classes used by the plugin // need to be styled via external stylesheet, see first example $.treeview = {}; var CLASSES = ($.treeview.classes = { open: "open", closed: "closed", expandable: "expandable", expandableHitarea: "expandable-hitarea", lastExpandableHitarea: "lastExpandable-hitarea", collapsable: "collapsable", collapsableHitarea: "collapsable-hitarea", lastCollapsableHitarea: "lastCollapsable-hitarea", lastCollapsable: "lastCollapsable", lastExpandable: "lastExpandable", last: "last", hitarea: "hitarea" }); })(jQuery);
JavaScript
(function(root, factory) { if(typeof exports === 'object') { module.exports = factory(); } else if(typeof define === 'function' && define.amd) { define('salvattore', [], factory); } else { root.salvattore = factory(); } }(this, function() { /*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas, David Knight. Dual MIT/BSD license */ window.matchMedia || (window.matchMedia = function() { "use strict"; // For browsers that support matchMedium api such as IE 9 and webkit var styleMedia = (window.styleMedia || window.media); // For those that don't support matchMedium if (!styleMedia) { var style = document.createElement('style'), script = document.getElementsByTagName('script')[0], info = null; style.type = 'text/css'; style.id = 'matchmediajs-test'; script.parentNode.insertBefore(style, script); // 'style.currentStyle' is used by IE <= 8 and 'window.getComputedStyle' for all other browsers info = ('getComputedStyle' in window) && window.getComputedStyle(style, null) || style.currentStyle; styleMedia = { matchMedium: function(media) { var text = '@media ' + media + '{ #matchmediajs-test { width: 1px; } }'; // 'style.styleSheet' is used by IE <= 8 and 'style.textContent' for all other browsers if (style.styleSheet) { style.styleSheet.cssText = text; } else { style.textContent = text; } // Test if media query is true or false return info.width === '1px'; } }; } return function(media) { return { matches: styleMedia.matchMedium(media || 'all'), media: media || 'all' }; }; }()); ;/*! matchMedia() polyfill addListener/removeListener extension. Author & copyright (c) 2012: Scott Jehl. Dual MIT/BSD license */ (function(){ // Bail out for browsers that have addListener support if (window.matchMedia && window.matchMedia('all').addListener) { return false; } var localMatchMedia = window.matchMedia, hasMediaQueries = localMatchMedia('only all').matches, isListening = false, timeoutID = 0, // setTimeout for debouncing 'handleChange' queries = [], // Contains each 'mql' and associated 'listeners' if 'addListener' is used handleChange = function(evt) { // Debounce clearTimeout(timeoutID); timeoutID = setTimeout(function() { for (var i = 0, il = queries.length; i < il; i++) { var mql = queries[i].mql, listeners = queries[i].listeners || [], matches = localMatchMedia(mql.media).matches; // Update mql.matches value and call listeners // Fire listeners only if transitioning to or from matched state if (matches !== mql.matches) { mql.matches = matches; for (var j = 0, jl = listeners.length; j < jl; j++) { listeners[j].call(window, mql); } } } }, 30); }; window.matchMedia = function(media) { var mql = localMatchMedia(media), listeners = [], index = 0; mql.addListener = function(listener) { // Changes would not occur to css media type so return now (Affects IE <= 8) if (!hasMediaQueries) { return; } // Set up 'resize' listener for browsers that support CSS3 media queries (Not for IE <= 8) // There should only ever be 1 resize listener running for performance if (!isListening) { isListening = true; window.addEventListener('resize', handleChange, true); } // Push object only if it has not been pushed already if (index === 0) { index = queries.push({ mql : mql, listeners : listeners }); } listeners.push(listener); }; mql.removeListener = function(listener) { for (var i = 0, il = listeners.length; i < il; i++){ if (listeners[i] === listener){ listeners.splice(i, 1); } } }; return mql; }; }()); ;// http://paulirish.com/2011/requestanimationframe-for-smart-animating/ // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating // requestAnimationFrame polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel // MIT license (function() { var lastTime = 0; var vendors = ['ms', 'moz', 'webkit', 'o']; for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame']; window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame']; } if (!window.requestAnimationFrame) window.requestAnimationFrame = function(callback, element) { var currTime = new Date().getTime(); var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; if (!window.cancelAnimationFrame) window.cancelAnimationFrame = function(id) { clearTimeout(id); }; }()); ;var salvattore = (function (global, document, undefined) { "use strict"; var self = {}, grids = [], add_to_dataset = function(element, key, value) { // uses dataset function or a fallback for <ie10 if (element.dataset) { element.dataset[key] = value; } else { element.setAttribute("data-" + key, value); } return; }; self.obtain_grid_settings = function obtain_grid_settings(element) { // returns the number of columns and the classes a column should have, // from computing the style of the ::before pseudo-element of the grid. var computedStyle = global.getComputedStyle(element, ":before") , content = computedStyle.getPropertyValue("content").slice(1, -1) , matchResult = content.match(/^\s*(\d+)(?:\s?\.(.+))?\s*$/) , numberOfColumns , columnClasses ; if (matchResult) { numberOfColumns = matchResult[1]; columnClasses = matchResult[2]; columnClasses = columnClasses? columnClasses.split(".") : ["column"]; } else { matchResult = content.match(/^\s*\.(.+)\s+(\d+)\s*$/); columnClasses = matchResult[1]; numberOfColumns = matchResult[2]; if (numberOfColumns) { numberOfColumns = numberOfColumns.split("."); } } return { numberOfColumns: numberOfColumns, columnClasses: columnClasses }; }; self.add_columns = function add_columns(grid, items) { // from the settings obtained, it creates columns with // the configured classes and adds to them a list of items. var settings = self.obtain_grid_settings(grid) , numberOfColumns = settings.numberOfColumns , columnClasses = settings.columnClasses , columnsItems = new Array(+numberOfColumns) , columnsFragment = document.createDocumentFragment() , i = numberOfColumns , selector ; while (i-- !== 0) { selector = "[data-columns] > *:nth-child(" + numberOfColumns + "n-" + i + ")"; columnsItems.push(items.querySelectorAll(selector)); } columnsItems.forEach(function append_to_grid_fragment(rows) { var column = document.createElement("div") , rowsFragment = document.createDocumentFragment() ; column.className = columnClasses.join(" "); Array.prototype.forEach.call(rows, function append_to_column(row) { rowsFragment.appendChild(row); }); column.appendChild(rowsFragment); columnsFragment.appendChild(column); }); grid.appendChild(columnsFragment); add_to_dataset(grid, 'columns', numberOfColumns); }; self.remove_columns = function remove_columns(grid) { // removes all the columns from a grid, and returns a list // of items sorted by the ordering of columns. var range = document.createRange(); range.selectNodeContents(grid); var columns = Array.prototype.filter.call(range.extractContents().childNodes, function filter_elements(node) { return node instanceof global.HTMLElement; }); var numberOfColumns = columns.length , numberOfRowsInFirstColumn = columns[0].childNodes.length , sortedRows = new Array(numberOfRowsInFirstColumn * numberOfColumns) ; Array.prototype.forEach.call(columns, function iterate_columns(column, columnIndex) { Array.prototype.forEach.call(column.children, function iterate_rows(row, rowIndex) { sortedRows[rowIndex * numberOfColumns + columnIndex] = row; }); }); var container = document.createElement("div"); add_to_dataset(container, 'columns', 0); sortedRows.filter(function filter_non_null(child) { return !!child; }).forEach(function append_row(child) { container.appendChild(child); }); return container; }; self.recreate_columns = function recreate_columns(grid) { // removes all the columns from the grid, and adds them again, // it is used when the number of columns change. global.requestAnimationFrame(function render_after_css_media_query_change() { self.add_columns(grid, self.remove_columns(grid)); }); }; self.media_query_change = function media_query_change(mql) { // recreates the columns when a media query matches the current state // of the browser. if (mql.matches) { Array.prototype.forEach.call(grids, self.recreate_columns); } }; self.get_css_rules = function get_css_rules(stylesheet) { // returns a list of css rules from a stylesheet var cssRules; try { cssRules = stylesheet.sheet.cssRules || stylesheet.sheet.rules; } catch (e) { return []; } return cssRules || []; }; self.get_stylesheets = function get_stylesheets() { // returns a list of all the styles in the document (that are accessible). return Array.prototype.concat.call( Array.prototype.slice.call(document.querySelectorAll("style[type='text/css']")), Array.prototype.slice.call(document.querySelectorAll("link[rel='stylesheet']")) ); }; self.media_rule_has_columns_selector = function media_rule_has_columns_selector(rules) { // checks if a media query css rule has in its contents a selector that // styles the grid. var i = rules.length , rule ; while (i--) { rule = rules[i]; if (rule.selectorText && rule.selectorText.match(/\[data-columns\](.*)::?before$/)) { return true; } } return false; }; self.scan_media_queries = function scan_media_queries() { // scans all the stylesheets for selectors that style grids, // if the matchMedia API is supported. var mediaQueries = []; if (!global.matchMedia) { return; } self.get_stylesheets().forEach(function extract_rules(stylesheet) { Array.prototype.forEach.call(self.get_css_rules(stylesheet), function filter_by_column_selector(rule) { if (rule.media && self.media_rule_has_columns_selector(rule.cssRules)) { mediaQueries.push(global.matchMedia(rule.media.mediaText)); } }); }); mediaQueries.forEach(function listen_to_changes(mql) { mql.addListener(self.media_query_change); }); }; self.next_element_column_index = function next_element_column_index(grid, fragments) { // returns the index of the column where the given element must be added. var children = grid.children , m = children.length , lowestRowCount = 0 , child , currentRowCount , i , index = 0 ; for (i = 0; i < m; i++) { child = children[i]; currentRowCount = child.children.length + fragments[i].children.length; if(lowestRowCount === 0) { lowestRowCount = currentRowCount; } if(currentRowCount < lowestRowCount) { index = i; lowestRowCount = currentRowCount; } } return index; }; self.create_list_of_fragments = function create_list_of_fragments(quantity) { // returns a list of fragments var fragments = new Array(quantity) , i = 0 ; while (i !== quantity) { fragments[i] = document.createDocumentFragment(); i++; } return fragments; }; self.append_elements = function append_elements(grid, elements) { // adds a list of elements to the end of a grid var columns = grid.children , numberOfColumns = columns.length , fragments = self.create_list_of_fragments(numberOfColumns) ; elements.forEach(function append_to_next_fragment(element) { var columnIndex = self.next_element_column_index(grid, fragments); fragments[columnIndex].appendChild(element); }); Array.prototype.forEach.call(columns, function insert_column(column, index) { column.appendChild(fragments[index]); }); }; self.prepend_elements = function prepend_elements(grid, elements) { // adds a list of elements to the start of a grid var columns = grid.children , numberOfColumns = columns.length , fragments = self.create_list_of_fragments(numberOfColumns) , columnIndex = numberOfColumns - 1 ; elements.forEach(function append_to_next_fragment(element) { var fragment = fragments[columnIndex]; fragment.insertBefore(element, fragment.firstChild); if (columnIndex === 0) { columnIndex = numberOfColumns - 1; } else { columnIndex--; } }); Array.prototype.forEach.call(columns, function insert_column(column, index) { column.insertBefore(fragments[index], column.firstChild); }); // populates a fragment with n columns till the right var fragment = document.createDocumentFragment() , numberOfColumnsToExtract = elements.length % numberOfColumns ; while (numberOfColumnsToExtract-- !== 0) { fragment.appendChild(grid.lastChild); } // adds the fragment to the left grid.insertBefore(fragment, grid.firstChild); }; self.register_grid = function register_grid (grid) { if (global.getComputedStyle(grid).display === "none") { return; } // retrieve the list of items from the grid itself var range = document.createRange(); range.selectNodeContents(grid); var items = document.createElement("div"); items.appendChild(range.extractContents()); add_to_dataset(items, 'columns', 0); self.add_columns(grid, items); grids.push(grid); }; self.init = function init() { // adds required CSS rule to hide 'content' based // configuration. var css = document.createElement("style"); css.innerHTML = "[data-columns]::before{visibility:hidden;position:absolute;font-size:1px;}"; document.head.appendChild(css); // scans all the grids in the document and generates // columns from their configuration. var gridElements = document.querySelectorAll("[data-columns]"); Array.prototype.forEach.call(gridElements, self.register_grid); self.scan_media_queries(); }; self.init(); return { append_elements: self.append_elements, prepend_elements: self.prepend_elements, register_grid: self.register_grid }; })(window, window.document); return salvattore; }));
JavaScript
(function(){ //get the background-color for each tile and apply it as background color for the cooresponding screen $('.tile').each(function(){ var $this= $(this), page = $this.data('page-name'), bgcolor = $this.css('background-color'), textColor = $this.css('color'); //if the tile rotates, we'll use the colors of the front face if($this.hasClass('rotate3d')) { frontface = $this.find('.front'); bgcolor = frontface.css('background-color'); textColor = frontface.css('color'); } //if the tile has an image and a caption, we'll use the caption styles if($this.hasClass('fig-tile')) { caption = $this.find('figcaption'); bgcolor = caption.css('background-color'); textColor = caption.css('color'); } $this.on('click',function(){ $('.'+page).css({'background-color': bgcolor, 'color': textColor}) .find('.close-button').css({'background-color': textColor, 'color': bgcolor}); }); }); function showDashBoard(){ for(var i = 1; i <= 3; i++) { $('.col'+i).each(function(){ $(this).addClass('fadeInForward-'+i).removeClass('fadeOutback'); }); } } function fadeDashBoard(){ for(var i = 1; i <= 3; i++) { $('.col'+i).addClass('fadeOutback').removeClass('fadeInForward-'+i); } } //listen for when a tile is clicked //retrieve the type of page it opens from its data attribute //based on the type of page, add corresponding class to page and fade the dashboard $('.tile').each(function(){ var $this= $(this), pageType = $this.data('page-type'), page = $this.data('page-name'); $this.on('click',function(){ if(pageType === "s-page"){ fadeDashBoard(); $('.'+page).addClass('slidePageInFromLeft').removeClass('slidePageBackLeft'); } else{ $('.'+page).addClass('openpage'); fadeDashBoard(); } }); }); //when a close button is clicked: //close the page //wait till the page is closed and fade dashboard back in $('.r-close-button').click(function(){ $(this).parent().addClass('slidePageLeft') .one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e) { $(this).removeClass('slidePageLeft').removeClass('openpage'); }); showDashBoard(); }); $('.s-close-button').click(function(){ $(this).parent().removeClass('slidePageInFromLeft').addClass('slidePageBackLeft'); showDashBoard(); }); })();
JavaScript
/* StreamWave Flash Title Widget _ Javascript for Embedding 2008. 10. 29. scripted by MinsangK (http://minsangk.com) */ // main function function showTitle(srcUrl, srcFilename, width, height, titleStr, linkStr, hAlign, tColor) { var str = "<embed id=\"viewTitle\" name=\"viewTitle\" type=\"application/x-shockwave-flash\" src=\"" + srcUrl + srcFilename + "\" width=\"" + width + "\" height=\"" + height + "\" wmode=\"transparent\"" + " allowScriptAccess=\"always\"" + "FlashVars=\"" + "articleTitle="+ pEncode(titleStr) +"&linkTo=" + linkStr + "&hAlign=" + hAlign + "&tColor="+ tColor + "\"/>"; // window.alert(str); document.write(str); } // percent-encoding function pEncode(str) { str = str.replace(/&amp;/g, "%26"); //str = str.replace(/[&]/g, "%26"); str = str.replace(/[+]/g, "%2b"); return str; }
JavaScript
/** * Cookie plugin * * Copyright (c) 2006 Klaus Hartl (stilbuero.de) * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * */ /** * Create a cookie with the given name and value and other optional parameters. * * @example $.cookie('the_cookie', 'the_value'); * @desc Set the value of a cookie. * @example $.cookie('the_cookie', 'the_value', {expires: 7, path: '/', domain: 'jquery.com', secure: true}); * @desc Create a cookie with all available options. * @example $.cookie('the_cookie', 'the_value'); * @desc Create a session cookie. * @example $.cookie('the_cookie', null); * @desc Delete a cookie by passing null as value. * * @param String name The name of the cookie. * @param String value The value of the cookie. * @param Object options An object literal containing key/value pairs to provide optional cookie attributes. * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object. * If a negative value is specified (e.g. a date in the past), the cookie will be deleted. * If set to null or omitted, the cookie will be a session cookie and will not be retained * when the the browser exits. * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie). * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie). * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will * require a secure protocol (like HTTPS). * @type undefined * * @name $.cookie * @cat Plugins/Cookie * @author Klaus Hartl/klaus.hartl@stilbuero.de */ /** * Get the value of a cookie with the given name. * * @example $.cookie('the_cookie'); * @desc Get the value of a cookie. * * @param String name The name of the cookie. * @return The value of the cookie. * @type String * * @name $.cookie * @cat Plugins/Cookie * @author Klaus Hartl/klaus.hartl@stilbuero.de */ jQuery.cookie = function(name, value, options) { if (typeof value != 'undefined') { // name and value given, set cookie options = options || {}; if (value === null) { value = ''; options.expires = -1; } var expires = ''; if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) { var date; if (typeof options.expires == 'number') { date = new Date(); date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000)); } else { date = options.expires; } expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE } var path = options.path ? '; path=' + options.path : ''; var domain = options.domain ? '; domain=' + options.domain : ''; var secure = options.secure ? '; secure' : ''; document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join(''); } else { // only name given, get cookie var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } };
JavaScript
$(document).ready(function(){ // first example $("#browser").treeview(); // second example $("#navigation").treeview({ persist: "location", collapsed: true, unique: true }); // third example $("#red").treeview({ animated: "fast", collapsed: true, unique: true, persist: "cookie", toggle: function() { window.console && console.log("%o was toggled", this); } }); // fourth example $("#black, #gray").treeview({ control: "#treecontrol", persist: "cookie", cookieId: "treeview-black" }); });
JavaScript
/* Set the defaults for DataTables initialisation */ $.extend( true, $.fn.dataTable.defaults, { "sDom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>", "sPaginationType": "bootstrap", "oLanguage": { "sLengthMenu": "_MENU_ records per page" } } ); /* Default class modification */ $.extend( $.fn.dataTableExt.oStdClasses, { "sWrapper": "dataTables_wrapper form-inline" } ); /* API method to get paging information */ $.fn.dataTableExt.oApi.fnPagingInfo = function ( oSettings ) { return { "iStart": oSettings._iDisplayStart, "iEnd": oSettings.fnDisplayEnd(), "iLength": oSettings._iDisplayLength, "iTotal": oSettings.fnRecordsTotal(), "iFilteredTotal": oSettings.fnRecordsDisplay(), "iPage": oSettings._iDisplayLength === -1 ? 0 : Math.ceil( oSettings._iDisplayStart / oSettings._iDisplayLength ), "iTotalPages": oSettings._iDisplayLength === -1 ? 0 : Math.ceil( oSettings.fnRecordsDisplay() / oSettings._iDisplayLength ) }; }; /* Bootstrap style pagination control */ $.extend( $.fn.dataTableExt.oPagination, { "bootstrap": { "fnInit": function( oSettings, nPaging, fnDraw ) { var oLang = oSettings.oLanguage.oPaginate; var fnClickHandler = function ( e ) { e.preventDefault(); if ( oSettings.oApi._fnPageChange(oSettings, e.data.action) ) { fnDraw( oSettings ); } }; $(nPaging).addClass('pagination').append( '<ul>'+ '<li class="prev disabled"><a href="#">&larr; '+oLang.sPrevious+'</a></li>'+ '<li class="next disabled"><a href="#">'+oLang.sNext+' &rarr; </a></li>'+ '</ul>' ); var els = $('a', nPaging); $(els[0]).bind( 'click.DT', { action: "previous" }, fnClickHandler ); $(els[1]).bind( 'click.DT', { action: "next" }, fnClickHandler ); }, "fnUpdate": function ( oSettings, fnDraw ) { var iListLength = 5; var oPaging = oSettings.oInstance.fnPagingInfo(); var an = oSettings.aanFeatures.p; var i, ien, j, sClass, iStart, iEnd, iHalf=Math.floor(iListLength/2); if ( oPaging.iTotalPages < iListLength) { iStart = 1; iEnd = oPaging.iTotalPages; } else if ( oPaging.iPage <= iHalf ) { iStart = 1; iEnd = iListLength; } else if ( oPaging.iPage >= (oPaging.iTotalPages-iHalf) ) { iStart = oPaging.iTotalPages - iListLength + 1; iEnd = oPaging.iTotalPages; } else { iStart = oPaging.iPage - iHalf + 1; iEnd = iStart + iListLength - 1; } for ( i=0, ien=an.length ; i<ien ; i++ ) { // Remove the middle elements $('li:gt(0)', an[i]).filter(':not(:last)').remove(); // Add the new list items and their event handlers for ( j=iStart ; j<=iEnd ; j++ ) { sClass = (j==oPaging.iPage+1) ? 'class="active"' : ''; $('<li '+sClass+'><a href="#">'+j+'</a></li>') .insertBefore( $('li:last', an[i])[0] ) .bind('click', function (e) { e.preventDefault(); oSettings._iDisplayStart = (parseInt($('a', this).text(),10)-1) * oPaging.iLength; fnDraw( oSettings ); } ); } // Add / remove disabled classes from the static elements if ( oPaging.iPage === 0 ) { $('li:first', an[i]).addClass('disabled'); } else { $('li:first', an[i]).removeClass('disabled'); } if ( oPaging.iPage === oPaging.iTotalPages-1 || oPaging.iTotalPages === 0 ) { $('li:last', an[i]).addClass('disabled'); } else { $('li:last', an[i]).removeClass('disabled'); } } } } } ); /* * TableTools Bootstrap compatibility * Required TableTools 2.1+ */ if ( $.fn.DataTable.TableTools ) { // Set the classes that TableTools uses to something suitable for Bootstrap $.extend( true, $.fn.DataTable.TableTools.classes, { "container": "DTTT btn-group", "buttons": { "normal": "btn", "disabled": "disabled" }, "collection": { "container": "DTTT_dropdown dropdown-menu", "buttons": { "normal": "", "disabled": "disabled" } }, "print": { "info": "DTTT_print_info modal" }, "select": { "row": "active" } } ); // Have the collection use a bootstrap compatible dropdown $.extend( true, $.fn.DataTable.TableTools.DEFAULTS.oTags, { "collection": { "container": "ul", "button": "li", "liner": "a" } } ); } /* Table initialisation */ $(document).ready(function() { $('#example').dataTable( { "sDom": "<'row'<'span6'l><'span6'f>r>t<'row'<'span6'i><'span6'p>>", "sPaginationType": "bootstrap", "oLanguage": { "sLengthMenu": "_MENU_ records per page" } } ); $('#example2').dataTable( { "sDom": "<'row'<'span6'l><'span6'f>r>t<'row'<'span6'i><'span6'p>>", "sPaginationType": "bootstrap", "oLanguage": { "sLengthMenu": "_MENU_ records per page" } } ); } );
JavaScript
var FormValidation = function () { var handleValidation1 = function() { // for more info visit the official plugin documentation: // http://docs.jquery.com/Plugins/Validation var form1 = $('#form_sample_1'); var error1 = $('.alert-error', form1); var success1 = $('.alert-success', form1); form1.validate({ errorElement: 'span', //default input error message container errorClass: 'help-inline', // default input error message class focusInvalid: false, // do not focus the last invalid input ignore: "", rules: { name: { minlength: 2, required: true }, email: { required: true, email: true }, url: { required: true, url: true }, number: { required: true, number: true }, digits: { required: true, digits: true }, creditcard: { required: true, creditcard: true }, occupation: { minlength: 5, }, category: { required: true } }, invalidHandler: function (event, validator) { //display error alert on form submit success1.hide(); error1.show(); FormValidation.scrollTo(error1, -200); }, highlight: function (element) { // hightlight error inputs $(element) .closest('.help-inline').removeClass('ok'); // display OK icon $(element) .closest('.control-group').removeClass('success').addClass('error'); // set error class to the control group }, unhighlight: function (element) { // revert the change done by hightlight $(element) .closest('.control-group').removeClass('error'); // set error class to the control group }, success: function (label) { label .addClass('valid').addClass('help-inline ok') // mark the current input as valid and display OK icon .closest('.control-group').removeClass('error').addClass('success'); // set success class to the control group }, submitHandler: function (form) { success1.show(); error1.hide(); } }); } return { //main function to initiate the module init: function () { handleValidation1(); }, // wrapper function to scroll to an element scrollTo: function (el, offeset) { pos = el ? el.offset().top : 0; jQuery('html,body').animate({ scrollTop: pos + (offeset ? offeset : 0) }, 'slow'); } }; }();
JavaScript
$(function() { // Side Bar Toggle $('.hide-sidebar').click(function() { $('#sidebar').hide('fast', function() { $('#content').removeClass('span9'); $('#content').addClass('span12'); $('.hide-sidebar').hide(); $('.show-sidebar').show(); }); }); $('.show-sidebar').click(function() { $('#content').removeClass('span12'); $('#content').addClass('span9'); $('.show-sidebar').hide(); $('.hide-sidebar').show(); $('#sidebar').show('fast'); }); });
JavaScript
/** * Galleria v 1.3.6 2014-06-23 * http://galleria.io * * Licensed under the MIT license * https://raw.github.com/aino/galleria/master/LICENSE * */ (function( $, window, Galleria, undef ) { /*global jQuery, navigator, Image, module, define */ // some references var doc = window.document, $doc = $( doc ), $win = $( window ), // native prototypes protoArray = Array.prototype, // internal constants VERSION = 1.36, DEBUG = true, TIMEOUT = 30000, DUMMY = false, NAV = navigator.userAgent.toLowerCase(), HASH = window.location.hash.replace(/#\//, ''), PROT = window.location.protocol, M = Math, F = function(){}, FALSE = function() { return false; }, IE = (function() { var v = 3, div = doc.createElement( 'div' ), all = div.getElementsByTagName( 'i' ); do { div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->'; } while ( all[0] ); return v > 4 ? v : doc.documentMode || undef; }() ), DOM = function() { return { html: doc.documentElement, body: doc.body, head: doc.getElementsByTagName('head')[0], title: doc.title }; }, IFRAME = window.parent !== window.self, // list of Galleria events _eventlist = 'data ready thumbnail loadstart loadfinish image play pause progress ' + 'fullscreen_enter fullscreen_exit idle_enter idle_exit rescale ' + 'lightbox_open lightbox_close lightbox_image', _events = (function() { var evs = []; $.each( _eventlist.split(' '), function( i, ev ) { evs.push( ev ); // legacy events if ( /_/.test( ev ) ) { evs.push( ev.replace( /_/g, '' ) ); } }); return evs; }()), // legacy options // allows the old my_setting syntax and converts it to camel case _legacyOptions = function( options ) { var n; if ( typeof options !== 'object' ) { // return whatever it was... return options; } $.each( options, function( key, value ) { if ( /^[a-z]+_/.test( key ) ) { n = ''; $.each( key.split('_'), function( i, k ) { n += i > 0 ? k.substr( 0, 1 ).toUpperCase() + k.substr( 1 ) : k; }); options[ n ] = value; delete options[ key ]; } }); return options; }, _patchEvent = function( type ) { // allow 'image' instead of Galleria.IMAGE if ( $.inArray( type, _events ) > -1 ) { return Galleria[ type.toUpperCase() ]; } return type; }, // video providers _video = { youtube: { reg: /https?:\/\/(?:[a-zA_Z]{2,3}.)?(?:youtube\.com\/watch\?)((?:[\w\d\-\_\=]+&amp;(?:amp;)?)*v(?:&lt;[A-Z]+&gt;)?=([0-9a-zA-Z\-\_]+))/i, embed: function() { return 'http://www.youtube.com/embed/' + this.id; }, getUrl: function() { return PROT + '//gdata.youtube.com/feeds/api/videos/' + this.id + '?v=2&alt=json-in-script&callback=?'; }, get_thumb: function(data) { return data.entry.media$group.media$thumbnail[2].url; }, get_image: function(data) { if ( data.entry.yt$hd ) { return PROT + '//img.youtube.com/vi/'+this.id+'/maxresdefault.jpg'; } return data.entry.media$group.media$thumbnail[3].url; } }, vimeo: { reg: /https?:\/\/(?:www\.)?(vimeo\.com)\/(?:hd#)?([0-9]+)/i, embed: function() { return 'http://player.vimeo.com/video/' + this.id; }, getUrl: function() { return PROT + '//vimeo.com/api/v2/video/' + this.id + '.json?callback=?'; }, get_thumb: function( data ) { return data[0].thumbnail_medium; }, get_image: function( data ) { return data[0].thumbnail_large; } }, dailymotion: { reg: /https?:\/\/(?:www\.)?(dailymotion\.com)\/video\/([^_]+)/, embed: function() { return PROT + '//www.dailymotion.com/embed/video/' + this.id; }, getUrl: function() { return 'https://api.dailymotion.com/video/' + this.id + '?fields=thumbnail_240_url,thumbnail_720_url&callback=?'; }, get_thumb: function( data ) { return data.thumbnail_240_url; }, get_image: function( data ) { return data.thumbnail_720_url; } }, _inst: [] }, Video = function( type, id ) { for( var i=0; i<_video._inst.length; i++ ) { if ( _video._inst[i].id === id && _video._inst[i].type == type ) { return _video._inst[i]; } } this.type = type; this.id = id; this.readys = []; _video._inst.push(this); var self = this; $.extend( this, _video[type] ); $.getJSON( this.getUrl(), function(data) { self.data = data; $.each( self.readys, function( i, fn ) { fn( self.data ); }); self.readys = []; }); this.getMedia = function( type, callback, fail ) { fail = fail || F; var self = this; var success = function( data ) { callback( self['get_'+type]( data ) ); }; try { if ( self.data ) { success( self.data ); } else { self.readys.push( success ); } } catch(e) { fail(); } }; }, // utility for testing the video URL and getting the video ID _videoTest = function( url ) { var match; for ( var v in _video ) { match = url && _video[v].reg && url.match( _video[v].reg ); if( match && match.length ) { return { id: match[2], provider: v }; } } return false; }, // native fullscreen handler _nativeFullscreen = { support: (function() { var html = DOM().html; return !IFRAME && ( html.requestFullscreen || html.msRequestFullscreen || html.mozRequestFullScreen || html.webkitRequestFullScreen ); }()), callback: F, enter: function( instance, callback, elem ) { this.instance = instance; this.callback = callback || F; elem = elem || DOM().html; if ( elem.requestFullscreen ) { elem.requestFullscreen(); } else if ( elem.msRequestFullscreen ) { elem.msRequestFullscreen(); } else if ( elem.mozRequestFullScreen ) { elem.mozRequestFullScreen(); } else if ( elem.webkitRequestFullScreen ) { elem.webkitRequestFullScreen(); } }, exit: function( callback ) { this.callback = callback || F; if ( doc.exitFullscreen ) { doc.exitFullscreen(); } else if ( doc.msExitFullscreen ) { doc.msExitFullscreen(); } else if ( doc.mozCancelFullScreen ) { doc.mozCancelFullScreen(); } else if ( doc.webkitCancelFullScreen ) { doc.webkitCancelFullScreen(); } }, instance: null, listen: function() { if ( !this.support ) { return; } var handler = function() { if ( !_nativeFullscreen.instance ) { return; } var fs = _nativeFullscreen.instance._fullscreen; if ( doc.fullscreen || doc.mozFullScreen || doc.webkitIsFullScreen || ( doc.msFullscreenElement && doc.msFullscreenElement !== null ) ) { fs._enter( _nativeFullscreen.callback ); } else { fs._exit( _nativeFullscreen.callback ); } }; doc.addEventListener( 'fullscreenchange', handler, false ); doc.addEventListener( 'MSFullscreenChange', handler, false ); doc.addEventListener( 'mozfullscreenchange', handler, false ); doc.addEventListener( 'webkitfullscreenchange', handler, false ); } }, // the internal gallery holder _galleries = [], // the internal instance holder _instances = [], // flag for errors _hasError = false, // canvas holder _canvas = false, // instance pool, holds the galleries until themeLoad is triggered _pool = [], // themeLoad trigger _themeLoad = function( theme ) { Galleria.theme = theme; // run the instances we have in the pool $.each( _pool, function( i, instance ) { if ( !instance._initialized ) { instance._init.call( instance ); } }); _pool = []; }, // the Utils singleton Utils = (function() { return { // legacy support for clearTimer clearTimer: function( id ) { $.each( Galleria.get(), function() { this.clearTimer( id ); }); }, // legacy support for addTimer addTimer: function( id ) { $.each( Galleria.get(), function() { this.addTimer( id ); }); }, array : function( obj ) { return protoArray.slice.call(obj, 0); }, create : function( className, nodeName ) { nodeName = nodeName || 'div'; var elem = doc.createElement( nodeName ); elem.className = className; return elem; }, removeFromArray : function( arr, elem ) { $.each(arr, function(i, el) { if ( el == elem ) { arr.splice(i, 1); return false; } }); return arr; }, getScriptPath : function( src ) { // the currently executing script is always the last src = src || $('script:last').attr('src'); var slices = src.split('/'); if (slices.length == 1) { return ''; } slices.pop(); return slices.join('/') + '/'; }, // CSS3 transitions, added in 1.2.4 animate : (function() { // detect transition var transition = (function( style ) { var props = 'transition WebkitTransition MozTransition OTransition'.split(' '), i; // disable css3 animations in opera until stable if ( window.opera ) { return false; } for ( i = 0; props[i]; i++ ) { if ( typeof style[ props[ i ] ] !== 'undefined' ) { return props[ i ]; } } return false; }(( doc.body || doc.documentElement).style )); // map transitionend event var endEvent = { MozTransition: 'transitionend', OTransition: 'oTransitionEnd', WebkitTransition: 'webkitTransitionEnd', transition: 'transitionend' }[ transition ]; // map bezier easing conversions var easings = { _default: [0.25, 0.1, 0.25, 1], galleria: [0.645, 0.045, 0.355, 1], galleriaIn: [0.55, 0.085, 0.68, 0.53], galleriaOut: [0.25, 0.46, 0.45, 0.94], ease: [0.25, 0, 0.25, 1], linear: [0.25, 0.25, 0.75, 0.75], 'ease-in': [0.42, 0, 1, 1], 'ease-out': [0, 0, 0.58, 1], 'ease-in-out': [0.42, 0, 0.58, 1] }; // function for setting transition css for all browsers var setStyle = function( elem, value, suffix ) { var css = {}; suffix = suffix || 'transition'; $.each( 'webkit moz ms o'.split(' '), function() { css[ '-' + this + '-' + suffix ] = value; }); elem.css( css ); }; // clear styles var clearStyle = function( elem ) { setStyle( elem, 'none', 'transition' ); if ( Galleria.WEBKIT && Galleria.TOUCH ) { setStyle( elem, 'translate3d(0,0,0)', 'transform' ); if ( elem.data('revert') ) { elem.css( elem.data('revert') ); elem.data('revert', null); } } }; // various variables var change, strings, easing, syntax, revert, form, css; // the actual animation method return function( elem, to, options ) { // extend defaults options = $.extend({ duration: 400, complete: F, stop: false }, options); // cache jQuery instance elem = $( elem ); if ( !options.duration ) { elem.css( to ); options.complete.call( elem[0] ); return; } // fallback to jQuery's animate if transition is not supported if ( !transition ) { elem.animate(to, options); return; } // stop if ( options.stop ) { // clear the animation elem.off( endEvent ); clearStyle( elem ); } // see if there is a change change = false; $.each( to, function( key, val ) { css = elem.css( key ); if ( Utils.parseValue( css ) != Utils.parseValue( val ) ) { change = true; } // also add computed styles for FF elem.css( key, css ); }); if ( !change ) { window.setTimeout( function() { options.complete.call( elem[0] ); }, options.duration ); return; } // the css strings to be applied strings = []; // the easing bezier easing = options.easing in easings ? easings[ options.easing ] : easings._default; // the syntax syntax = ' ' + options.duration + 'ms' + ' cubic-bezier(' + easing.join(',') + ')'; // add a tiny timeout so that the browsers catches any css changes before animating window.setTimeout( (function(elem, endEvent, to, syntax) { return function() { // attach the end event elem.one(endEvent, (function( elem ) { return function() { // clear the animation clearStyle(elem); // run the complete method options.complete.call(elem[0]); }; }( elem ))); // do the webkit translate3d for better performance on iOS if( Galleria.WEBKIT && Galleria.TOUCH ) { revert = {}; form = [0,0,0]; $.each( ['left', 'top'], function(i, m) { if ( m in to ) { form[ i ] = ( Utils.parseValue( to[ m ] ) - Utils.parseValue(elem.css( m )) ) + 'px'; revert[ m ] = to[ m ]; delete to[ m ]; } }); if ( form[0] || form[1]) { elem.data('revert', revert); strings.push('-webkit-transform' + syntax); // 3d animate setStyle( elem, 'translate3d(' + form.join(',') + ')', 'transform'); } } // push the animation props $.each(to, function( p, val ) { strings.push(p + syntax); }); // set the animation styles setStyle( elem, strings.join(',') ); // animate elem.css( to ); }; }(elem, endEvent, to, syntax)), 2); }; }()), removeAlpha : function( elem ) { if ( elem instanceof jQuery ) { elem = elem[0]; } if ( IE < 9 && elem ) { var style = elem.style, currentStyle = elem.currentStyle, filter = currentStyle && currentStyle.filter || style.filter || ""; if ( /alpha/.test( filter ) ) { style.filter = filter.replace( /alpha\([^)]*\)/i, '' ); } } }, forceStyles : function( elem, styles ) { elem = $(elem); if ( elem.attr( 'style' ) ) { elem.data( 'styles', elem.attr( 'style' ) ).removeAttr( 'style' ); } elem.css( styles ); }, revertStyles : function() { $.each( Utils.array( arguments ), function( i, elem ) { elem = $( elem ); elem.removeAttr( 'style' ); elem.attr('style',''); // "fixes" webkit bug if ( elem.data( 'styles' ) ) { elem.attr( 'style', elem.data('styles') ).data( 'styles', null ); } }); }, moveOut : function( elem ) { Utils.forceStyles( elem, { position: 'absolute', left: -10000 }); }, moveIn : function() { Utils.revertStyles.apply( Utils, Utils.array( arguments ) ); }, hide : function( elem, speed, callback ) { callback = callback || F; var $elem = $(elem); elem = $elem[0]; // save the value if not exist if (! $elem.data('opacity') ) { $elem.data('opacity', $elem.css('opacity') ); } // always hide var style = { opacity: 0 }; if (speed) { var complete = IE < 9 && elem ? function() { Utils.removeAlpha( elem ); elem.style.visibility = 'hidden'; callback.call( elem ); } : callback; Utils.animate( elem, style, { duration: speed, complete: complete, stop: true }); } else { if ( IE < 9 && elem ) { Utils.removeAlpha( elem ); elem.style.visibility = 'hidden'; } else { $elem.css( style ); } } }, show : function( elem, speed, callback ) { callback = callback || F; var $elem = $(elem); elem = $elem[0]; // bring back saved opacity var saved = parseFloat( $elem.data('opacity') ) || 1, style = { opacity: saved }; // animate or toggle if (speed) { if ( IE < 9 ) { $elem.css('opacity', 0); elem.style.visibility = 'visible'; } var complete = IE < 9 && elem ? function() { if ( style.opacity == 1 ) { Utils.removeAlpha( elem ); } callback.call( elem ); } : callback; Utils.animate( elem, style, { duration: speed, complete: complete, stop: true }); } else { if ( IE < 9 && style.opacity == 1 && elem ) { Utils.removeAlpha( elem ); elem.style.visibility = 'visible'; } else { $elem.css( style ); } } }, wait : function(options) { Galleria._waiters = Galleria._waiters || []; options = $.extend({ until : FALSE, success : F, error : function() { Galleria.raise('Could not complete wait function.'); }, timeout: 3000 }, options); var start = Utils.timestamp(), elapsed, now, tid, fn = function() { now = Utils.timestamp(); elapsed = now - start; Utils.removeFromArray( Galleria._waiters, tid ); if ( options.until( elapsed ) ) { options.success(); return false; } if (typeof options.timeout == 'number' && now >= start + options.timeout) { options.error(); return false; } Galleria._waiters.push( tid = window.setTimeout(fn, 10) ); }; Galleria._waiters.push( tid = window.setTimeout(fn, 10) ); }, toggleQuality : function( img, force ) { if ( ( IE !== 7 && IE !== 8 ) || !img || img.nodeName.toUpperCase() != 'IMG' ) { return; } if ( typeof force === 'undefined' ) { force = img.style.msInterpolationMode === 'nearest-neighbor'; } img.style.msInterpolationMode = force ? 'bicubic' : 'nearest-neighbor'; }, insertStyleTag : function( styles, id ) { if ( id && $( '#'+id ).length ) { return; } var style = doc.createElement( 'style' ); if ( id ) { style.id = id; } DOM().head.appendChild( style ); if ( style.styleSheet ) { // IE style.styleSheet.cssText = styles; } else { var cssText = doc.createTextNode( styles ); style.appendChild( cssText ); } }, // a loadscript method that works for local scripts loadScript: function( url, callback ) { var done = false, script = $('<scr'+'ipt>').attr({ src: url, async: true }).get(0); // Attach handlers for all browsers script.onload = script.onreadystatechange = function() { if ( !done && (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete') ) { done = true; // Handle memory leak in IE script.onload = script.onreadystatechange = null; if (typeof callback === 'function') { callback.call( this, this ); } } }; DOM().head.appendChild( script ); }, // parse anything into a number parseValue: function( val ) { if (typeof val === 'number') { return val; } else if (typeof val === 'string') { var arr = val.match(/\-?\d|\./g); return arr && arr.constructor === Array ? arr.join('')*1 : 0; } else { return 0; } }, // timestamp abstraction timestamp: function() { return new Date().getTime(); }, loadCSS : function( href, id, callback ) { var link, length; // look for manual css $('link[rel=stylesheet]').each(function() { if ( new RegExp( href ).test( this.href ) ) { link = this; return false; } }); if ( typeof id === 'function' ) { callback = id; id = undef; } callback = callback || F; // dirty // if already present, return if ( link ) { callback.call( link, link ); return link; } // save the length of stylesheets to check against length = doc.styleSheets.length; // check for existing id if( $( '#' + id ).length ) { $( '#' + id ).attr( 'href', href ); length--; } else { link = $( '<link>' ).attr({ rel: 'stylesheet', href: href, id: id }).get(0); var styles = $('link[rel="stylesheet"], style'); if ( styles.length ) { styles.get(0).parentNode.insertBefore( link, styles[0] ); } else { DOM().head.appendChild( link ); } if ( IE && length >= 31 ) { Galleria.raise( 'You have reached the browser stylesheet limit (31)', true ); return; } } if ( typeof callback === 'function' ) { // First check for dummy element (new in 1.2.8) var $loader = $('<s>').attr( 'id', 'galleria-loader' ).hide().appendTo( DOM().body ); Utils.wait({ until: function() { return $loader.height() == 1; }, success: function() { $loader.remove(); callback.call( link, link ); }, error: function() { $loader.remove(); // If failed, tell the dev to download the latest theme Galleria.raise( 'Theme CSS could not load after 20 sec. ' + ( Galleria.QUIRK ? 'Your browser is in Quirks Mode, please add a correct doctype.' : 'Please download the latest theme at http://galleria.io/customer/.' ), true ); }, timeout: 5000 }); } return link; } }; }()), // play icon _playIcon = function( container ) { var css = '.galleria-videoicon{width:60px;height:60px;position:absolute;top:50%;left:50%;z-index:1;' + 'margin:-30px 0 0 -30px;cursor:pointer;background:#000;background:rgba(0,0,0,.8);border-radius:3px;-webkit-transition:all 150ms}' + '.galleria-videoicon i{width:0px;height:0px;border-style:solid;border-width:10px 0 10px 16px;display:block;' + 'border-color:transparent transparent transparent #ffffff;margin:20px 0 0 22px}.galleria-image:hover .galleria-videoicon{background:#000}'; Utils.insertStyleTag( css, 'galleria-videoicon' ); return $( Utils.create( 'galleria-videoicon' ) ).html( '<i></i>' ).appendTo( container ) .click( function() { $( this ).siblings( 'img' ).mouseup(); }); }, // the transitions holder _transitions = (function() { var _slide = function(params, complete, fade, door) { var easing = this.getOptions('easing'), distance = this.getStageWidth(), from = { left: distance * ( params.rewind ? -1 : 1 ) }, to = { left: 0 }; if ( fade ) { from.opacity = 0; to.opacity = 1; } else { from.opacity = 1; } $(params.next).css(from); Utils.animate(params.next, to, { duration: params.speed, complete: (function( elems ) { return function() { complete(); elems.css({ left: 0 }); }; }( $( params.next ).add( params.prev ) )), queue: false, easing: easing }); if (door) { params.rewind = !params.rewind; } if (params.prev) { from = { left: 0 }; to = { left: distance * ( params.rewind ? 1 : -1 ) }; if ( fade ) { from.opacity = 1; to.opacity = 0; } $(params.prev).css(from); Utils.animate(params.prev, to, { duration: params.speed, queue: false, easing: easing, complete: function() { $(this).css('opacity', 0); } }); } }; return { active: false, init: function( effect, params, complete ) { if ( _transitions.effects.hasOwnProperty( effect ) ) { _transitions.effects[ effect ].call( this, params, complete ); } }, effects: { fade: function(params, complete) { $(params.next).css({ opacity: 0, left: 0 }); Utils.animate(params.next, { opacity: 1 },{ duration: params.speed, complete: complete }); if (params.prev) { $(params.prev).css('opacity',1).show(); Utils.animate(params.prev, { opacity: 0 },{ duration: params.speed }); } }, flash: function(params, complete) { $(params.next).css({ opacity: 0, left: 0 }); if (params.prev) { Utils.animate( params.prev, { opacity: 0 },{ duration: params.speed/2, complete: function() { Utils.animate( params.next, { opacity:1 },{ duration: params.speed, complete: complete }); } }); } else { Utils.animate( params.next, { opacity: 1 },{ duration: params.speed, complete: complete }); } }, pulse: function(params, complete) { if (params.prev) { $(params.prev).hide(); } $(params.next).css({ opacity: 0, left: 0 }).show(); Utils.animate(params.next, { opacity:1 },{ duration: params.speed, complete: complete }); }, slide: function(params, complete) { _slide.apply( this, Utils.array( arguments ) ); }, fadeslide: function(params, complete) { _slide.apply( this, Utils.array( arguments ).concat( [true] ) ); }, doorslide: function(params, complete) { _slide.apply( this, Utils.array( arguments ).concat( [false, true] ) ); } } }; }()); // listen to fullscreen _nativeFullscreen.listen(); // create special click:fast event for fast touch interaction $.event.special['click:fast'] = { propagate: true, add: function(handleObj) { var getCoords = function(e) { if ( e.touches && e.touches.length ) { var touch = e.touches[0]; return { x: touch.pageX, y: touch.pageY }; } }; var def = { touched: false, touchdown: false, coords: { x:0, y:0 }, evObj: {} }; $(this).data({ clickstate: def, timer: 0 }).on('touchstart.fast', function(e) { window.clearTimeout($(this).data('timer')); $(this).data('clickstate', { touched: true, touchdown: true, coords: getCoords(e.originalEvent), evObj: e }); }).on('touchmove.fast', function(e) { var coords = getCoords(e.originalEvent), state = $(this).data('clickstate'), distance = Math.max( Math.abs(state.coords.x - coords.x), Math.abs(state.coords.y - coords.y) ); if ( distance > 6 ) { $(this).data('clickstate', $.extend(state, { touchdown: false })); } }).on('touchend.fast', function(e) { var $this = $(this), state = $this.data('clickstate'); if(state.touchdown) { handleObj.handler.call(this, e); } $this.data('timer', window.setTimeout(function() { $this.data('clickstate', def); }, 400)); }).on('click.fast', function(e) { var state = $(this).data('clickstate'); if ( state.touched ) { return false; } $(this).data('clickstate', def); handleObj.handler.call(this, e); }); }, remove: function() { $(this).off('touchstart.fast touchmove.fast touchend.fast click.fast'); } }; /* if ( Galleria.TOUCH ) { $(this).on('touchstart.fast', function start(e) { var ev = e.originalEvent, x, y, dist = 0; if ( ev.touches.length == 1 ) { x = ev.touches[0].pageX; y = ev.touches[0].pageY; $(this).on('touchmove.fast', function(f) { var ft = f.originalEvent.touches; if ( ft.length == 1 ) { dist = M.max( M.abs( x - ft[0].pageX ), M.abs( y - ft[0].pageY ) ); } }); $(this).on('touchend.fast', function() { if( dist > 4 ) { return $(this).off('touchend.fast touchmove.fast'); } handleObj.handler.call(this, e); $(this).off('touchend.fast touchmove.fast'); }); } }); } else { $(this).on('click.fast', handleObj.handler); } }, remove: function(handleObj) { if ( Galleria.TOUCH ) { $(this).off('touchstart.fast touchmove.fast touchend.fast'); } else { $(this).off('click.fast', handleObj.handler); } } }; */ // trigger resize on orientationchange (IOS7) $win.on( 'orientationchange', function() { $(this).resize(); }); /** The main Galleria class @class @constructor @example var gallery = new Galleria(); @author http://aino.se @requires jQuery */ Galleria = function() { var self = this; // internal options this._options = {}; // flag for controlling play/pause this._playing = false; // internal interval for slideshow this._playtime = 5000; // internal variable for the currently active image this._active = null; // the internal queue, arrayified this._queue = { length: 0 }; // the internal data array this._data = []; // the internal dom collection this._dom = {}; // the internal thumbnails array this._thumbnails = []; // the internal layers array this._layers = []; // internal init flag this._initialized = false; // internal firstrun flag this._firstrun = false; // global stagewidth/height this._stageWidth = 0; this._stageHeight = 0; // target holder this._target = undef; // bind hashes this._binds = []; // instance id this._id = parseInt(M.random()*10000, 10); // add some elements var divs = 'container stage images image-nav image-nav-left image-nav-right ' + 'info info-text info-title info-description ' + 'thumbnails thumbnails-list thumbnails-container thumb-nav-left thumb-nav-right ' + 'loader counter tooltip', spans = 'current total'; $.each( divs.split(' '), function( i, elemId ) { self._dom[ elemId ] = Utils.create( 'galleria-' + elemId ); }); $.each( spans.split(' '), function( i, elemId ) { self._dom[ elemId ] = Utils.create( 'galleria-' + elemId, 'span' ); }); // the internal keyboard object // keeps reference of the keybinds and provides helper methods for binding keys var keyboard = this._keyboard = { keys : { 'UP': 38, 'DOWN': 40, 'LEFT': 37, 'RIGHT': 39, 'RETURN': 13, 'ESCAPE': 27, 'BACKSPACE': 8, 'SPACE': 32 }, map : {}, bound: false, press: function(e) { var key = e.keyCode || e.which; if ( key in keyboard.map && typeof keyboard.map[key] === 'function' ) { keyboard.map[key].call(self, e); } }, attach: function(map) { var key, up; for( key in map ) { if ( map.hasOwnProperty( key ) ) { up = key.toUpperCase(); if ( up in keyboard.keys ) { keyboard.map[ keyboard.keys[up] ] = map[key]; } else { keyboard.map[ up ] = map[key]; } } } if ( !keyboard.bound ) { keyboard.bound = true; $doc.on('keydown', keyboard.press); } }, detach: function() { keyboard.bound = false; keyboard.map = {}; $doc.off('keydown', keyboard.press); } }; // internal controls for keeping track of active / inactive images var controls = this._controls = { 0: undef, 1: undef, active : 0, swap : function() { controls.active = controls.active ? 0 : 1; }, getActive : function() { return self._options.swipe ? controls.slides[ self._active ] : controls[ controls.active ]; }, getNext : function() { return self._options.swipe ? controls.slides[ self.getNext( self._active ) ] : controls[ 1 - controls.active ]; }, slides : [], frames: [], layers: [] }; // internal carousel object var carousel = this._carousel = { // shortcuts next: self.$('thumb-nav-right'), prev: self.$('thumb-nav-left'), // cache the width width: 0, // track the current position current: 0, // cache max value max: 0, // save all hooks for each width in an array hooks: [], // update the carousel // you can run this method anytime, f.ex on window.resize update: function() { var w = 0, h = 0, hooks = [0]; $.each( self._thumbnails, function( i, thumb ) { if ( thumb.ready ) { w += thumb.outerWidth || $( thumb.container ).outerWidth( true ); // Due to a bug in jquery, outerwidth() returns the floor of the actual outerwidth, // if the browser is zoom to a value other than 100%. height() returns the floating point value. var containerWidth = $( thumb.container).width(); w += containerWidth - M.floor(containerWidth); hooks[ i+1 ] = w; h = M.max( h, thumb.outerHeight || $( thumb.container).outerHeight( true ) ); } }); self.$( 'thumbnails' ).css({ width: w, height: h }); carousel.max = w; carousel.hooks = hooks; carousel.width = self.$( 'thumbnails-list' ).width(); carousel.setClasses(); self.$( 'thumbnails-container' ).toggleClass( 'galleria-carousel', w > carousel.width ); // one extra calculation carousel.width = self.$( 'thumbnails-list' ).width(); // todo: fix so the carousel moves to the left }, bindControls: function() { var i; carousel.next.on( 'click:fast', function(e) { e.preventDefault(); if ( self._options.carouselSteps === 'auto' ) { for ( i = carousel.current; i < carousel.hooks.length; i++ ) { if ( carousel.hooks[i] - carousel.hooks[ carousel.current ] > carousel.width ) { carousel.set(i - 2); break; } } } else { carousel.set( carousel.current + self._options.carouselSteps); } }); carousel.prev.on( 'click:fast', function(e) { e.preventDefault(); if ( self._options.carouselSteps === 'auto' ) { for ( i = carousel.current; i >= 0; i-- ) { if ( carousel.hooks[ carousel.current ] - carousel.hooks[i] > carousel.width ) { carousel.set( i + 2 ); break; } else if ( i === 0 ) { carousel.set( 0 ); break; } } } else { carousel.set( carousel.current - self._options.carouselSteps ); } }); }, // calculate and set positions set: function( i ) { i = M.max( i, 0 ); while ( carousel.hooks[i - 1] + carousel.width >= carousel.max && i >= 0 ) { i--; } carousel.current = i; carousel.animate(); }, // get the last position getLast: function(i) { return ( i || carousel.current ) - 1; }, // follow the active image follow: function(i) { //don't follow if position fits if ( i === 0 || i === carousel.hooks.length - 2 ) { carousel.set( i ); return; } // calculate last position var last = carousel.current; while( carousel.hooks[last] - carousel.hooks[ carousel.current ] < carousel.width && last <= carousel.hooks.length ) { last ++; } // set position if ( i - 1 < carousel.current ) { carousel.set( i - 1 ); } else if ( i + 2 > last) { carousel.set( i - last + carousel.current + 2 ); } }, // helper for setting disabled classes setClasses: function() { carousel.prev.toggleClass( 'disabled', !carousel.current ); carousel.next.toggleClass( 'disabled', carousel.hooks[ carousel.current ] + carousel.width >= carousel.max ); }, // the animation method animate: function(to) { carousel.setClasses(); var num = carousel.hooks[ carousel.current ] * -1; if ( isNaN( num ) ) { return; } // FF 24 bug self.$( 'thumbnails' ).css('left', function() { return $(this).css('left'); }); Utils.animate(self.get( 'thumbnails' ), { left: num },{ duration: self._options.carouselSpeed, easing: self._options.easing, queue: false }); } }; // tooltip control // added in 1.2 var tooltip = this._tooltip = { initialized : false, open: false, timer: 'tooltip' + self._id, swapTimer: 'swap' + self._id, init: function() { tooltip.initialized = true; var css = '.galleria-tooltip{padding:3px 8px;max-width:50%;background:#ffe;color:#000;z-index:3;position:absolute;font-size:11px;line-height:1.3;' + 'opacity:0;box-shadow:0 0 2px rgba(0,0,0,.4);-moz-box-shadow:0 0 2px rgba(0,0,0,.4);-webkit-box-shadow:0 0 2px rgba(0,0,0,.4);}'; Utils.insertStyleTag( css, 'galleria-tooltip' ); self.$( 'tooltip' ).css({ opacity: 0.8, visibility: 'visible', display: 'none' }); }, // move handler move: function( e ) { var mouseX = self.getMousePosition(e).x, mouseY = self.getMousePosition(e).y, $elem = self.$( 'tooltip' ), x = mouseX, y = mouseY, height = $elem.outerHeight( true ) + 1, width = $elem.outerWidth( true ), limitY = height + 15; var maxX = self.$( 'container' ).width() - width - 2, maxY = self.$( 'container' ).height() - height - 2; if ( !isNaN(x) && !isNaN(y) ) { x += 10; y -= ( height+8 ); x = M.max( 0, M.min( maxX, x ) ); y = M.max( 0, M.min( maxY, y ) ); if( mouseY < limitY ) { y = limitY; } $elem.css({ left: x, top: y }); } }, // bind elements to the tooltip // you can bind multiple elementIDs using { elemID : function } or { elemID : string } // you can also bind single DOM elements using bind(elem, string) bind: function( elem, value ) { // todo: revise if alternative tooltip is needed for mobile devices if (Galleria.TOUCH) { return; } if (! tooltip.initialized ) { tooltip.init(); } var mouseout = function() { self.$( 'container' ).off( 'mousemove', tooltip.move ); self.clearTimer( tooltip.timer ); self.$( 'tooltip' ).stop().animate({ opacity: 0 }, 200, function() { self.$( 'tooltip' ).hide(); self.addTimer( tooltip.swapTimer, function() { tooltip.open = false; }, 1000); }); }; var hover = function( elem, value) { tooltip.define( elem, value ); $( elem ).hover(function() { self.clearTimer( tooltip.swapTimer ); self.$('container').off( 'mousemove', tooltip.move ).on( 'mousemove', tooltip.move ).trigger( 'mousemove' ); tooltip.show( elem ); self.addTimer( tooltip.timer, function() { self.$( 'tooltip' ).stop().show().animate({ opacity: 1 }); tooltip.open = true; }, tooltip.open ? 0 : 500); }, mouseout).click(mouseout); }; if ( typeof value === 'string' ) { hover( ( elem in self._dom ? self.get( elem ) : elem ), value ); } else { // asume elemID here $.each( elem, function( elemID, val ) { hover( self.get(elemID), val ); }); } }, show: function( elem ) { elem = $( elem in self._dom ? self.get(elem) : elem ); var text = elem.data( 'tt' ), mouseup = function( e ) { // attach a tiny settimeout to make sure the new tooltip is filled window.setTimeout( (function( ev ) { return function() { tooltip.move( ev ); }; }( e )), 10); elem.off( 'mouseup', mouseup ); }; text = typeof text === 'function' ? text() : text; if ( ! text ) { return; } self.$( 'tooltip' ).html( text.replace(/\s/, '&#160;') ); // trigger mousemove on mouseup in case of click elem.on( 'mouseup', mouseup ); }, define: function( elem, value ) { // we store functions, not strings if (typeof value !== 'function') { var s = value; value = function() { return s; }; } elem = $( elem in self._dom ? self.get(elem) : elem ).data('tt', value); tooltip.show( elem ); } }; // internal fullscreen control var fullscreen = this._fullscreen = { scrolled: 0, crop: undef, active: false, prev: $(), beforeEnter: function(fn){ fn(); }, beforeExit: function(fn){ fn(); }, keymap: self._keyboard.map, parseCallback: function( callback, enter ) { return _transitions.active ? function() { if ( typeof callback == 'function' ) { callback.call(self); } var active = self._controls.getActive(), next = self._controls.getNext(); self._scaleImage( next ); self._scaleImage( active ); if ( enter && self._options.trueFullscreen ) { // Firefox bug, revise later $( active.container ).add( next.container ).trigger( 'transitionend' ); } } : callback; }, enter: function( callback ) { fullscreen.beforeEnter(function() { callback = fullscreen.parseCallback( callback, true ); if ( self._options.trueFullscreen && _nativeFullscreen.support ) { // do some stuff prior animation for wmoother transitions fullscreen.active = true; Utils.forceStyles( self.get('container'), { width: '100%', height: '100%' }); self.rescale(); if ( Galleria.MAC ) { if ( !( Galleria.SAFARI && /version\/[1-5]/.test(NAV)) ) { self.$('container').css('opacity', 0).addClass('fullscreen'); window.setTimeout(function() { fullscreen.scale(); self.$('container').css('opacity', 1); }, 50); } else { self.$('stage').css('opacity', 0); window.setTimeout(function() { fullscreen.scale(); self.$('stage').css('opacity', 1); },4); } } else { self.$('container').addClass('fullscreen'); } $win.resize( fullscreen.scale ); _nativeFullscreen.enter( self, callback, self.get('container') ); } else { fullscreen.scrolled = $win.scrollTop(); if( !Galleria.TOUCH ) { window.scrollTo(0, 0); } fullscreen._enter( callback ); } }); }, _enter: function( callback ) { fullscreen.active = true; if ( IFRAME ) { fullscreen.iframe = (function() { var elem, refer = doc.referrer, test = doc.createElement('a'), loc = window.location; test.href = refer; if( test.protocol != loc.protocol || test.hostname != loc.hostname || test.port != loc.port ) { Galleria.raise('Parent fullscreen not available. Iframe protocol, domains and ports must match.'); return false; } fullscreen.pd = window.parent.document; $( fullscreen.pd ).find('iframe').each(function() { var idoc = this.contentDocument || this.contentWindow.document; if ( idoc === doc ) { elem = this; return false; } }); return elem; }()); } // hide the image until rescale is complete Utils.hide( self.getActiveImage() ); if ( IFRAME && fullscreen.iframe ) { fullscreen.iframe.scrolled = $( window.parent ).scrollTop(); window.parent.scrollTo(0, 0); } var data = self.getData(), options = self._options, inBrowser = !self._options.trueFullscreen || !_nativeFullscreen.support, htmlbody = { height: '100%', overflow: 'hidden', margin:0, padding:0 }; if (inBrowser) { self.$('container').addClass('fullscreen'); fullscreen.prev = self.$('container').prev(); if ( !fullscreen.prev.length ) { fullscreen.parent = self.$( 'container' ).parent(); } // move self.$( 'container' ).appendTo( 'body' ); // begin styleforce Utils.forceStyles(self.get('container'), { position: Galleria.TOUCH ? 'absolute' : 'fixed', top: 0, left: 0, width: '100%', height: '100%', zIndex: 10000 }); Utils.forceStyles( DOM().html, htmlbody ); Utils.forceStyles( DOM().body, htmlbody ); } if ( IFRAME && fullscreen.iframe ) { Utils.forceStyles( fullscreen.pd.documentElement, htmlbody ); Utils.forceStyles( fullscreen.pd.body, htmlbody ); Utils.forceStyles( fullscreen.iframe, $.extend( htmlbody, { width: '100%', height: '100%', top: 0, left: 0, position: 'fixed', zIndex: 10000, border: 'none' })); } // temporarily attach some keys // save the old ones first in a cloned object fullscreen.keymap = $.extend({}, self._keyboard.map); self.attachKeyboard({ escape: self.exitFullscreen, right: self.next, left: self.prev }); // temporarily save the crop fullscreen.crop = options.imageCrop; // set fullscreen options if ( options.fullscreenCrop != undef ) { options.imageCrop = options.fullscreenCrop; } // swap to big image if it's different from the display image if ( data && data.big && data.image !== data.big ) { var big = new Galleria.Picture(), cached = big.isCached( data.big ), index = self.getIndex(), thumb = self._thumbnails[ index ]; self.trigger( { type: Galleria.LOADSTART, cached: cached, rewind: false, index: index, imageTarget: self.getActiveImage(), thumbTarget: thumb, galleriaData: data }); big.load( data.big, function( big ) { self._scaleImage( big, { complete: function( big ) { self.trigger({ type: Galleria.LOADFINISH, cached: cached, index: index, rewind: false, imageTarget: big.image, thumbTarget: thumb }); var image = self._controls.getActive().image; if ( image ) { $( image ).width( big.image.width ).height( big.image.height ) .attr( 'style', $( big.image ).attr('style') ) .attr( 'src', big.image.src ); } } }); }); var n = self.getNext(index), p = new Galleria.Picture(), ndata = self.getData( n ); p.preload( self.isFullscreen() && ndata.big ? ndata.big : ndata.image ); } // init the first rescale and attach callbacks self.rescale(function() { self.addTimer(false, function() { // show the image after 50 ms if ( inBrowser ) { Utils.show( self.getActiveImage() ); } if (typeof callback === 'function') { callback.call( self ); } self.rescale(); }, 100); self.trigger( Galleria.FULLSCREEN_ENTER ); }); if ( !inBrowser ) { Utils.show( self.getActiveImage() ); } else { $win.resize( fullscreen.scale ); } }, scale : function() { self.rescale(); }, exit: function( callback ) { fullscreen.beforeExit(function() { callback = fullscreen.parseCallback( callback ); if ( self._options.trueFullscreen && _nativeFullscreen.support ) { _nativeFullscreen.exit( callback ); } else { fullscreen._exit( callback ); } }); }, _exit: function( callback ) { fullscreen.active = false; var inBrowser = !self._options.trueFullscreen || !_nativeFullscreen.support, $container = self.$( 'container' ).removeClass( 'fullscreen' ); // move back if ( fullscreen.parent ) { fullscreen.parent.prepend( $container ); } else { $container.insertAfter( fullscreen.prev ); } if ( inBrowser ) { Utils.hide( self.getActiveImage() ); // revert all styles Utils.revertStyles( self.get('container'), DOM().html, DOM().body ); // scroll back if( !Galleria.TOUCH ) { window.scrollTo(0, fullscreen.scrolled); } // reload iframe src manually var frame = self._controls.frames[ self._controls.active ]; if ( frame && frame.image ) { frame.image.src = frame.image.src; } } if ( IFRAME && fullscreen.iframe ) { Utils.revertStyles( fullscreen.pd.documentElement, fullscreen.pd.body, fullscreen.iframe ); if ( fullscreen.iframe.scrolled ) { window.parent.scrollTo(0, fullscreen.iframe.scrolled ); } } // detach all keyboard events and apply the old keymap self.detachKeyboard(); self.attachKeyboard( fullscreen.keymap ); // bring back cached options self._options.imageCrop = fullscreen.crop; // return to original image var big = self.getData().big, image = self._controls.getActive().image; if ( !self.getData().iframe && image && big && big == image.src ) { window.setTimeout(function(src) { return function() { image.src = src; }; }( self.getData().image ), 1 ); } self.rescale(function() { self.addTimer(false, function() { // show the image after 50 ms if ( inBrowser ) { Utils.show( self.getActiveImage() ); } if ( typeof callback === 'function' ) { callback.call( self ); } $win.trigger( 'resize' ); }, 50); self.trigger( Galleria.FULLSCREEN_EXIT ); }); $win.off('resize', fullscreen.scale); } }; // the internal idle object for controlling idle states var idle = this._idle = { trunk: [], bound: false, active: false, add: function(elem, to, from, hide) { if ( !elem || Galleria.TOUCH ) { return; } if (!idle.bound) { idle.addEvent(); } elem = $(elem); if ( typeof from == 'boolean' ) { hide = from; from = {}; } from = from || {}; var extract = {}, style; for ( style in to ) { if ( to.hasOwnProperty( style ) ) { extract[ style ] = elem.css( style ); } } elem.data('idle', { from: $.extend( extract, from ), to: to, complete: true, busy: false }); if ( !hide ) { idle.addTimer(); } else { elem.css( to ); } idle.trunk.push(elem); }, remove: function(elem) { elem = $(elem); $.each(idle.trunk, function(i, el) { if ( el && el.length && !el.not(elem).length ) { elem.css( elem.data( 'idle' ).from ); idle.trunk.splice(i, 1); } }); if (!idle.trunk.length) { idle.removeEvent(); self.clearTimer( idle.timer ); } }, addEvent : function() { idle.bound = true; self.$('container').on( 'mousemove click', idle.showAll ); if ( self._options.idleMode == 'hover' ) { self.$('container').on( 'mouseleave', idle.hide ); } }, removeEvent : function() { idle.bound = false; self.$('container').on( 'mousemove click', idle.showAll ); if ( self._options.idleMode == 'hover' ) { self.$('container').off( 'mouseleave', idle.hide ); } }, addTimer : function() { if( self._options.idleMode == 'hover' ) { return; } self.addTimer( 'idle', function() { idle.hide(); }, self._options.idleTime ); }, hide : function() { if ( !self._options.idleMode || self.getIndex() === false ) { return; } self.trigger( Galleria.IDLE_ENTER ); var len = idle.trunk.length; $.each( idle.trunk, function(i, elem) { var data = elem.data('idle'); if (! data) { return; } elem.data('idle').complete = false; Utils.animate( elem, data.to, { duration: self._options.idleSpeed, complete: function() { if ( i == len-1 ) { idle.active = false; } } }); }); }, showAll : function() { self.clearTimer( 'idle' ); $.each( idle.trunk, function( i, elem ) { idle.show( elem ); }); }, show: function(elem) { var data = elem.data('idle'); if ( !idle.active || ( !data.busy && !data.complete ) ) { data.busy = true; self.trigger( Galleria.IDLE_EXIT ); self.clearTimer( 'idle' ); Utils.animate( elem, data.from, { duration: self._options.idleSpeed/2, complete: function() { idle.active = true; $(elem).data('idle').busy = false; $(elem).data('idle').complete = true; } }); } idle.addTimer(); } }; // internal lightbox object // creates a predesigned lightbox for simple popups of images in galleria var lightbox = this._lightbox = { width : 0, height : 0, initialized : false, active : null, image : null, elems : {}, keymap: false, init : function() { if ( lightbox.initialized ) { return; } lightbox.initialized = true; // create some elements to work with var elems = 'overlay box content shadow title info close prevholder prev nextholder next counter image', el = {}, op = self._options, css = '', abs = 'position:absolute;', prefix = 'lightbox-', cssMap = { overlay: 'position:fixed;display:none;opacity:'+op.overlayOpacity+';filter:alpha(opacity='+(op.overlayOpacity*100)+ ');top:0;left:0;width:100%;height:100%;background:'+op.overlayBackground+';z-index:99990', box: 'position:fixed;display:none;width:400px;height:400px;top:50%;left:50%;margin-top:-200px;margin-left:-200px;z-index:99991', shadow: abs+'background:#000;width:100%;height:100%;', content: abs+'background-color:#fff;top:10px;left:10px;right:10px;bottom:10px;overflow:hidden', info: abs+'bottom:10px;left:10px;right:10px;color:#444;font:11px/13px arial,sans-serif;height:13px', close: abs+'top:10px;right:10px;height:20px;width:20px;background:#fff;text-align:center;cursor:pointer;color:#444;font:16px/22px arial,sans-serif;z-index:99999', image: abs+'top:10px;left:10px;right:10px;bottom:30px;overflow:hidden;display:block;', prevholder: abs+'width:50%;top:0;bottom:40px;cursor:pointer;', nextholder: abs+'width:50%;top:0;bottom:40px;right:-1px;cursor:pointer;', prev: abs+'top:50%;margin-top:-20px;height:40px;width:30px;background:#fff;left:20px;display:none;text-align:center;color:#000;font:bold 16px/36px arial,sans-serif', next: abs+'top:50%;margin-top:-20px;height:40px;width:30px;background:#fff;right:20px;left:auto;display:none;font:bold 16px/36px arial,sans-serif;text-align:center;color:#000', title: 'float:left', counter: 'float:right;margin-left:8px;' }, hover = function(elem) { return elem.hover( function() { $(this).css( 'color', '#bbb' ); }, function() { $(this).css( 'color', '#444' ); } ); }, appends = {}; // fix for navigation hovers transparent background event "feature" var exs = ''; if ( IE > 7 ) { exs = IE < 9 ? 'background:#000;filter:alpha(opacity=0);' : 'background:rgba(0,0,0,0);'; } else { exs = 'z-index:99999'; } cssMap.nextholder += exs; cssMap.prevholder += exs; // create and insert CSS $.each(cssMap, function( key, value ) { css += '.galleria-'+prefix+key+'{'+value+'}'; }); css += '.galleria-'+prefix+'box.iframe .galleria-'+prefix+'prevholder,'+ '.galleria-'+prefix+'box.iframe .galleria-'+prefix+'nextholder{'+ 'width:100px;height:100px;top:50%;margin-top:-70px}'; Utils.insertStyleTag( css, 'galleria-lightbox' ); // create the elements $.each(elems.split(' '), function( i, elemId ) { self.addElement( 'lightbox-' + elemId ); el[ elemId ] = lightbox.elems[ elemId ] = self.get( 'lightbox-' + elemId ); }); // initiate the image lightbox.image = new Galleria.Picture(); // append the elements $.each({ box: 'shadow content close prevholder nextholder', info: 'title counter', content: 'info image', prevholder: 'prev', nextholder: 'next' }, function( key, val ) { var arr = []; $.each( val.split(' '), function( i, prop ) { arr.push( prefix + prop ); }); appends[ prefix+key ] = arr; }); self.append( appends ); $( el.image ).append( lightbox.image.container ); $( DOM().body ).append( el.overlay, el.box ); // add the prev/next nav and bind some controls hover( $( el.close ).on( 'click:fast', lightbox.hide ).html('&#215;') ); $.each( ['Prev','Next'], function(i, dir) { var $d = $( el[ dir.toLowerCase() ] ).html( /v/.test( dir ) ? '&#8249;&#160;' : '&#160;&#8250;' ), $e = $( el[ dir.toLowerCase()+'holder'] ); $e.on( 'click:fast', function() { lightbox[ 'show' + dir ](); }); // IE7 and touch devices will simply show the nav if ( IE < 8 || Galleria.TOUCH ) { $d.show(); return; } $e.hover( function() { $d.show(); }, function(e) { $d.stop().fadeOut( 200 ); }); }); $( el.overlay ).on( 'click:fast', lightbox.hide ); // the lightbox animation is slow on ipad if ( Galleria.IPAD ) { self._options.lightboxTransitionSpeed = 0; } }, rescale: function(event) { // calculate var width = M.min( $win.width()-40, lightbox.width ), height = M.min( $win.height()-60, lightbox.height ), ratio = M.min( width / lightbox.width, height / lightbox.height ), destWidth = M.round( lightbox.width * ratio ) + 40, destHeight = M.round( lightbox.height * ratio ) + 60, to = { width: destWidth, height: destHeight, 'margin-top': M.ceil( destHeight / 2 ) *- 1, 'margin-left': M.ceil( destWidth / 2 ) *- 1 }; // if rescale event, don't animate if ( event ) { $( lightbox.elems.box ).css( to ); } else { $( lightbox.elems.box ).animate( to, { duration: self._options.lightboxTransitionSpeed, easing: self._options.easing, complete: function() { var image = lightbox.image, speed = self._options.lightboxFadeSpeed; self.trigger({ type: Galleria.LIGHTBOX_IMAGE, imageTarget: image.image }); $( image.container ).show(); $( image.image ).animate({ opacity: 1 }, speed); Utils.show( lightbox.elems.info, speed ); } }); } }, hide: function() { // remove the image lightbox.image.image = null; $win.off('resize', lightbox.rescale); $( lightbox.elems.box ).hide().find( 'iframe' ).remove(); Utils.hide( lightbox.elems.info ); self.detachKeyboard(); self.attachKeyboard( lightbox.keymap ); lightbox.keymap = false; Utils.hide( lightbox.elems.overlay, 200, function() { $( this ).hide().css( 'opacity', self._options.overlayOpacity ); self.trigger( Galleria.LIGHTBOX_CLOSE ); }); }, showNext: function() { lightbox.show( self.getNext( lightbox.active ) ); }, showPrev: function() { lightbox.show( self.getPrev( lightbox.active ) ); }, show: function(index) { lightbox.active = index = typeof index === 'number' ? index : self.getIndex() || 0; if ( !lightbox.initialized ) { lightbox.init(); } // trigger the event self.trigger( Galleria.LIGHTBOX_OPEN ); // temporarily attach some keys // save the old ones first in a cloned object if ( !lightbox.keymap ) { lightbox.keymap = $.extend({}, self._keyboard.map); self.attachKeyboard({ escape: lightbox.hide, right: lightbox.showNext, left: lightbox.showPrev }); } $win.off('resize', lightbox.rescale ); var data = self.getData(index), total = self.getDataLength(), n = self.getNext( index ), ndata, p, i; Utils.hide( lightbox.elems.info ); try { for ( i = self._options.preload; i > 0; i-- ) { p = new Galleria.Picture(); ndata = self.getData( n ); p.preload( ndata.big ? ndata.big : ndata.image ); n = self.getNext( n ); } } catch(e) {} lightbox.image.isIframe = ( data.iframe && !data.image ); $( lightbox.elems.box ).toggleClass( 'iframe', lightbox.image.isIframe ); $( lightbox.image.container ).find( '.galleria-videoicon' ).remove(); lightbox.image.load( data.big || data.image || data.iframe, function( image ) { if ( image.isIframe ) { var cw = $(window).width(), ch = $(window).height(); if ( image.video && self._options.maxVideoSize ) { var r = M.min( self._options.maxVideoSize/cw, self._options.maxVideoSize/ch ); if ( r < 1 ) { cw *= r; ch *= r; } } lightbox.width = cw; lightbox.height = ch; } else { lightbox.width = image.original.width; lightbox.height = image.original.height; } $( image.image ).css({ width: image.isIframe ? '100%' : '100.1%', height: image.isIframe ? '100%' : '100.1%', top: 0, bottom: 0, zIndex: 99998, opacity: 0, visibility: 'visible' }).parent().height('100%'); lightbox.elems.title.innerHTML = data.title || ''; lightbox.elems.counter.innerHTML = (index + 1) + ' / ' + total; $win.resize( lightbox.rescale ); lightbox.rescale(); if( data.image && data.iframe ) { $( lightbox.elems.box ).addClass('iframe'); if ( data.video ) { var $icon = _playIcon( image.container ).hide(); window.setTimeout(function() { $icon.fadeIn(200); }, 200); } $( image.image ).css( 'cursor', 'pointer' ).mouseup((function(data, image) { return function(e) { $( lightbox.image.container ).find( '.galleria-videoicon' ).remove(); e.preventDefault(); image.isIframe = true; image.load( data.iframe + ( data.video ? '&autoplay=1' : '' ), { width: '100%', height: IE < 8 ? $( lightbox.image.container ).height() : '100%' }); }; }(data, image))); } }); $( lightbox.elems.overlay ).show().css( 'visibility', 'visible' ); $( lightbox.elems.box ).show(); } }; // the internal timeouts object // provides helper methods for controlling timeouts var _timer = this._timer = { trunk: {}, add: function( id, fn, delay, loop ) { id = id || new Date().getTime(); loop = loop || false; this.clear( id ); if ( loop ) { var old = fn; fn = function() { old(); _timer.add( id, fn, delay ); }; } this.trunk[ id ] = window.setTimeout( fn, delay ); }, clear: function( id ) { var del = function( i ) { window.clearTimeout( this.trunk[ i ] ); delete this.trunk[ i ]; }, i; if ( !!id && id in this.trunk ) { del.call( this, id ); } else if ( typeof id === 'undefined' ) { for ( i in this.trunk ) { if ( this.trunk.hasOwnProperty( i ) ) { del.call( this, i ); } } } } }; return this; }; // end Galleria constructor Galleria.prototype = { // bring back the constructor reference constructor: Galleria, /** Use this function to initialize the gallery and start loading. Should only be called once per instance. @param {HTMLElement} target The target element @param {Object} options The gallery options @returns Instance */ init: function( target, options ) { options = _legacyOptions( options ); // save the original ingredients this._original = { target: target, options: options, data: null }; // save the target here this._target = this._dom.target = target.nodeName ? target : $( target ).get(0); // save the original content for destruction this._original.html = this._target.innerHTML; // push the instance _instances.push( this ); // raise error if no target is detected if ( !this._target ) { Galleria.raise('Target not found', true); return; } // apply options this._options = { autoplay: false, carousel: true, carouselFollow: true, // legacy, deprecate at 1.3 carouselSpeed: 400, carouselSteps: 'auto', clicknext: false, dailymotion: { foreground: '%23EEEEEE', highlight: '%235BCEC5', background: '%23222222', logo: 0, hideInfos: 1 }, dataConfig : function( elem ) { return {}; }, dataSelector: 'img', dataSort: false, dataSource: this._target, debug: undef, dummy: undef, // 1.2.5 easing: 'galleria', extend: function(options) {}, fullscreenCrop: undef, // 1.2.5 fullscreenDoubleTap: true, // 1.2.4 toggles fullscreen on double-tap for touch devices fullscreenTransition: undef, // 1.2.6 height: 0, idleMode: true, // 1.2.4 toggles idleMode idleTime: 3000, idleSpeed: 200, imageCrop: false, imageMargin: 0, imagePan: false, imagePanSmoothness: 12, imagePosition: '50%', imageTimeout: undef, // 1.2.5 initialTransition: undef, // 1.2.4, replaces transitionInitial keepSource: false, layerFollow: true, // 1.2.5 lightbox: false, // 1.2.3 lightboxFadeSpeed: 200, lightboxTransitionSpeed: 200, linkSourceImages: true, maxScaleRatio: undef, maxVideoSize: undef, // 1.2.9 minScaleRatio: undef, // deprecated in 1.2.9 overlayOpacity: 0.85, overlayBackground: '#0b0b0b', pauseOnInteraction: true, popupLinks: false, preload: 2, queue: true, responsive: true, show: 0, showInfo: true, showCounter: true, showImagenav: true, swipe: 'auto', // 1.2.4 -> revised in 1.3 -> changed type in 1.3.5 thumbCrop: true, thumbEventType: 'click:fast', thumbMargin: 0, thumbQuality: 'auto', thumbDisplayOrder: true, // 1.2.8 thumbPosition: '50%', // 1.3 thumbnails: true, touchTransition: undef, // 1.2.6 transition: 'fade', transitionInitial: undef, // legacy, deprecate in 1.3. Use initialTransition instead. transitionSpeed: 400, trueFullscreen: true, // 1.2.7 useCanvas: false, // 1.2.4 variation: '', // 1.3.2 videoPoster: true, // 1.3 vimeo: { title: 0, byline: 0, portrait: 0, color: 'aaaaaa' }, wait: 5000, // 1.2.7 width: 'auto', youtube: { modestbranding: 1, autohide: 1, color: 'white', hd: 1, rel: 0, showinfo: 0 } }; // legacy support for transitionInitial this._options.initialTransition = this._options.initialTransition || this._options.transitionInitial; // turn off debug if ( options && options.debug === false ) { DEBUG = false; } // set timeout if ( options && typeof options.imageTimeout === 'number' ) { TIMEOUT = options.imageTimeout; } // set dummy if ( options && typeof options.dummy === 'string' ) { DUMMY = options.dummy; } // hide all content $( this._target ).children().hide(); // Warn for quirks mode if ( Galleria.QUIRK ) { Galleria.raise('Your page is in Quirks mode, Galleria may not render correctly. Please validate your HTML and add a correct doctype.'); } // now we just have to wait for the theme... if ( typeof Galleria.theme === 'object' ) { this._init(); } else { // push the instance into the pool and run it when the theme is ready _pool.push( this ); } return this; }, // this method should only be called once per instance // for manipulation of data, use the .load method _init: function() { var self = this, options = this._options; if ( this._initialized ) { Galleria.raise( 'Init failed: Gallery instance already initialized.' ); return this; } this._initialized = true; if ( !Galleria.theme ) { Galleria.raise( 'Init failed: No theme found.', true ); return this; } // merge the theme & caller options $.extend( true, options, Galleria.theme.defaults, this._original.options, Galleria.configure.options ); // internally we use boolean for swipe options.swipe = (function(s) { if ( s == 'enforced' ) { return true; } // legacy patch if( s === false || s == 'disabled' ) { return false; } return !!Galleria.TOUCH; }( options.swipe )); // disable options that arent compatible with swipe if ( options.swipe ) { options.clicknext = false; options.imagePan = false; } // check for canvas support (function( can ) { if ( !( 'getContext' in can ) ) { can = null; return; } _canvas = _canvas || { elem: can, context: can.getContext( '2d' ), cache: {}, length: 0 }; }( doc.createElement( 'canvas' ) ) ); // bind the gallery to run when data is ready this.bind( Galleria.DATA, function() { // remove big if total pixels are less than 1024 (most phones) if ( window.screen && window.screen.width && Array.prototype.forEach ) { this._data.forEach(function(data) { var density = 'devicePixelRatio' in window ? window.devicePixelRatio : 1, m = M.max( window.screen.width, window.screen.height ); if ( m*density < 1024 ) { data.big = data.image; } }); } // save the new data this._original.data = this._data; // lets show the counter here this.get('total').innerHTML = this.getDataLength(); // cache the container var $container = this.$( 'container' ); // set ratio if height is < 2 if ( self._options.height < 2 ) { self._userRatio = self._ratio = self._options.height; } // the gallery is ready, let's just wait for the css var num = { width: 0, height: 0 }; var testHeight = function() { return self.$( 'stage' ).height(); }; // check container and thumbnail height Utils.wait({ until: function() { // keep trying to get the value num = self._getWH(); $container.width( num.width ).height( num.height ); return testHeight() && num.width && num.height > 50; }, success: function() { self._width = num.width; self._height = num.height; self._ratio = self._ratio || num.height/num.width; // for some strange reason, webkit needs a single setTimeout to play ball if ( Galleria.WEBKIT ) { window.setTimeout( function() { self._run(); }, 1); } else { self._run(); } }, error: function() { // Height was probably not set, raise hard errors if ( testHeight() ) { Galleria.raise('Could not extract sufficient width/height of the gallery container. Traced measures: width:' + num.width + 'px, height: ' + num.height + 'px.', true); } else { Galleria.raise('Could not extract a stage height from the CSS. Traced height: ' + testHeight() + 'px.', true); } }, timeout: typeof this._options.wait == 'number' ? this._options.wait : false }); }); // build the gallery frame this.append({ 'info-text' : ['info-title', 'info-description'], 'info' : ['info-text'], 'image-nav' : ['image-nav-right', 'image-nav-left'], 'stage' : ['images', 'loader', 'counter', 'image-nav'], 'thumbnails-list' : ['thumbnails'], 'thumbnails-container' : ['thumb-nav-left', 'thumbnails-list', 'thumb-nav-right'], 'container' : ['stage', 'thumbnails-container', 'info', 'tooltip'] }); Utils.hide( this.$( 'counter' ).append( this.get( 'current' ), doc.createTextNode(' / '), this.get( 'total' ) ) ); this.setCounter('&#8211;'); Utils.hide( self.get('tooltip') ); // add a notouch class on the container to prevent unwanted :hovers on touch devices this.$( 'container' ).addClass( ( Galleria.TOUCH ? 'touch' : 'notouch' ) + ' ' + this._options.variation ); // add images to the controls if ( !this._options.swipe ) { $.each( new Array(2), function( i ) { // create a new Picture instance var image = new Galleria.Picture(); // apply some styles, create & prepend overlay $( image.container ).css({ position: 'absolute', top: 0, left: 0 }).prepend( self._layers[i] = $( Utils.create('galleria-layer') ).css({ position: 'absolute', top:0, left:0, right:0, bottom:0, zIndex:2 })[0] ); // append the image self.$( 'images' ).append( image.container ); // reload the controls self._controls[i] = image; // build a frame var frame = new Galleria.Picture(); frame.isIframe = true; $( frame.container ).attr('class', 'galleria-frame').css({ position: 'absolute', top: 0, left: 0, zIndex: 4, background: '#000', display: 'none' }).appendTo( image.container ); self._controls.frames[i] = frame; }); } // some forced generic styling this.$( 'images' ).css({ position: 'relative', top: 0, left: 0, width: '100%', height: '100%' }); if ( options.swipe ) { this.$( 'images' ).css({ position: 'absolute', top: 0, left: 0, width: 0, height: '100%' }); this.finger = new Galleria.Finger(this.get('stage'), { onchange: function(page) { self.pause().show(page); }, oncomplete: function(page) { var index = M.max( 0, M.min( parseInt( page, 10 ), self.getDataLength() - 1 ) ), data = self.getData(index); $( self._thumbnails[ index ].container ) .addClass( 'active' ) .siblings( '.active' ) .removeClass( 'active' ); if ( !data ) { return; } // remove video iframes self.$( 'images' ).find( '.galleria-frame' ).css('opacity', 0).hide().find( 'iframe' ).remove(); if ( self._options.carousel && self._options.carouselFollow ) { self._carousel.follow( index ); } } }); this.bind( Galleria.RESCALE, function() { this.finger.setup(); }); this.$('stage').on('click', function(e) { var data = self.getData(); if ( !data ) { return; } if ( data.iframe ) { if ( self.isPlaying() ) { self.pause(); } var frame = self._controls.frames[ self._active ], w = self._stageWidth, h = self._stageHeight; if ( $( frame.container ).find( 'iframe' ).length ) { return; } $( frame.container ).css({ width: w, height: h, opacity: 0 }).show().animate({ opacity: 1 }, 200); window.setTimeout(function() { frame.load( data.iframe + ( data.video ? '&autoplay=1' : '' ), { width: w, height: h }, function( frame ) { self.$( 'container' ).addClass( 'videoplay' ); frame.scale({ width: self._stageWidth, height: self._stageHeight, iframelimit: data.video ? self._options.maxVideoSize : undef }); }); }, 100); return; } if ( data.link ) { if ( self._options.popupLinks ) { var win = window.open( data.link, '_blank' ); } else { window.location.href = data.link; } return; } }); this.bind( Galleria.IMAGE, function(e) { self.setCounter( e.index ); self.setInfo( e.index ); var next = this.getNext(), prev = this.getPrev(); var preloads = [prev,next]; preloads.push(this.getNext(next), this.getPrev(prev), self._controls.slides.length-1); var filtered = []; $.each(preloads, function(i, val) { if ( $.inArray(val, filtered) == -1 ) { filtered.push(val); } }); $.each(filtered, function(i, loadme) { var d = self.getData(loadme), img = self._controls.slides[loadme], src = self.isFullscreen() && d.big ? d.big : ( d.image || d.iframe ); if ( d.iframe && !d.image ) { img.isIframe = true; } if ( !img.ready ) { self._controls.slides[loadme].load(src, function(img) { if ( !img.isIframe ) { $(img.image).css('visibility', 'hidden'); } self._scaleImage(img, { complete: function(img) { if ( !img.isIframe ) { $(img.image).css({ opacity: 0, visibility: 'visible' }).animate({ opacity: 1 }, 200); } } }); }); } }); }); } this.$( 'thumbnails, thumbnails-list' ).css({ overflow: 'hidden', position: 'relative' }); // bind image navigation arrows this.$( 'image-nav-right, image-nav-left' ).on( 'click:fast', function(e) { // pause if options is set if ( options.pauseOnInteraction ) { self.pause(); } // navigate var fn = /right/.test( this.className ) ? 'next' : 'prev'; self[ fn ](); }).on('click', function(e) { e.preventDefault(); // tune the clicknext option if ( options.clicknext || options.swipe ) { e.stopPropagation(); } }); // hide controls if chosen to $.each( ['info','counter','image-nav'], function( i, el ) { if ( options[ 'show' + el.substr(0,1).toUpperCase() + el.substr(1).replace(/-/,'') ] === false ) { Utils.moveOut( self.get( el.toLowerCase() ) ); } }); // load up target content this.load(); // now it's usually safe to remove the content // IE will never stop loading if we remove it, so let's keep it hidden for IE (it's usually fast enough anyway) if ( !options.keepSource && !IE ) { this._target.innerHTML = ''; } // re-append the errors, if they happened before clearing if ( this.get( 'errors' ) ) { this.appendChild( 'target', 'errors' ); } // append the gallery frame this.appendChild( 'target', 'container' ); // parse the carousel on each thumb load if ( options.carousel ) { var count = 0, show = options.show; this.bind( Galleria.THUMBNAIL, function() { this.updateCarousel(); if ( ++count == this.getDataLength() && typeof show == 'number' && show > 0 ) { this._carousel.follow( show ); } }); } // bind window resize for responsiveness if ( options.responsive ) { $win.on( 'resize', function() { if ( !self.isFullscreen() ) { self.resize(); } }); } // double-tap/click fullscreen toggle if ( options.fullscreenDoubleTap ) { this.$( 'stage' ).on( 'touchstart', (function() { var last, cx, cy, lx, ly, now, getData = function(e) { return e.originalEvent.touches ? e.originalEvent.touches[0] : e; }; self.$( 'stage' ).on('touchmove', function() { last = 0; }); return function(e) { if( /(-left|-right)/.test(e.target.className) ) { return; } now = Utils.timestamp(); cx = getData(e).pageX; cy = getData(e).pageY; if ( e.originalEvent.touches.length < 2 && ( now - last < 300 ) && ( cx - lx < 20) && ( cy - ly < 20) ) { self.toggleFullscreen(); e.preventDefault(); return; } last = now; lx = cx; ly = cy; }; }())); } // bind the ons $.each( Galleria.on.binds, function(i, bind) { // check if already bound if ( $.inArray( bind.hash, self._binds ) == -1 ) { self.bind( bind.type, bind.callback ); } }); return this; }, addTimer : function() { this._timer.add.apply( this._timer, Utils.array( arguments ) ); return this; }, clearTimer : function() { this._timer.clear.apply( this._timer, Utils.array( arguments ) ); return this; }, // parse width & height from CSS or options _getWH : function() { var $container = this.$( 'container' ), $target = this.$( 'target' ), self = this, num = {}, arr; $.each(['width', 'height'], function( i, m ) { // first check if options is set if ( self._options[ m ] && typeof self._options[ m ] === 'number') { num[ m ] = self._options[ m ]; } else { arr = [ Utils.parseValue( $container.css( m ) ), // the container css height Utils.parseValue( $target.css( m ) ), // the target css height $container[ m ](), // the container jQuery method $target[ m ]() // the target jQuery method ]; // if first time, include the min-width & min-height if ( !self[ '_'+m ] ) { arr.splice(arr.length, Utils.parseValue( $container.css( 'min-'+m ) ), Utils.parseValue( $target.css( 'min-'+m ) ) ); } // else extract the measures from different sources and grab the highest value num[ m ] = M.max.apply( M, arr ); } }); // allow setting a height ratio instead of exact value // useful when doing responsive galleries if ( self._userRatio ) { num.height = num.width * self._userRatio; } return num; }, // Creates the thumbnails and carousel // can be used at any time, f.ex when the data object is manipulated // push is an optional argument with pushed images _createThumbnails : function( push ) { this.get( 'total' ).innerHTML = this.getDataLength(); var src, thumb, data, $container, self = this, o = this._options, i = push ? this._data.length - push.length : 0, chunk = i, thumbchunk = [], loadindex = 0, gif = IE < 8 ? 'http://upload.wikimedia.org/wikipedia/commons/c/c0/Blank.gif' : 'data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw%3D%3D', // get previously active thumbnail, if exists active = (function() { var a = self.$('thumbnails').find('.active'); if ( !a.length ) { return false; } return a.find('img').attr('src'); }()), // cache the thumbnail option optval = typeof o.thumbnails === 'string' ? o.thumbnails.toLowerCase() : null, // move some data into the instance // for some reason, jQuery cant handle css(property) when zooming in FF, breaking the gallery // so we resort to getComputedStyle for browsers who support it getStyle = function( prop ) { return doc.defaultView && doc.defaultView.getComputedStyle ? doc.defaultView.getComputedStyle( thumb.container, null )[ prop ] : $container.css( prop ); }, fake = function(image, index, container) { return function() { $( container ).append( image ); self.trigger({ type: Galleria.THUMBNAIL, thumbTarget: image, index: index, galleriaData: self.getData( index ) }); }; }, onThumbEvent = function( e ) { // pause if option is set if ( o.pauseOnInteraction ) { self.pause(); } // extract the index from the data var index = $( e.currentTarget ).data( 'index' ); if ( self.getIndex() !== index ) { self.show( index ); } e.preventDefault(); }, thumbComplete = function( thumb, callback ) { $( thumb.container ).css( 'visibility', 'visible' ); self.trigger({ type: Galleria.THUMBNAIL, thumbTarget: thumb.image, index: thumb.data.order, galleriaData: self.getData( thumb.data.order ) }); if ( typeof callback == 'function' ) { callback.call( self, thumb ); } }, onThumbLoad = function( thumb, callback ) { // scale when ready thumb.scale({ width: thumb.data.width, height: thumb.data.height, crop: o.thumbCrop, margin: o.thumbMargin, canvas: o.useCanvas, position: o.thumbPosition, complete: function( thumb ) { // shrink thumbnails to fit var top = ['left', 'top'], arr = ['Width', 'Height'], m, css, data = self.getData( thumb.index ); // calculate shrinked positions $.each(arr, function( i, measure ) { m = measure.toLowerCase(); if ( (o.thumbCrop !== true || o.thumbCrop === m ) ) { css = {}; css[ m ] = thumb[ m ]; $( thumb.container ).css( css ); css = {}; css[ top[ i ] ] = 0; $( thumb.image ).css( css ); } // cache outer measures thumb[ 'outer' + measure ] = $( thumb.container )[ 'outer' + measure ]( true ); }); // set high quality if downscale is moderate Utils.toggleQuality( thumb.image, o.thumbQuality === true || ( o.thumbQuality === 'auto' && thumb.original.width < thumb.width * 3 ) ); if ( o.thumbDisplayOrder && !thumb.lazy ) { $.each( thumbchunk, function( i, th ) { if ( i === loadindex && th.ready && !th.displayed ) { loadindex++; th.displayed = true; thumbComplete( th, callback ); return; } }); } else { thumbComplete( thumb, callback ); } } }); }; if ( !push ) { this._thumbnails = []; this.$( 'thumbnails' ).empty(); } // loop through data and create thumbnails for( ; this._data[ i ]; i++ ) { data = this._data[ i ]; // get source from thumb or image src = data.thumb || data.image; if ( ( o.thumbnails === true || optval == 'lazy' ) && ( data.thumb || data.image ) ) { // add a new Picture instance thumb = new Galleria.Picture(i); // save the index thumb.index = i; // flag displayed thumb.displayed = false; // flag lazy thumb.lazy = false; // flag video thumb.video = false; // append the thumbnail this.$( 'thumbnails' ).append( thumb.container ); // cache the container $container = $( thumb.container ); // hide it $container.css( 'visibility', 'hidden' ); thumb.data = { width : Utils.parseValue( getStyle( 'width' ) ), height : Utils.parseValue( getStyle( 'height' ) ), order : i, src : src }; // grab & reset size for smoother thumbnail loads if ( o.thumbCrop !== true ) { $container.css( { width: 'auto', height: 'auto' } ); } else { $container.css( { width: thumb.data.width, height: thumb.data.height } ); } // load the thumbnail if ( optval == 'lazy' ) { $container.addClass( 'lazy' ); thumb.lazy = true; thumb.load( gif, { height: thumb.data.height, width: thumb.data.width }); } else { thumb.load( src, onThumbLoad ); } // preload all images here if ( o.preload === 'all' ) { thumb.preload( data.image ); } // create empty spans if thumbnails is set to 'empty' } else if ( data.iframe || optval === 'empty' || optval === 'numbers' ) { thumb = { container: Utils.create( 'galleria-image' ), image: Utils.create( 'img', 'span' ), ready: true, data: { order: i } }; // create numbered thumbnails if ( optval === 'numbers' ) { $( thumb.image ).text( i + 1 ); } if ( data.iframe ) { $( thumb.image ).addClass( 'iframe' ); } this.$( 'thumbnails' ).append( thumb.container ); // we need to "fake" a loading delay before we append and trigger // 50+ should be enough window.setTimeout( ( fake )( thumb.image, i, thumb.container ), 50 + ( i*20 ) ); // create null object to silent errors } else { thumb = { container: null, image: null }; } // add events for thumbnails // you can control the event type using thumb_event_type // we'll add the same event to the source if it's kept $( thumb.container ).add( o.keepSource && o.linkSourceImages ? data.original : null ) .data('index', i).on( o.thumbEventType, onThumbEvent ) .data('thumbload', onThumbLoad); if (active === src) { $( thumb.container ).addClass( 'active' ); } this._thumbnails.push( thumb ); } thumbchunk = this._thumbnails.slice( chunk ); return this; }, /** Lazy-loads thumbnails. You can call this method to load lazy thumbnails at run time @param {Array|Number} index Index or array of indexes of thumbnails to be loaded @param {Function} complete Callback that is called when all lazy thumbnails have been loaded @returns Instance */ lazyLoad: function( index, complete ) { var arr = index.constructor == Array ? index : [ index ], self = this, loaded = 0; $.each( arr, function(i, ind) { if ( ind > self._thumbnails.length - 1 ) { return; } var thumb = self._thumbnails[ ind ], data = thumb.data, callback = function() { if ( ++loaded == arr.length && typeof complete == 'function' ) { complete.call( self ); } }, thumbload = $( thumb.container ).data( 'thumbload' ); if ( thumb.video ) { thumbload.call( self, thumb, callback ); } else { thumb.load( data.src , function( thumb ) { thumbload.call( self, thumb, callback ); }); } }); return this; }, /** Lazy-loads thumbnails in chunks. This method automatcally chops up the loading process of many thumbnails into chunks @param {Number} size Size of each chunk to be loaded @param {Number} [delay] Delay between each loads @returns Instance */ lazyLoadChunks: function( size, delay ) { var len = this.getDataLength(), i = 0, n = 0, arr = [], temp = [], self = this; delay = delay || 0; for( ; i<len; i++ ) { temp.push(i); if ( ++n == size || i == len-1 ) { arr.push( temp ); n = 0; temp = []; } } var init = function( wait ) { var a = arr.shift(); if ( a ) { window.setTimeout(function() { self.lazyLoad(a, function() { init( true ); }); }, ( delay && wait ) ? delay : 0 ); } }; init( false ); return this; }, // the internal _run method should be called after loading data into galleria // makes sure the gallery has proper measurements before postrun & ready _run : function() { var self = this; self._createThumbnails(); // make sure we have a stageHeight && stageWidth Utils.wait({ timeout: 10000, until: function() { // Opera crap if ( Galleria.OPERA ) { self.$( 'stage' ).css( 'display', 'inline-block' ); } self._stageWidth = self.$( 'stage' ).width(); self._stageHeight = self.$( 'stage' ).height(); return( self._stageWidth && self._stageHeight > 50 ); // what is an acceptable height? }, success: function() { // save the instance _galleries.push( self ); // postrun some stuff after the gallery is ready // create the touch slider if ( self._options.swipe ) { var $images = self.$( 'images' ).width( self.getDataLength() * self._stageWidth ); $.each( new Array( self.getDataLength() ), function(i) { var image = new Galleria.Picture(), data = self.getData(i); $( image.container ).css({ position: 'absolute', top: 0, left: self._stageWidth*i }).prepend( self._layers[i] = $( Utils.create('galleria-layer') ).css({ position: 'absolute', top:0, left:0, right:0, bottom:0, zIndex:2 })[0] ).appendTo( $images ); if( data.video ) { _playIcon( image.container ); } self._controls.slides.push(image); var frame = new Galleria.Picture(); frame.isIframe = true; $( frame.container ).attr('class', 'galleria-frame').css({ position: 'absolute', top: 0, left: 0, zIndex: 4, background: '#000', display: 'none' }).appendTo( image.container ); self._controls.frames.push(frame); }); self.finger.setup(); } // show counter Utils.show( self.get('counter') ); // bind carousel nav if ( self._options.carousel ) { self._carousel.bindControls(); } // start autoplay if ( self._options.autoplay ) { self.pause(); if ( typeof self._options.autoplay === 'number' ) { self._playtime = self._options.autoplay; } self._playing = true; } // if second load, just do the show and return if ( self._firstrun ) { if ( self._options.autoplay ) { self.trigger( Galleria.PLAY ); } if ( typeof self._options.show === 'number' ) { self.show( self._options.show ); } return; } self._firstrun = true; // initialize the History plugin if ( Galleria.History ) { // bind the show method Galleria.History.change(function( value ) { // if ID is NaN, the user pressed back from the first image // return to previous address if ( isNaN( value ) ) { window.history.go(-1); // else show the image } else { self.show( value, undef, true ); } }); } self.trigger( Galleria.READY ); // call the theme init method Galleria.theme.init.call( self, self._options ); // Trigger Galleria.ready $.each( Galleria.ready.callbacks, function(i ,fn) { if ( typeof fn == 'function' ) { fn.call( self, self._options ); } }); // call the extend option self._options.extend.call( self, self._options ); // show the initial image // first test for permalinks in history if ( /^[0-9]{1,4}$/.test( HASH ) && Galleria.History ) { self.show( HASH, undef, true ); } else if( self._data[ self._options.show ] ) { self.show( self._options.show ); } // play trigger if ( self._options.autoplay ) { self.trigger( Galleria.PLAY ); } }, error: function() { Galleria.raise('Stage width or height is too small to show the gallery. Traced measures: width:' + self._stageWidth + 'px, height: ' + self._stageHeight + 'px.', true); } }); }, /** Loads data into the gallery. You can call this method on an existing gallery to reload the gallery with new data. @param {Array|string} [source] Optional JSON array of data or selector of where to find data in the document. Defaults to the Galleria target or dataSource option. @param {string} [selector] Optional element selector of what elements to parse. Defaults to 'img'. @param {Function} [config] Optional function to modify the data extraction proceedure from the selector. See the dataConfig option for more information. @returns Instance */ load : function( source, selector, config ) { var self = this, o = this._options; // empty the data array this._data = []; // empty the thumbnails this._thumbnails = []; this.$('thumbnails').empty(); // shorten the arguments if ( typeof selector === 'function' ) { config = selector; selector = null; } // use the source set by target source = source || o.dataSource; // use selector set by option selector = selector || o.dataSelector; // use the dataConfig set by option config = config || o.dataConfig; // if source is a true object, make it into an array if( $.isPlainObject( source ) ) { source = [source]; } // check if the data is an array already if ( $.isArray( source ) ) { if ( this.validate( source ) ) { this._data = source; } else { Galleria.raise( 'Load failed: JSON Array not valid.' ); } } else { // add .video and .iframe to the selector (1.2.7) selector += ',.video,.iframe'; // loop through images and set data $( source ).find( selector ).each( function( i, elem ) { elem = $( elem ); var data = {}, parent = elem.parent(), href = parent.attr( 'href' ), rel = parent.attr( 'rel' ); if( href && ( elem[0].nodeName == 'IMG' || elem.hasClass('video') ) && _videoTest( href ) ) { data.video = href; } else if( href && elem.hasClass('iframe') ) { data.iframe = href; } else { data.image = data.big = href; } if ( rel ) { data.big = rel; } // alternative extraction from HTML5 data attribute, added in 1.2.7 $.each( 'big title description link layer image'.split(' '), function( i, val ) { if ( elem.data(val) ) { data[ val ] = elem.data(val).toString(); } }); if ( !data.big ) { data.big = data.image; } // mix default extractions with the hrefs and config // and push it into the data array self._data.push( $.extend({ title: elem.attr('title') || '', thumb: elem.attr('src'), image: elem.attr('src'), big: elem.attr('src'), description: elem.attr('alt') || '', link: elem.attr('longdesc'), original: elem.get(0) // saved as a reference }, data, config( elem ) ) ); }); } if ( typeof o.dataSort == 'function' ) { protoArray.sort.call( this._data, o.dataSort ); } else if ( o.dataSort == 'random' ) { this._data.sort( function() { return M.round(M.random())-0.5; }); } // trigger the DATA event and return if ( this.getDataLength() ) { this._parseData( function() { this.trigger( Galleria.DATA ); } ); } return this; }, // make sure the data works properly _parseData : function( callback ) { var self = this, current, ready = false, onload = function() { var complete = true; $.each( self._data, function( i, data ) { if ( data.loading ) { complete = false; return false; } }); if ( complete && !ready ) { ready = true; callback.call( self ); } }; $.each( this._data, function( i, data ) { current = self._data[ i ]; // copy image as thumb if no thumb exists if ( 'thumb' in data === false ) { current.thumb = data.image; } // copy image as big image if no biggie exists if ( !data.big ) { current.big = data.image; } // parse video if ( 'video' in data ) { var result = _videoTest( data.video ); if ( result ) { current.iframe = new Video(result.provider, result.id ).embed() + (function() { // add options if ( typeof self._options[ result.provider ] == 'object' ) { var str = '?', arr = []; $.each( self._options[ result.provider ], function( key, val ) { arr.push( key + '=' + val ); }); // small youtube specifics, perhaps move to _video later if ( result.provider == 'youtube' ) { arr = ['wmode=opaque'].concat(arr); } return str + arr.join('&'); } return ''; }()); // pre-fetch video providers media if( !current.thumb || !current.image ) { $.each( ['thumb', 'image'], function( i, type ) { if ( type == 'image' && !self._options.videoPoster ) { current.image = undef; return; } var video = new Video( result.provider, result.id ); if ( !current[ type ] ) { current.loading = true; video.getMedia( type, (function(current, type) { return function(src) { current[ type ] = src; if ( type == 'image' && !current.big ) { current.big = current.image; } delete current.loading; onload(); }; }( current, type ))); } }); } } } }); onload(); return this; }, /** Destroy the Galleria instance and recover the original content @example this.destroy(); @returns Instance */ destroy : function() { this.$( 'target' ).data( 'galleria', null ); this.$( 'container' ).off( 'galleria' ); this.get( 'target' ).innerHTML = this._original.html; this.clearTimer(); Utils.removeFromArray( _instances, this ); Utils.removeFromArray( _galleries, this ); if ( Galleria._waiters.length ) { $.each( Galleria._waiters, function( i, w ) { if ( w ) window.clearTimeout( w ); }); } return this; }, /** Adds and/or removes images from the gallery Works just like Array.splice https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice @example this.splice( 2, 4 ); // removes 4 images after the second image @returns Instance */ splice : function() { var self = this, args = Utils.array( arguments ); window.setTimeout(function() { protoArray.splice.apply( self._data, args ); self._parseData( function() { self._createThumbnails(); }); },2); return self; }, /** Append images to the gallery Works just like Array.push https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push @example this.push({ image: 'image1.jpg' }); // appends the image to the gallery @returns Instance */ push : function() { var self = this, args = Utils.array( arguments ); if ( args.length == 1 && args[0].constructor == Array ) { args = args[0]; } window.setTimeout(function() { protoArray.push.apply( self._data, args ); self._parseData( function() { self._createThumbnails( args ); }); }, 2); return self; }, _getActive : function() { return this._controls.getActive(); }, validate : function( data ) { // todo: validate a custom data array return true; }, /** Bind any event to Galleria @param {string} type The Event type to listen for @param {Function} fn The function to execute when the event is triggered @example this.bind( 'image', function() { Galleria.log('image shown') }); @returns Instance */ bind : function(type, fn) { // allow 'image' instead of Galleria.IMAGE type = _patchEvent( type ); this.$( 'container' ).on( type, this.proxy(fn) ); return this; }, /** Unbind any event to Galleria @param {string} type The Event type to forget @returns Instance */ unbind : function(type) { type = _patchEvent( type ); this.$( 'container' ).off( type ); return this; }, /** Manually trigger a Galleria event @param {string} type The Event to trigger @returns Instance */ trigger : function( type ) { type = typeof type === 'object' ? $.extend( type, { scope: this } ) : { type: _patchEvent( type ), scope: this }; this.$( 'container' ).trigger( type ); return this; }, /** Assign an "idle state" to any element. The idle state will be applied after a certain amount of idle time Useful to hide f.ex navigation when the gallery is inactive @param {HTMLElement|string} elem The Dom node or selector to apply the idle state to @param {Object} styles the CSS styles to apply when in idle mode @param {Object} [from] the CSS styles to apply when in normal @param {Boolean} [hide] set to true if you want to hide it first @example addIdleState( this.get('image-nav'), { opacity: 0 }); @example addIdleState( '.galleria-image-nav', { top: -200 }, true); @returns Instance */ addIdleState: function( elem, styles, from, hide ) { this._idle.add.apply( this._idle, Utils.array( arguments ) ); return this; }, /** Removes any idle state previously set using addIdleState() @param {HTMLElement|string} elem The Dom node or selector to remove the idle state from. @returns Instance */ removeIdleState: function( elem ) { this._idle.remove.apply( this._idle, Utils.array( arguments ) ); return this; }, /** Force Galleria to enter idle mode. @returns Instance */ enterIdleMode: function() { this._idle.hide(); return this; }, /** Force Galleria to exit idle mode. @returns Instance */ exitIdleMode: function() { this._idle.showAll(); return this; }, /** Enter FullScreen mode @param {Function} callback the function to be executed when the fullscreen mode is fully applied. @returns Instance */ enterFullscreen: function( callback ) { this._fullscreen.enter.apply( this, Utils.array( arguments ) ); return this; }, /** Exits FullScreen mode @param {Function} callback the function to be executed when the fullscreen mode is fully applied. @returns Instance */ exitFullscreen: function( callback ) { this._fullscreen.exit.apply( this, Utils.array( arguments ) ); return this; }, /** Toggle FullScreen mode @param {Function} callback the function to be executed when the fullscreen mode is fully applied or removed. @returns Instance */ toggleFullscreen: function( callback ) { this._fullscreen[ this.isFullscreen() ? 'exit' : 'enter'].apply( this, Utils.array( arguments ) ); return this; }, /** Adds a tooltip to any element. You can also call this method with an object as argument with elemID:value pairs to apply tooltips to (see examples) @param {HTMLElement} elem The DOM Node to attach the event to @param {string|Function} value The tooltip message. Can also be a function that returns a string. @example this.bindTooltip( this.get('thumbnails'), 'My thumbnails'); @example this.bindTooltip( this.get('thumbnails'), function() { return 'My thumbs' }); @example this.bindTooltip( { image_nav: 'Navigation' }); @returns Instance */ bindTooltip: function( elem, value ) { this._tooltip.bind.apply( this._tooltip, Utils.array(arguments) ); return this; }, /** Note: this method is deprecated. Use refreshTooltip() instead. Redefine a tooltip. Use this if you want to re-apply a tooltip value to an already bound tooltip element. @param {HTMLElement} elem The DOM Node to attach the event to @param {string|Function} value The tooltip message. Can also be a function that returns a string. @returns Instance */ defineTooltip: function( elem, value ) { this._tooltip.define.apply( this._tooltip, Utils.array(arguments) ); return this; }, /** Refresh a tooltip value. Use this if you want to change the tooltip value at runtime, f.ex if you have a play/pause toggle. @param {HTMLElement} elem The DOM Node that has a tooltip that should be refreshed @returns Instance */ refreshTooltip: function( elem ) { this._tooltip.show.apply( this._tooltip, Utils.array(arguments) ); return this; }, /** Open a pre-designed lightbox with the currently active image. You can control some visuals using gallery options. @returns Instance */ openLightbox: function() { this._lightbox.show.apply( this._lightbox, Utils.array( arguments ) ); return this; }, /** Close the lightbox. @returns Instance */ closeLightbox: function() { this._lightbox.hide.apply( this._lightbox, Utils.array( arguments ) ); return this; }, /** Check if a variation exists @returns {Boolean} If the variation has been applied */ hasVariation: function( variation ) { return $.inArray( variation, this._options.variation.split(/\s+/) ) > -1; }, /** Get the currently active image element. @returns {HTMLElement} The image element */ getActiveImage: function() { var active = this._getActive(); return active ? active.image : undef; }, /** Get the currently active thumbnail element. @returns {HTMLElement} The thumbnail element */ getActiveThumb: function() { return this._thumbnails[ this._active ].image || undef; }, /** Get the mouse position relative to the gallery container @param e The mouse event @example var gallery = this; $(document).mousemove(function(e) { console.log( gallery.getMousePosition(e).x ); }); @returns {Object} Object with x & y of the relative mouse postion */ getMousePosition : function(e) { return { x: e.pageX - this.$( 'container' ).offset().left, y: e.pageY - this.$( 'container' ).offset().top }; }, /** Adds a panning effect to the image @param [img] The optional image element. If not specified it takes the currently active image @returns Instance */ addPan : function( img ) { if ( this._options.imageCrop === false ) { return; } img = $( img || this.getActiveImage() ); // define some variables and methods var self = this, x = img.width() / 2, y = img.height() / 2, destX = parseInt( img.css( 'left' ), 10 ), destY = parseInt( img.css( 'top' ), 10 ), curX = destX || 0, curY = destY || 0, distX = 0, distY = 0, active = false, ts = Utils.timestamp(), cache = 0, move = 0, // positions the image position = function( dist, cur, pos ) { if ( dist > 0 ) { move = M.round( M.max( dist * -1, M.min( 0, cur ) ) ); if ( cache !== move ) { cache = move; if ( IE === 8 ) { // scroll is faster for IE img.parent()[ 'scroll' + pos ]( move * -1 ); } else { var css = {}; css[ pos.toLowerCase() ] = move; img.css(css); } } } }, // calculates mouse position after 50ms calculate = function(e) { if (Utils.timestamp() - ts < 50) { return; } active = true; x = self.getMousePosition(e).x; y = self.getMousePosition(e).y; }, // the main loop to check loop = function(e) { if (!active) { return; } distX = img.width() - self._stageWidth; distY = img.height() - self._stageHeight; destX = x / self._stageWidth * distX * -1; destY = y / self._stageHeight * distY * -1; curX += ( destX - curX ) / self._options.imagePanSmoothness; curY += ( destY - curY ) / self._options.imagePanSmoothness; position( distY, curY, 'Top' ); position( distX, curX, 'Left' ); }; // we need to use scroll in IE8 to speed things up if ( IE === 8 ) { img.parent().scrollTop( curY * -1 ).scrollLeft( curX * -1 ); img.css({ top: 0, left: 0 }); } // unbind and bind event this.$( 'stage' ).off( 'mousemove', calculate ).on( 'mousemove', calculate ); // loop the loop this.addTimer( 'pan' + self._id, loop, 50, true); return this; }, /** Brings the scope into any callback @param fn The callback to bring the scope into @param [scope] Optional scope to bring @example $('#fullscreen').click( this.proxy(function() { this.enterFullscreen(); }) ) @returns {Function} Return the callback with the gallery scope */ proxy : function( fn, scope ) { if ( typeof fn !== 'function' ) { return F; } scope = scope || this; return function() { return fn.apply( scope, Utils.array( arguments ) ); }; }, /** Removes the panning effect set by addPan() @returns Instance */ removePan: function() { // todo: doublecheck IE8 this.$( 'stage' ).off( 'mousemove' ); this.clearTimer( 'pan' + this._id ); return this; }, /** Adds an element to the Galleria DOM array. When you add an element here, you can access it using element ID in many API calls @param {string} id The element ID you wish to use. You can add many elements by adding more arguments. @example addElement('mybutton'); @example addElement('mybutton','mylink'); @returns Instance */ addElement : function( id ) { var dom = this._dom; $.each( Utils.array(arguments), function( i, blueprint ) { dom[ blueprint ] = Utils.create( 'galleria-' + blueprint ); }); return this; }, /** Attach keyboard events to Galleria @param {Object} map The map object of events. Possible keys are 'UP', 'DOWN', 'LEFT', 'RIGHT', 'RETURN', 'ESCAPE', 'BACKSPACE', and 'SPACE'. @example this.attachKeyboard({ right: this.next, left: this.prev, up: function() { console.log( 'up key pressed' ) } }); @returns Instance */ attachKeyboard : function( map ) { this._keyboard.attach.apply( this._keyboard, Utils.array( arguments ) ); return this; }, /** Detach all keyboard events to Galleria @returns Instance */ detachKeyboard : function() { this._keyboard.detach.apply( this._keyboard, Utils.array( arguments ) ); return this; }, /** Fast helper for appending galleria elements that you added using addElement() @param {string} parentID The parent element ID where the element will be appended @param {string} childID the element ID that should be appended @example this.addElement('myElement'); this.appendChild( 'info', 'myElement' ); @returns Instance */ appendChild : function( parentID, childID ) { this.$( parentID ).append( this.get( childID ) || childID ); return this; }, /** Fast helper for prepending galleria elements that you added using addElement() @param {string} parentID The parent element ID where the element will be prepended @param {string} childID the element ID that should be prepended @example this.addElement('myElement'); this.prependChild( 'info', 'myElement' ); @returns Instance */ prependChild : function( parentID, childID ) { this.$( parentID ).prepend( this.get( childID ) || childID ); return this; }, /** Remove an element by blueprint @param {string} elemID The element to be removed. You can remove multiple elements by adding arguments. @returns Instance */ remove : function( elemID ) { this.$( Utils.array( arguments ).join(',') ).remove(); return this; }, // a fast helper for building dom structures // leave this out of the API for now append : function( data ) { var i, j; for( i in data ) { if ( data.hasOwnProperty( i ) ) { if ( data[i].constructor === Array ) { for( j = 0; data[i][j]; j++ ) { this.appendChild( i, data[i][j] ); } } else { this.appendChild( i, data[i] ); } } } return this; }, // an internal helper for scaling according to options _scaleImage : function( image, options ) { image = image || this._controls.getActive(); // janpub (JH) fix: // image might be unselected yet // e.g. when external logics rescales the gallery on window resize events if( !image ) { return; } var complete, scaleLayer = function( img ) { $( img.container ).children(':first').css({ top: M.max(0, Utils.parseValue( img.image.style.top )), left: M.max(0, Utils.parseValue( img.image.style.left )), width: Utils.parseValue( img.image.width ), height: Utils.parseValue( img.image.height ) }); }; options = $.extend({ width: this._stageWidth, height: this._stageHeight, crop: this._options.imageCrop, max: this._options.maxScaleRatio, min: this._options.minScaleRatio, margin: this._options.imageMargin, position: this._options.imagePosition, iframelimit: this._options.maxVideoSize }, options ); if ( this._options.layerFollow && this._options.imageCrop !== true ) { if ( typeof options.complete == 'function' ) { complete = options.complete; options.complete = function() { complete.call( image, image ); scaleLayer( image ); }; } else { options.complete = scaleLayer; } } else { $( image.container ).children(':first').css({ top: 0, left: 0 }); } image.scale( options ); return this; }, /** Updates the carousel, useful if you resize the gallery and want to re-check if the carousel nav is needed. @returns Instance */ updateCarousel : function() { this._carousel.update(); return this; }, /** Resize the entire gallery container @param {Object} [measures] Optional object with width/height specified @param {Function} [complete] The callback to be called when the scaling is complete @returns Instance */ resize : function( measures, complete ) { if ( typeof measures == 'function' ) { complete = measures; measures = undef; } measures = $.extend( { width:0, height:0 }, measures ); var self = this, $container = this.$( 'container' ); $.each( measures, function( m, val ) { if ( !val ) { $container[ m ]( 'auto' ); measures[ m ] = self._getWH()[ m ]; } }); $.each( measures, function( m, val ) { $container[ m ]( val ); }); return this.rescale( complete ); }, /** Rescales the gallery @param {number} width The target width @param {number} height The target height @param {Function} complete The callback to be called when the scaling is complete @returns Instance */ rescale : function( width, height, complete ) { var self = this; // allow rescale(fn) if ( typeof width === 'function' ) { complete = width; width = undef; } var scale = function() { // set stagewidth self._stageWidth = width || self.$( 'stage' ).width(); self._stageHeight = height || self.$( 'stage' ).height(); if ( self._options.swipe ) { $.each( self._controls.slides, function(i, img) { self._scaleImage( img ); $( img.container ).css('left', self._stageWidth * i); }); self.$('images').css('width', self._stageWidth * self.getDataLength()); } else { // scale the active image self._scaleImage(); } if ( self._options.carousel ) { self.updateCarousel(); } var frame = self._controls.frames[ self._controls.active ]; if (frame) { self._controls.frames[ self._controls.active ].scale({ width: self._stageWidth, height: self._stageHeight, iframelimit: self._options.maxVideoSize }); } self.trigger( Galleria.RESCALE ); if ( typeof complete === 'function' ) { complete.call( self ); } }; scale.call( self ); return this; }, /** Refreshes the gallery. Useful if you change image options at runtime and want to apply the changes to the active image. @returns Instance */ refreshImage : function() { this._scaleImage(); if ( this._options.imagePan ) { this.addPan(); } return this; }, _preload: function() { if ( this._options.preload ) { var p, i, n = this.getNext(), ndata; try { for ( i = this._options.preload; i > 0; i-- ) { p = new Galleria.Picture(); ndata = this.getData( n ); p.preload( this.isFullscreen() && ndata.big ? ndata.big : ndata.image ); n = this.getNext( n ); } } catch(e) {} } }, /** Shows an image by index @param {number|boolean} index The index to show @param {Boolean} rewind A boolean that should be true if you want the transition to go back @returns Instance */ show : function( index, rewind, _history ) { var swipe = this._options.swipe; // do nothing queue is long || index is false || queue is false and transition is in progress if ( !swipe && ( this._queue.length > 3 || index === false || ( !this._options.queue && this._queue.stalled ) ) ) { return; } index = M.max( 0, M.min( parseInt( index, 10 ), this.getDataLength() - 1 ) ); rewind = typeof rewind !== 'undefined' ? !!rewind : index < this.getIndex(); _history = _history || false; // do the history thing and return if ( !_history && Galleria.History ) { Galleria.History.set( index.toString() ); return; } if ( this.finger && index !== this._active ) { this.finger.to = -( index*this.finger.width ); this.finger.index = index; } this._active = index; // we do things a bit simpler in swipe: if ( swipe ) { var data = this.getData(index), self = this; if ( !data ) { return; } var src = this.isFullscreen() && data.big ? data.big : ( data.image || data.iframe ), image = this._controls.slides[index], cached = image.isCached( src ), thumb = this._thumbnails[ index ]; var evObj = { cached: cached, index: index, rewind: rewind, imageTarget: image.image, thumbTarget: thumb.image, galleriaData: data }; this.trigger($.extend(evObj, { type: Galleria.LOADSTART })); self.$('container').removeClass( 'videoplay' ); var complete = function() { self._layers[index].innerHTML = self.getData().layer || ''; self.trigger($.extend(evObj, { type: Galleria.LOADFINISH })); self._playCheck(); }; self._preload(); window.setTimeout(function() { // load if not ready if ( !image.ready || $(image.image).attr('src') != src ) { if ( data.iframe && !data.image ) { image.isIframe = true; } image.load(src, function(image) { evObj.imageTarget = image.image; self._scaleImage(image, complete).trigger($.extend(evObj, { type: Galleria.IMAGE })); complete(); }); } else { self.trigger($.extend(evObj, { type: Galleria.IMAGE })); complete(); } }, 100); } else { protoArray.push.call( this._queue, { index : index, rewind : rewind }); if ( !this._queue.stalled ) { this._show(); } } return this; }, // the internal _show method does the actual showing _show : function() { // shortcuts var self = this, queue = this._queue[ 0 ], data = this.getData( queue.index ); if ( !data ) { return; } var src = this.isFullscreen() && data.big ? data.big : ( data.image || data.iframe ), active = this._controls.getActive(), next = this._controls.getNext(), cached = next.isCached( src ), thumb = this._thumbnails[ queue.index ], mousetrigger = function() { $( next.image ).trigger( 'mouseup' ); }; self.$('container').toggleClass('iframe', !!data.isIframe).removeClass( 'videoplay' ); // to be fired when loading & transition is complete: var complete = (function( data, next, active, queue, thumb ) { return function() { var win; _transitions.active = false; // optimize quality Utils.toggleQuality( next.image, self._options.imageQuality ); // remove old layer self._layers[ self._controls.active ].innerHTML = ''; // swap $( active.container ).css({ zIndex: 0, opacity: 0 }).show(); $( active.container ).find( 'iframe, .galleria-videoicon' ).remove(); $( self._controls.frames[ self._controls.active ].container ).hide(); $( next.container ).css({ zIndex: 1, left: 0, top: 0 }).show(); self._controls.swap(); // add pan according to option if ( self._options.imagePan ) { self.addPan( next.image ); } // make the image clickable // order of precedence: iframe, link, lightbox, clicknext if ( ( data.iframe && data.image ) || data.link || self._options.lightbox || self._options.clicknext ) { $( next.image ).css({ cursor: 'pointer' }).on( 'mouseup', function( e ) { // non-left click if ( typeof e.which == 'number' && e.which > 1 ) { return; } // iframe / video if ( data.iframe ) { if ( self.isPlaying() ) { self.pause(); } var frame = self._controls.frames[ self._controls.active ], w = self._stageWidth, h = self._stageHeight; $( frame.container ).css({ width: w, height: h, opacity: 0 }).show().animate({ opacity: 1 }, 200); window.setTimeout(function() { frame.load( data.iframe + ( data.video ? '&autoplay=1' : '' ), { width: w, height: h }, function( frame ) { self.$( 'container' ).addClass( 'videoplay' ); frame.scale({ width: self._stageWidth, height: self._stageHeight, iframelimit: data.video ? self._options.maxVideoSize : undef }); }); }, 100); return; } // clicknext if ( self._options.clicknext && !Galleria.TOUCH ) { if ( self._options.pauseOnInteraction ) { self.pause(); } self.next(); return; } // popup link if ( data.link ) { if ( self._options.popupLinks ) { win = window.open( data.link, '_blank' ); } else { window.location.href = data.link; } return; } if ( self._options.lightbox ) { self.openLightbox(); } }); } // check if we are playing self._playCheck(); // trigger IMAGE event self.trigger({ type: Galleria.IMAGE, index: queue.index, imageTarget: next.image, thumbTarget: thumb.image, galleriaData: data }); // remove the queued image protoArray.shift.call( self._queue ); // remove stalled self._queue.stalled = false; // if we still have images in the queue, show it if ( self._queue.length ) { self._show(); } }; }( data, next, active, queue, thumb )); // let the carousel follow if ( this._options.carousel && this._options.carouselFollow ) { this._carousel.follow( queue.index ); } // preload images self._preload(); // show the next image, just in case Utils.show( next.container ); next.isIframe = data.iframe && !data.image; // add active classes $( self._thumbnails[ queue.index ].container ) .addClass( 'active' ) .siblings( '.active' ) .removeClass( 'active' ); // trigger the LOADSTART event self.trigger( { type: Galleria.LOADSTART, cached: cached, index: queue.index, rewind: queue.rewind, imageTarget: next.image, thumbTarget: thumb.image, galleriaData: data }); // stall the queue self._queue.stalled = true; // begin loading the next image next.load( src, function( next ) { // add layer HTML var layer = $( self._layers[ 1-self._controls.active ] ).html( data.layer || '' ).hide(); self._scaleImage( next, { complete: function( next ) { // toggle low quality for IE if ( 'image' in active ) { Utils.toggleQuality( active.image, false ); } Utils.toggleQuality( next.image, false ); // remove the image panning, if applied // TODO: rethink if this is necessary self.removePan(); // set the captions and counter self.setInfo( queue.index ); self.setCounter( queue.index ); // show the layer now if ( data.layer ) { layer.show(); // inherit click events set on image if ( ( data.iframe && data.image ) || data.link || self._options.lightbox || self._options.clicknext ) { layer.css( 'cursor', 'pointer' ).off( 'mouseup' ).mouseup( mousetrigger ); } } // add play icon if( data.video && data.image ) { _playIcon( next.container ); } var transition = self._options.transition; // can JavaScript loop through objects in order? yes. $.each({ initial: active.image === null, touch: Galleria.TOUCH, fullscreen: self.isFullscreen() }, function( type, arg ) { if ( arg && self._options[ type + 'Transition' ] !== undef ) { transition = self._options[ type + 'Transition' ]; return false; } }); // validate the transition if ( transition in _transitions.effects === false ) { complete(); } else { var params = { prev: active.container, next: next.container, rewind: queue.rewind, speed: self._options.transitionSpeed || 400 }; _transitions.active = true; // call the transition function and send some stuff _transitions.init.call( self, transition, params, complete ); } // trigger the LOADFINISH event self.trigger({ type: Galleria.LOADFINISH, cached: cached, index: queue.index, rewind: queue.rewind, imageTarget: next.image, thumbTarget: self._thumbnails[ queue.index ].image, galleriaData: self.getData( queue.index ) }); } }); }); }, /** Gets the next index @param {number} [base] Optional starting point @returns {number} the next index, or the first if you are at the first (looping) */ getNext : function( base ) { base = typeof base === 'number' ? base : this.getIndex(); return base === this.getDataLength() - 1 ? 0 : base + 1; }, /** Gets the previous index @param {number} [base] Optional starting point @returns {number} the previous index, or the last if you are at the first (looping) */ getPrev : function( base ) { base = typeof base === 'number' ? base : this.getIndex(); return base === 0 ? this.getDataLength() - 1 : base - 1; }, /** Shows the next image in line @returns Instance */ next : function() { if ( this.getDataLength() > 1 ) { this.show( this.getNext(), false ); } return this; }, /** Shows the previous image in line @returns Instance */ prev : function() { if ( this.getDataLength() > 1 ) { this.show( this.getPrev(), true ); } return this; }, /** Retrieve a DOM element by element ID @param {string} elemId The delement ID to fetch @returns {HTMLElement} The elements DOM node or null if not found. */ get : function( elemId ) { return elemId in this._dom ? this._dom[ elemId ] : null; }, /** Retrieve a data object @param {number} index The data index to retrieve. If no index specified it will take the currently active image @returns {Object} The data object */ getData : function( index ) { return index in this._data ? this._data[ index ] : this._data[ this._active ]; }, /** Retrieve the number of data items @returns {number} The data length */ getDataLength : function() { return this._data.length; }, /** Retrieve the currently active index @returns {number|boolean} The active index or false if none found */ getIndex : function() { return typeof this._active === 'number' ? this._active : false; }, /** Retrieve the stage height @returns {number} The stage height */ getStageHeight : function() { return this._stageHeight; }, /** Retrieve the stage width @returns {number} The stage width */ getStageWidth : function() { return this._stageWidth; }, /** Retrieve the option @param {string} key The option key to retrieve. If no key specified it will return all options in an object. @returns option or options */ getOptions : function( key ) { return typeof key === 'undefined' ? this._options : this._options[ key ]; }, /** Set options to the instance. You can set options using a key & value argument or a single object argument (see examples) @param {string} key The option key @param {string} value the the options value @example setOptions( 'autoplay', true ) @example setOptions({ autoplay: true }); @returns Instance */ setOptions : function( key, value ) { if ( typeof key === 'object' ) { $.extend( this._options, key ); } else { this._options[ key ] = value; } return this; }, /** Starts playing the slideshow @param {number} delay Sets the slideshow interval in milliseconds. If you set it once, you can just call play() and get the same interval the next time. @returns Instance */ play : function( delay ) { this._playing = true; this._playtime = delay || this._playtime; this._playCheck(); this.trigger( Galleria.PLAY ); return this; }, /** Stops the slideshow if currently playing @returns Instance */ pause : function() { this._playing = false; this.trigger( Galleria.PAUSE ); return this; }, /** Toggle between play and pause events. @param {number} delay Sets the slideshow interval in milliseconds. @returns Instance */ playToggle : function( delay ) { return ( this._playing ) ? this.pause() : this.play( delay ); }, /** Checks if the gallery is currently playing @returns {Boolean} */ isPlaying : function() { return this._playing; }, /** Checks if the gallery is currently in fullscreen mode @returns {Boolean} */ isFullscreen : function() { return this._fullscreen.active; }, _playCheck : function() { var self = this, played = 0, interval = 20, now = Utils.timestamp(), timer_id = 'play' + this._id; if ( this._playing ) { this.clearTimer( timer_id ); var fn = function() { played = Utils.timestamp() - now; if ( played >= self._playtime && self._playing ) { self.clearTimer( timer_id ); self.next(); return; } if ( self._playing ) { // trigger the PROGRESS event self.trigger({ type: Galleria.PROGRESS, percent: M.ceil( played / self._playtime * 100 ), seconds: M.floor( played / 1000 ), milliseconds: played }); self.addTimer( timer_id, fn, interval ); } }; self.addTimer( timer_id, fn, interval ); } }, /** Modify the slideshow delay @param {number} delay the number of milliseconds between slides, @returns Instance */ setPlaytime: function( delay ) { this._playtime = delay; return this; }, setIndex: function( val ) { this._active = val; return this; }, /** Manually modify the counter @param {number} [index] Optional data index to fectch, if no index found it assumes the currently active index @returns Instance */ setCounter: function( index ) { if ( typeof index === 'number' ) { index++; } else if ( typeof index === 'undefined' ) { index = this.getIndex()+1; } this.get( 'current' ).innerHTML = index; if ( IE ) { // weird IE bug var count = this.$( 'counter' ), opacity = count.css( 'opacity' ); if ( parseInt( opacity, 10 ) === 1) { Utils.removeAlpha( count[0] ); } else { this.$( 'counter' ).css( 'opacity', opacity ); } } return this; }, /** Manually set captions @param {number} [index] Optional data index to fectch and apply as caption, if no index found it assumes the currently active index @returns Instance */ setInfo : function( index ) { var self = this, data = this.getData( index ); $.each( ['title','description'], function( i, type ) { var elem = self.$( 'info-' + type ); if ( !!data[type] ) { elem[ data[ type ].length ? 'show' : 'hide' ]().html( data[ type ] ); } else { elem.empty().hide(); } }); return this; }, /** Checks if the data contains any captions @param {number} [index] Optional data index to fectch, if no index found it assumes the currently active index. @returns {boolean} */ hasInfo : function( index ) { var check = 'title description'.split(' '), i; for ( i = 0; check[i]; i++ ) { if ( !!this.getData( index )[ check[i] ] ) { return true; } } return false; }, jQuery : function( str ) { var self = this, ret = []; $.each( str.split(','), function( i, elemId ) { elemId = $.trim( elemId ); if ( self.get( elemId ) ) { ret.push( elemId ); } }); var jQ = $( self.get( ret.shift() ) ); $.each( ret, function( i, elemId ) { jQ = jQ.add( self.get( elemId ) ); }); return jQ; }, /** Converts element IDs into a jQuery collection You can call for multiple IDs separated with commas. @param {string} str One or more element IDs (comma-separated) @returns jQuery @example this.$('info,container').hide(); */ $ : function( str ) { return this.jQuery.apply( this, Utils.array( arguments ) ); } }; // End of Galleria prototype // Add events as static variables $.each( _events, function( i, ev ) { // legacy events var type = /_/.test( ev ) ? ev.replace( /_/g, '' ) : ev; Galleria[ ev.toUpperCase() ] = 'galleria.'+type; } ); $.extend( Galleria, { // Browser helpers IE9: IE === 9, IE8: IE === 8, IE7: IE === 7, IE6: IE === 6, IE: IE, WEBKIT: /webkit/.test( NAV ), CHROME: /chrome/.test( NAV ), SAFARI: /safari/.test( NAV ) && !(/chrome/.test( NAV )), QUIRK: ( IE && doc.compatMode && doc.compatMode === "BackCompat" ), MAC: /mac/.test( navigator.platform.toLowerCase() ), OPERA: !!window.opera, IPHONE: /iphone/.test( NAV ), IPAD: /ipad/.test( NAV ), ANDROID: /android/.test( NAV ), TOUCH: ('ontouchstart' in doc) }); // Galleria static methods /** Adds a theme that you can use for your Gallery @param {Object} theme Object that should contain all your theme settings. <ul> <li>name - name of the theme</li> <li>author - name of the author</li> <li>css - css file name (not path)</li> <li>defaults - default options to apply, including theme-specific options</li> <li>init - the init function</li> </ul> @returns {Object} theme */ Galleria.addTheme = function( theme ) { // make sure we have a name if ( !theme.name ) { Galleria.raise('No theme name specified'); } if ( typeof theme.defaults !== 'object' ) { theme.defaults = {}; } else { theme.defaults = _legacyOptions( theme.defaults ); } var css = false, reg; if ( typeof theme.css === 'string' ) { // look for manually added CSS $('link').each(function( i, link ) { reg = new RegExp( theme.css ); if ( reg.test( link.href ) ) { // we found the css css = true; // the themeload trigger _themeLoad( theme ); return false; } }); // else look for the absolute path and load the CSS dynamic if ( !css ) { $(function() { // Try to determine the css-path from the theme script. // In IE8/9, the script-dom-element seems to be not present // at once, if galleria itself is inserted into the dom // dynamically. We therefore try multiple times before raising // an error. var retryCount = 0; var tryLoadCss = function() { $('script').each(function (i, script) { // look for the theme script reg = new RegExp('galleria\\.' + theme.name.toLowerCase() + '\\.'); if (reg.test(script.src)) { // we have a match css = script.src.replace(/[^\/]*$/, '') + theme.css; window.setTimeout(function () { Utils.loadCSS(css, 'galleria-theme', function () { // the themeload trigger _themeLoad(theme); }); }, 1); } }); if (!css) { if (retryCount++ > 5) { Galleria.raise('No theme CSS loaded'); } else { window.setTimeout(tryLoadCss, 500); } } }; tryLoadCss(); }); } } else { // pass _themeLoad( theme ); } return theme; }; /** loadTheme loads a theme js file and attaches a load event to Galleria @param {string} src The relative path to the theme source file @param {Object} [options] Optional options you want to apply @returns Galleria */ Galleria.loadTheme = function( src, options ) { // Don't load if theme is already loaded if( $('script').filter(function() { return $(this).attr('src') == src; }).length ) { return; } var loaded = false, err; // start listening for the timeout onload $( window ).load( function() { if ( !loaded ) { // give it another 20 seconds err = window.setTimeout(function() { if ( !loaded && !Galleria.theme ) { Galleria.raise( "Galleria had problems loading theme at " + src + ". Please check theme path or load manually.", true ); } }, 20000); } }); // first clear the current theme, if exists Galleria.unloadTheme(); // load the theme Utils.loadScript( src, function() { loaded = true; window.clearTimeout( err ); }); return Galleria; }; /** unloadTheme unloads the Galleria theme and prepares for a new theme @returns Galleria */ Galleria.unloadTheme = function() { if ( typeof Galleria.theme == 'object' ) { $('script').each(function( i, script ) { if( new RegExp( 'galleria\\.' + Galleria.theme.name + '\\.' ).test( script.src ) ) { $( script ).remove(); } }); Galleria.theme = undef; } return Galleria; }; /** Retrieves a Galleria instance. @param {number} [index] Optional index to retrieve. If no index is supplied, the method will return all instances in an array. @returns Instance or Array of instances */ Galleria.get = function( index ) { if ( !!_instances[ index ] ) { return _instances[ index ]; } else if ( typeof index !== 'number' ) { return _instances; } else { Galleria.raise('Gallery index ' + index + ' not found'); } }; /** Configure Galleria options via a static function. The options will be applied to all instances @param {string|object} key The options to apply or a key @param [value] If key is a string, this is the value @returns Galleria */ Galleria.configure = function( key, value ) { var opts = {}; if( typeof key == 'string' && value ) { opts[key] = value; key = opts; } else { $.extend( opts, key ); } Galleria.configure.options = opts; $.each( Galleria.get(), function(i, instance) { instance.setOptions( opts ); }); return Galleria; }; Galleria.configure.options = {}; /** Bind a Galleria event to the gallery @param {string} type A string representing the galleria event @param {function} callback The function that should run when the event is triggered @returns Galleria */ Galleria.on = function( type, callback ) { if ( !type ) { return; } callback = callback || F; // hash the bind var hash = type + callback.toString().replace(/\s/g,'') + Utils.timestamp(); // for existing instances $.each( Galleria.get(), function(i, instance) { instance._binds.push( hash ); instance.bind( type, callback ); }); // for future instances Galleria.on.binds.push({ type: type, callback: callback, hash: hash }); return Galleria; }; Galleria.on.binds = []; /** Run Galleria Alias for $(selector).galleria(options) @param {string} selector A selector of element(s) to intialize galleria to @param {object} options The options to apply @returns Galleria */ Galleria.run = function( selector, options ) { if ( $.isFunction( options ) ) { options = { extend: options }; } $( selector || '#galleria' ).galleria( options ); return Galleria; }; /** Creates a transition to be used in your gallery @param {string} name The name of the transition that you will use as an option @param {Function} fn The function to be executed in the transition. The function contains two arguments, params and complete. Use the params Object to integrate the transition, and then call complete when you are done. @returns Galleria */ Galleria.addTransition = function( name, fn ) { _transitions.effects[name] = fn; return Galleria; }; /** The Galleria utilites */ Galleria.utils = Utils; /** A helper metod for cross-browser logging. It uses the console log if available otherwise it falls back to alert @example Galleria.log("hello", document.body, [1,2,3]); */ Galleria.log = function() { var args = Utils.array( arguments ); if( 'console' in window && 'log' in window.console ) { try { return window.console.log.apply( window.console, args ); } catch( e ) { $.each( args, function() { window.console.log(this); }); } } else { return window.alert( args.join('<br>') ); } }; /** A ready method for adding callbacks when a gallery is ready Each method is call before the extend option for every instance @param {function} callback The function to call @returns Galleria */ Galleria.ready = function( fn ) { if ( typeof fn != 'function' ) { return Galleria; } $.each( _galleries, function( i, gallery ) { fn.call( gallery, gallery._options ); }); Galleria.ready.callbacks.push( fn ); return Galleria; }; Galleria.ready.callbacks = []; /** Method for raising errors @param {string} msg The message to throw @param {boolean} [fatal] Set this to true to override debug settings and display a fatal error */ Galleria.raise = function( msg, fatal ) { var type = fatal ? 'Fatal error' : 'Error', css = { color: '#fff', position: 'absolute', top: 0, left: 0, zIndex: 100000 }, echo = function( msg ) { var html = '<div style="padding:4px;margin:0 0 2px;background:#' + ( fatal ? '811' : '222' ) + ';">' + ( fatal ? '<strong>' + type + ': </strong>' : '' ) + msg + '</div>'; $.each( _instances, function() { var cont = this.$( 'errors' ), target = this.$( 'target' ); if ( !cont.length ) { target.css( 'position', 'relative' ); cont = this.addElement( 'errors' ).appendChild( 'target', 'errors' ).$( 'errors' ).css(css); } cont.append( html ); }); if ( !_instances.length ) { $('<div>').css( $.extend( css, { position: 'fixed' } ) ).append( html ).appendTo( DOM().body ); } }; // if debug is on, display errors and throw exception if fatal if ( DEBUG ) { echo( msg ); if ( fatal ) { throw new Error(type + ': ' + msg); } // else just echo a silent generic error if fatal } else if ( fatal ) { if ( _hasError ) { return; } _hasError = true; fatal = false; echo( 'Gallery could not load.' ); } }; // Add the version Galleria.version = VERSION; /** A method for checking what version of Galleria the user has installed and throws a readable error if the user needs to upgrade. Useful when building plugins that requires a certain version to function. @param {number} version The minimum version required @param {string} [msg] Optional message to display. If not specified, Galleria will throw a generic error. @returns Galleria */ Galleria.requires = function( version, msg ) { msg = msg || 'You need to upgrade Galleria to version ' + version + ' to use one or more components.'; if ( Galleria.version < version ) { Galleria.raise(msg, true); } return Galleria; }; /** Adds preload, cache, scale and crop functionality @constructor @requires jQuery @param {number} [id] Optional id to keep track of instances */ Galleria.Picture = function( id ) { // save the id this.id = id || null; // the image should be null until loaded this.image = null; // Create a new container this.container = Utils.create('galleria-image'); // add container styles $( this.container ).css({ overflow: 'hidden', position: 'relative' // for IE Standards mode }); // saves the original measurements this.original = { width: 0, height: 0 }; // flag when the image is ready this.ready = false; // flag for iframe Picture this.isIframe = false; }; Galleria.Picture.prototype = { // the inherited cache object cache: {}, // show the image on stage show: function() { Utils.show( this.image ); }, // hide the image hide: function() { Utils.moveOut( this.image ); }, clear: function() { this.image = null; }, /** Checks if an image is in cache @param {string} src The image source path, ex '/path/to/img.jpg' @returns {boolean} */ isCached: function( src ) { return !!this.cache[src]; }, /** Preloads an image into the cache @param {string} src The image source path, ex '/path/to/img.jpg' @returns Galleria.Picture */ preload: function( src ) { $( new Image() ).load((function(src, cache) { return function() { cache[ src ] = src; }; }( src, this.cache ))).attr( 'src', src ); }, /** Loads an image and call the callback when ready. Will also add the image to cache. @param {string} src The image source path, ex '/path/to/img.jpg' @param {Object} [size] The forced size of the image, defined as an object { width: xx, height:xx } @param {Function} callback The function to be executed when the image is loaded & scaled @returns The image container (jQuery object) */ load: function(src, size, callback) { if ( typeof size == 'function' ) { callback = size; size = null; } if( this.isIframe ) { var id = 'if'+new Date().getTime(); var iframe = this.image = $('<iframe>', { src: src, frameborder: 0, id: id, allowfullscreen: true, css: { visibility: 'hidden' } })[0]; if ( size ) { $( iframe ).css( size ); } $( this.container ).find( 'iframe,img' ).remove(); this.container.appendChild( this.image ); $('#'+id).load( (function( self, callback ) { return function() { window.setTimeout(function() { $( self.image ).css( 'visibility', 'visible' ); if( typeof callback == 'function' ) { callback.call( self, self ); } }, 10); }; }( this, callback ))); return this.container; } this.image = new Image(); // IE8 opacity inherit bug if ( Galleria.IE8 ) { $( this.image ).css( 'filter', 'inherit' ); } var reload = false, resort = false, // some jquery cache $container = $( this.container ), $image = $( this.image ), onerror = function() { if ( !reload ) { reload = true; // reload the image with a timestamp window.setTimeout((function(image, src) { return function() { image.attr('src', src + (src.indexOf('?') > -1 ? '&' : '?') + Utils.timestamp() ); }; }( $(this), src )), 50); } else { // apply the dummy image if it exists if ( DUMMY ) { $( this ).attr( 'src', DUMMY ); } else { Galleria.raise('Image not found: ' + src); } } }, // the onload method onload = (function( self, callback, src ) { return function() { var complete = function() { $( this ).off( 'load' ); // save the original size self.original = size || { height: this.height, width: this.width }; // translate3d if needed if ( Galleria.HAS3D ) { this.style.MozTransform = this.style.webkitTransform = 'translate3d(0,0,0)'; } $container.append( this ); self.cache[ src ] = src; // will override old cache if (typeof callback == 'function' ) { window.setTimeout(function() { callback.call( self, self ); },1); } }; // Delay the callback to "fix" the Adblock Bug // http://code.google.com/p/adblockforchrome/issues/detail?id=3701 if ( ( !this.width || !this.height ) ) { (function( img ) { Utils.wait({ until: function() { return img.width && img.height; }, success: function() { complete.call( img ); }, error: function() { if ( !resort ) { $(new Image()).load( onload ).attr( 'src', img.src ); resort = true; } else { Galleria.raise('Could not extract width/height from image: ' + img.src + '. Traced measures: width:' + img.width + 'px, height: ' + img.height + 'px.'); } }, timeout: 100 }); }( this )); } else { complete.call( this ); } }; }( this, callback, src )); // remove any previous images $container.find( 'iframe,img' ).remove(); // append the image $image.css( 'display', 'block'); // hide it for now Utils.hide( this.image ); // remove any max/min scaling $.each('minWidth minHeight maxWidth maxHeight'.split(' '), function(i, prop) { $image.css(prop, (/min/.test(prop) ? '0' : 'none')); }); // begin load and insert in cache when done $image.load( onload ).on( 'error', onerror ).attr( 'src', src ); // return the container return this.container; }, /** Scales and crops the image @param {Object} options The method takes an object with a number of options: <ul> <li>width - width of the container</li> <li>height - height of the container</li> <li>min - minimum scale ratio</li> <li>max - maximum scale ratio</li> <li>margin - distance in pixels from the image border to the container</li> <li>complete - a callback that fires when scaling is complete</li> <li>position - positions the image, works like the css background-image property.</li> <li>crop - defines how to crop. Can be true, false, 'width' or 'height'</li> <li>canvas - set to true to try a canvas-based rescale</li> </ul> @returns The image container object (jQuery) */ scale: function( options ) { var self = this; // extend some defaults options = $.extend({ width: 0, height: 0, min: undef, max: undef, margin: 0, complete: F, position: 'center', crop: false, canvas: false, iframelimit: undef }, options); if( this.isIframe ) { var cw = options.width, ch = options.height, nw, nh; if ( options.iframelimit ) { var r = M.min( options.iframelimit/cw, options.iframelimit/ch ); if ( r < 1 ) { nw = cw * r; nh = ch * r; $( this.image ).css({ top: ch/2-nh/2, left: cw/2-nw/2, position: 'absolute' }); } else { $( this.image ).css({ top: 0, left: 0 }); } } $( this.image ).width( nw || cw ).height( nh || ch ).removeAttr( 'width' ).removeAttr( 'height' ); $( this.container ).width( cw ).height( ch ); options.complete.call(self, self); try { if( this.image.contentWindow ) { $( this.image.contentWindow ).trigger('resize'); } } catch(e) {} return this.container; } // return the element if no image found if (!this.image) { return this.container; } // store locale variables var width, height, $container = $( self.container ), data; // wait for the width/height Utils.wait({ until: function() { width = options.width || $container.width() || Utils.parseValue( $container.css('width') ); height = options.height || $container.height() || Utils.parseValue( $container.css('height') ); return width && height; }, success: function() { // calculate some cropping var newWidth = ( width - options.margin * 2 ) / self.original.width, newHeight = ( height - options.margin * 2 ) / self.original.height, min = M.min( newWidth, newHeight ), max = M.max( newWidth, newHeight ), cropMap = { 'true' : max, 'width' : newWidth, 'height': newHeight, 'false' : min, 'landscape': self.original.width > self.original.height ? max : min, 'portrait': self.original.width < self.original.height ? max : min }, ratio = cropMap[ options.crop.toString() ], canvasKey = ''; // allow maxScaleRatio if ( options.max ) { ratio = M.min( options.max, ratio ); } // allow minScaleRatio if ( options.min ) { ratio = M.max( options.min, ratio ); } $.each( ['width','height'], function( i, m ) { $( self.image )[ m ]( self[ m ] = self.image[ m ] = M.round( self.original[ m ] * ratio ) ); }); $( self.container ).width( width ).height( height ); if ( options.canvas && _canvas ) { _canvas.elem.width = self.width; _canvas.elem.height = self.height; canvasKey = self.image.src + ':' + self.width + 'x' + self.height; self.image.src = _canvas.cache[ canvasKey ] || (function( key ) { _canvas.context.drawImage(self.image, 0, 0, self.original.width*ratio, self.original.height*ratio); try { data = _canvas.elem.toDataURL(); _canvas.length += data.length; _canvas.cache[ key ] = data; return data; } catch( e ) { return self.image.src; } }( canvasKey ) ); } // calculate image_position var pos = {}, mix = {}, getPosition = function(value, measure, margin) { var result = 0; if (/\%/.test(value)) { var flt = parseInt( value, 10 ) / 100, m = self.image[ measure ] || $( self.image )[ measure ](); result = M.ceil( m * -1 * flt + margin * flt ); } else { result = Utils.parseValue( value ); } return result; }, positionMap = { 'top': { top: 0 }, 'left': { left: 0 }, 'right': { left: '100%' }, 'bottom': { top: '100%' } }; $.each( options.position.toLowerCase().split(' '), function( i, value ) { if ( value === 'center' ) { value = '50%'; } pos[i ? 'top' : 'left'] = value; }); $.each( pos, function( i, value ) { if ( positionMap.hasOwnProperty( value ) ) { $.extend( mix, positionMap[ value ] ); } }); pos = pos.top ? $.extend( pos, mix ) : mix; pos = $.extend({ top: '50%', left: '50%' }, pos); // apply position $( self.image ).css({ position : 'absolute', top : getPosition(pos.top, 'height', height), left : getPosition(pos.left, 'width', width) }); // show the image self.show(); // flag ready and call the callback self.ready = true; options.complete.call( self, self ); }, error: function() { Galleria.raise('Could not scale image: '+self.image.src); }, timeout: 1000 }); return this; } }; // our own easings $.extend( $.easing, { galleria: function (_, t, b, c, d) { if ((t/=d/2) < 1) { return c/2*t*t*t + b; } return c/2*((t-=2)*t*t + 2) + b; }, galleriaIn: function (_, t, b, c, d) { return c*(t/=d)*t + b; }, galleriaOut: function (_, t, b, c, d) { return -c *(t/=d)*(t-2) + b; } }); // Forked version of Ainos Finger.js for native-style touch Galleria.Finger = (function() { var abs = M.abs; // test for translate3d support var has3d = Galleria.HAS3D = (function() { var el = doc.createElement('p'), has3d, t = ['webkit','O','ms','Moz',''], s, i=0, a = 'transform'; DOM().html.insertBefore(el, null); for (; t[i]; i++) { s = t[i] ? t[i]+'Transform' : a; if (el.style[s] !== undefined) { el.style[s] = "translate3d(1px,1px,1px)"; has3d = $(el).css(t[i] ? '-'+t[i].toLowerCase()+'-'+a : a); } } DOM().html.removeChild(el); return (has3d !== undefined && has3d.length > 0 && has3d !== "none"); }()); // request animation shim var requestFrame = (function(){ var r = 'RequestAnimationFrame'; return window.requestAnimationFrame || window['webkit'+r] || window['moz'+r] || window['o'+r] || window['ms'+r] || function( callback ) { window.setTimeout(callback, 1000 / 60); }; }()); var Finger = function(elem, options) { // default options this.config = { start: 0, duration: 500, onchange: function() {}, oncomplete: function() {}, easing: function(x,t,b,c,d) { return -c * ((t=t/d-1)*t*t*t - 1) + b; // easeOutQuart } }; this.easeout = function (x, t, b, c, d) { return c*((t=t/d-1)*t*t*t*t + 1) + b; }; if ( !elem.children.length ) { return; } var self = this; // extend options $.extend(this.config, options); this.elem = elem; this.child = elem.children[0]; this.to = this.pos = 0; this.touching = false; this.start = {}; this.index = this.config.start; this.anim = 0; this.easing = this.config.easing; if ( !has3d ) { this.child.style.position = 'absolute'; this.elem.style.position = 'relative'; } // Bind event handlers to context $.each(['ontouchstart','ontouchmove','ontouchend','setup'], function(i, fn) { self[fn] = (function(caller) { return function() { caller.apply( self, arguments ); }; }(self[fn])); }); // the physical animator this.setX = function() { var style = self.child.style; if (!has3d) { // this is actually faster than CSS3 translate style.left = self.pos+'px'; return; } style.MozTransform = style.webkitTransform = style.transform = 'translate3d(' + self.pos + 'px,0,0)'; return; }; // bind events $(elem).on('touchstart', this.ontouchstart); $(window).on('resize', this.setup); $(window).on('orientationchange', this.setup); // set up width this.setup(); // start the animations (function animloop(){ requestFrame(animloop); self.loop.call( self ); }()); }; Finger.prototype = { constructor: Finger, setup: function() { this.width = $( this.elem ).width(); this.length = M.ceil( $(this.child).width() / this.width ); if ( this.index !== 0 ) { this.index = M.max(0, M.min( this.index, this.length-1 ) ); this.pos = this.to = -this.width*this.index; } }, setPosition: function(pos) { this.pos = pos; this.to = pos; }, ontouchstart: function(e) { var touch = e.originalEvent.touches; this.start = { pageX: touch[0].pageX, pageY: touch[0].pageY, time: +new Date() }; this.isScrolling = null; this.touching = true; this.deltaX = 0; $doc.on('touchmove', this.ontouchmove); $doc.on('touchend', this.ontouchend); }, ontouchmove: function(e) { var touch = e.originalEvent.touches; // ensure swiping with one touch and not pinching if( touch && touch.length > 1 || e.scale && e.scale !== 1 ) { return; } this.deltaX = touch[0].pageX - this.start.pageX; // determine if scrolling test has run - one time test if ( this.isScrolling === null ) { this.isScrolling = !!( this.isScrolling || M.abs(this.deltaX) < M.abs(touch[0].pageY - this.start.pageY) ); } // if user is not trying to scroll vertically if (!this.isScrolling) { // prevent native scrolling e.preventDefault(); // increase resistance if first or last slide this.deltaX /= ( (!this.index && this.deltaX > 0 || this.index == this.length - 1 && this.deltaX < 0 ) ? ( M.abs(this.deltaX) / this.width + 1.8 ) : 1 ); this.to = this.deltaX - this.index * this.width; } e.stopPropagation(); }, ontouchend: function(e) { this.touching = false; // determine if slide attempt triggers next/prev slide var isValidSlide = +new Date() - this.start.time < 250 && M.abs(this.deltaX) > 40 || M.abs(this.deltaX) > this.width/2, isPastBounds = !this.index && this.deltaX > 0 || this.index == this.length - 1 && this.deltaX < 0; // if not scrolling vertically if ( !this.isScrolling ) { this.show( this.index + ( isValidSlide && !isPastBounds ? (this.deltaX < 0 ? 1 : -1) : 0 ) ); } $doc.off('touchmove', this.ontouchmove); $doc.off('touchend', this.ontouchend); }, show: function( index ) { if ( index != this.index ) { this.config.onchange.call(this, index); } else { this.to = -( index*this.width ); } }, moveTo: function( index ) { if ( index != this.index ) { this.pos = this.to = -( index*this.width ); this.index = index; } }, loop: function() { var distance = this.to - this.pos, factor = 1; if ( this.width && distance ) { factor = M.max(0.5, M.min(1.5, M.abs(distance / this.width) ) ); } // if distance is short or the user is touching, do a 1-1 animation if ( this.touching || M.abs(distance) <= 1 ) { this.pos = this.to; distance = 0; if ( this.anim && !this.touching ) { this.config.oncomplete( this.index ); } this.anim = 0; this.easing = this.config.easing; } else { if ( !this.anim ) { // save animation parameters this.anim = { start: this.pos, time: +new Date(), distance: distance, factor: factor, destination: this.to }; } // check if to has changed or time has run out var elapsed = +new Date() - this.anim.time; var duration = this.config.duration*this.anim.factor; if ( elapsed > duration || this.anim.destination != this.to ) { this.anim = 0; this.easing = this.easeout; return; } // apply easing this.pos = this.easing( null, elapsed, this.anim.start, this.anim.distance, duration ); } this.setX(); } }; return Finger; }()); // the plugin initializer $.fn.galleria = function( options ) { var selector = this.selector; // try domReady if element not found if ( !$(this).length ) { $(function() { if ( $( selector ).length ) { // if found on domReady, go ahead $( selector ).galleria( options ); } else { // if not, try fetching the element for 5 secs, then raise a warning. Galleria.utils.wait({ until: function() { return $( selector ).length; }, success: function() { $( selector ).galleria( options ); }, error: function() { Galleria.raise('Init failed: Galleria could not find the element "'+selector+'".'); }, timeout: 5000 }); } }); return this; } return this.each(function() { // destroy previous instance and prepare for new load if ( $.data(this, 'galleria') ) { $.data( this, 'galleria' ).destroy(); $( this ).find( '*' ).hide(); } // load the new gallery $.data( this, 'galleria', new Galleria().init( this, options ) ); }); }; // export as AMD or CommonJS if ( typeof module === "object" && module && typeof module.exports === "object" ) { module.exports = Galleria; } else { window.Galleria = Galleria; if ( typeof define === "function" && define.amd ) { define( "galleria", ['jquery'], function() { return Galleria; } ); } } // phew }( jQuery, this ) );
JavaScript
/** * Galleria Classic Theme 2012-08-08 * http://galleria.io * * Licensed under the MIT license * https://raw.github.com/aino/galleria/master/LICENSE * */ (function($) { /*global window, jQuery, Galleria */ Galleria.addTheme({ name: 'classic', author: 'Galleria', css: 'galleria.classic.css', defaults: { transition: 'slide', thumbCrop: 'height', // set this to false if you want to show the caption all the time: _toggleInfo: true }, init: function(options) { Galleria.requires(1.33, 'This version of Classic theme requires Galleria 1.3.3 or later'); // add some elements this.addElement('info-link','info-close'); this.append({ 'info' : ['info-link','info-close'] }); // cache some stuff var info = this.$('info-link,info-close,info-text'), touch = Galleria.TOUCH; // show loader & counter with opacity this.$('loader,counter').show().css('opacity', 0.4); // some stuff for non-touch browsers if (! touch ) { this.addIdleState( this.get('image-nav-left'), { left:-50 }); this.addIdleState( this.get('image-nav-right'), { right:-50 }); this.addIdleState( this.get('counter'), { opacity:0 }); } // toggle info if ( options._toggleInfo === true ) { info.bind( 'click:fast', function() { info.toggle(); }); } else { info.show(); this.$('info-link, info-close').hide(); } // bind some stuff this.bind('thumbnail', function(e) { if (! touch ) { // fade thumbnails $(e.thumbTarget).css('opacity', 0.6).parent().hover(function() { $(this).not('.active').children().stop().fadeTo(100, 1); }, function() { $(this).not('.active').children().stop().fadeTo(400, 0.6); }); if ( e.index === this.getIndex() ) { $(e.thumbTarget).css('opacity',1); } } else { $(e.thumbTarget).css('opacity', this.getIndex() ? 1 : 0.6).bind('click:fast', function() { $(this).css( 'opacity', 1 ).parent().siblings().children().css('opacity', 0.6); }); } }); var activate = function(e) { $(e.thumbTarget).css('opacity',1).parent().siblings().children().css('opacity', 0.6); }; this.bind('loadstart', function(e) { if (!e.cached) { this.$('loader').show().fadeTo(200, 0.4); } window.setTimeout(function() { activate(e); }, touch ? 300 : 0); this.$('info').toggle( this.hasInfo() ); }); this.bind('loadfinish', function(e) { this.$('loader').fadeOut(200); }); } }); }(jQuery));
JavaScript
AmCharts.themes.dark = { themeName: "dark", AmChart: { color: "#e7e7e7" }, AmCoordinateChart: { colors: ["#ae85c9", "#aab9f7", "#b6d2ff", "#c9e6f2", "#c9f0e1", "#e8d685", "#e0ad63", "#d48652", "#d27362", "#495fba", "#7a629b", "#8881cc"] }, AmStockChart: { colors: ["#639dbd", "#e8d685", "#ae85c9", "#c9f0e1", "#d48652", "#629b6d", "#719dc3", "#719dc3"] }, AmSlicedChart: { outlineAlpha: 1, outlineThickness: 2, labelTickColor: "#FFFFFF", labelTickAlpha: 0.3, colors: ["#495fba", "#e8d685", "#ae85c9", "#c9f0e1", "#d48652", "#629b6d", "#719dc3", "#719dc3"] }, AmRectangularChart: { zoomOutButtonColor: '#FFFFFF', zoomOutButtonRollOverAlpha: 0.15, zoomOutButtonImage: "lensWhite.png" }, AxisBase: { axisColor: "#FFFFFF", axisAlpha: 0.3, gridAlpha: 0.1, gridColor: "#FFFFFF", dashLength: 3 }, ChartScrollbar: { backgroundColor: "#000000", backgroundAlpha: 0.2, graphFillAlpha: 0.2, graphLineAlpha: 0, graphFillColor: "#FFFFFF", selectedGraphFillColor: "#FFFFFF", selectedGraphFillAlpha: 0.4, selectedGraphLineColor: "#FFFFFF", selectedBackgroundColor: "#FFFFFF", selectedBackgroundAlpha: 0.09, gridAlpha: 0.15 }, ChartCursor: { cursorColor: "#FFFFFF", color: "#000000", cursorAlpha: 0.5 }, AmLegend: { color: "#e7e7e7" }, AmGraph: { lineAlpha: 0.9 }, GaugeArrow: { color: "#FFFFFF", alpha: 0.8, nailAlpha: 0, innerRadius: "40%", nailRadius: 15, startWidth: 15, borderAlpha: 0.8, nailBorderAlpha: 0 }, GaugeAxis: { tickColor: "#FFFFFF", tickAlpha: 1, tickLength: 15, minorTickLength: 8, axisThickness: 3, axisColor: '#FFFFFF', axisAlpha: 1, bandAlpha: 0.8 }, TrendLine: { lineColor: "#c03246", lineAlpha: 0.8 }, // ammap AreasSettings: { alpha: 0.8, color: "#FFFFFF", colorSolid: "#000000", unlistedAreasAlpha: 0.4, unlistedAreasColor: "#FFFFFF", outlineColor: "#000000", outlineAlpha: 0.5, outlineThickness: 0.5, rollOverColor: "#3c5bdc", rollOverOutlineColor: "#000000", selectedOutlineColor: "#000000", selectedColor: "#f15135", unlistedAreasOutlineColor: "#000000", unlistedAreasOutlineAlpha: 0.5 }, LinesSettings: { color: "#FFFFFF", alpha: 0.8 }, ImagesSettings: { alpha: 0.8, labelColor: "#FFFFFF", color: "#FFFFFF", labelRollOverColor: "#3c5bdc" }, ZoomControl: { buttonRollOverColor: "#3c5bdc", buttonFillColor: "#f15135", buttonFillAlpha: 0.8, gridBackgroundColor: "#FFFFFF", buttonBorderAlpha:0, buttonCornerRadius:2, gridAlpha:0.5, gridBackgroundColor:"#FFFFFF", homeIconFile:"homeIconWhite.gif", buttonIconAlpha:0.6, gridAlpha: 0.2, buttonSize:20 }, SmallMap: { mapColor: "#FFFFFF", rectangleColor: "#FFFFFF", backgroundColor: "#000000", backgroundAlpha: 0.7, borderThickness: 1, borderAlpha: 0.8 }, // the defaults below are set using CSS syntax, you can use any existing css property // if you don't use Stock chart, you can delete lines below PeriodSelector: { color: "#e7e7e7" }, PeriodButton: { color: "#e7e7e7", background: "transparent", opacity: 0.7, border: "1px solid rgba(255, 255, 255, .15)", MozBorderRadius: "5px", borderRadius: "5px", margin: "1px", outline: "none", boxSizing: "border-box" }, PeriodButtonSelected: { color: "#e7e7e7", backgroundColor: "rgba(255, 255, 255, 0.1)", border: "1px solid rgba(255, 255, 255, .3)", MozBorderRadius: "5px", borderRadius: "5px", margin: "1px", outline: "none", opacity: 1, boxSizing: "border-box" }, PeriodInputField: { color: "#e7e7e7", background: "transparent", border: "1px solid rgba(255, 255, 255, .15)", outline: "none" }, DataSetSelector: { color: "#e7e7e7", selectedBackgroundColor: "rgba(255, 255, 255, .25)", rollOverBackgroundColor: "rgba(255, 255, 255, .15)" }, DataSetCompareList: { color: "#e7e7e7", lineHeight: "100%", boxSizing: "initial", webkitBoxSizing: "initial", border: "1px solid rgba(255, 255, 255, .15)" }, DataSetSelect: { border: "1px solid rgba(255, 255, 255, .15)", outline: "none" } };
JavaScript
AmCharts.themes.light = { themeName:"light", AmChart: { color: "#000000" }, AmCoordinateChart: { colors: ["#67b7dc", "#fdd400", "#84b761", "#cc4748", "#cd82ad", "#2f4074", "#448e4d", "#b7b83f", "#b9783f", "#b93e3d", "#913167"] }, AmStockChart: { colors: ["#67b7dc", "#fdd400", "#84b761", "#cc4748", "#cd82ad", "#2f4074", "#448e4d", "#b7b83f", "#b9783f", "#b93e3d", "#913167"] }, AmSlicedChart: { colors: ["#67b7dc", "#fdd400", "#84b761", "#cc4748", "#cd82ad", "#2f4074", "#448e4d", "#b7b83f", "#b9783f", "#b93e3d", "#913167"], outlineAlpha: 1, outlineThickness: 2, labelTickColor: "#000000", labelTickAlpha: 0.3 }, AmRectangularChart: { zoomOutButtonColor: '#000000', zoomOutButtonRollOverAlpha: 0.15, zoomOutButtonImage: "lens.png" }, AxisBase: { axisColor: "#000000", axisAlpha: 0.3, gridAlpha: 0.1, gridColor: "#000000" }, ChartScrollbar: { backgroundColor: "#000000", backgroundAlpha: 0.12, graphFillAlpha: 0.5, graphLineAlpha: 0, selectedBackgroundColor: "#FFFFFF", selectedBackgroundAlpha: 0.4, gridAlpha: 0.15 }, ChartCursor: { cursorColor: "#000000", color: "#FFFFFF", cursorAlpha: 0.5 }, AmLegend: { color: "#000000" }, AmGraph: { lineAlpha: 0.9 }, GaugeArrow: { color: "#000000", alpha: 0.8, nailAlpha: 0, innerRadius: "40%", nailRadius: 15, startWidth: 15, borderAlpha: 0.8, nailBorderAlpha: 0 }, GaugeAxis: { tickColor: "#000000", tickAlpha: 1, tickLength: 15, minorTickLength: 8, axisThickness: 3, axisColor: '#000000', axisAlpha: 1, bandAlpha: 0.8 }, TrendLine: { lineColor: "#c03246", lineAlpha: 0.8 }, // ammap AreasSettings: { alpha: 0.8, color: "#67b7dc", colorSolid: "#003767", unlistedAreasAlpha: 0.4, unlistedAreasColor: "#000000", outlineColor: "#FFFFFF", outlineAlpha: 0.5, outlineThickness: 0.5, rollOverColor: "#3c5bdc", rollOverOutlineColor: "#FFFFFF", selectedOutlineColor: "#FFFFFF", selectedColor: "#f15135", unlistedAreasOutlineColor: "#FFFFFF", unlistedAreasOutlineAlpha: 0.5 }, LinesSettings: { color: "#000000", alpha: 0.8 }, ImagesSettings: { alpha: 0.8, labelColor: "#000000", color: "#000000", labelRollOverColor: "#3c5bdc" }, ZoomControl: { buttonRollOverColor: "#3c5bdc", buttonFillColor: "#3994e2", buttonBorderColor: "#3994e2", buttonFillAlpha: 0.8, gridBackgroundColor: "#FFFFFF", buttonBorderAlpha:0, buttonCornerRadius:2, gridColor:"#FFFFFF", gridBackgroundColor:"#000000", buttonIconAlpha:0.6, gridAlpha: 0.6, buttonSize:20 }, SmallMap: { mapColor: "#000000", rectangleColor: "#f15135", backgroundColor: "#FFFFFF", backgroundAlpha: 0.7, borderThickness: 1, borderAlpha: 0.8 }, // the defaults below are set using CSS syntax, you can use any existing css property // if you don't use Stock chart, you can delete lines below PeriodSelector: { color: "#000000" }, PeriodButton: { color: "#000000", background: "transparent", opacity: 0.7, border: "1px solid rgba(0, 0, 0, .3)", MozBorderRadius: "5px", borderRadius: "5px", margin: "1px", outline: "none", boxSizing: "border-box" }, PeriodButtonSelected: { color: "#000000", backgroundColor: "#b9cdf5", border: "1px solid rgba(0, 0, 0, .3)", MozBorderRadius: "5px", borderRadius: "5px", margin: "1px", outline: "none", opacity: 1, boxSizing: "border-box" }, PeriodInputField: { color: "#000000", background: "transparent", border: "1px solid rgba(0, 0, 0, .3)", outline: "none" }, DataSetSelector: { color: "#000000", selectedBackgroundColor: "#b9cdf5", rollOverBackgroundColor: "#a8b0e4" }, DataSetCompareList: { color: "#000000", lineHeight: "100%", boxSizing: "initial", webkitBoxSizing: "initial", border: "1px solid rgba(0, 0, 0, .3)" }, DataSetSelect: { border: "1px solid rgba(0, 0, 0, .3)", outline: "none" } };
JavaScript
AmCharts.themes.chalk = { themeName: "chalk", AmChart: { color: "#e7e7e7", fontFamily: "Covered By Your Grace", fontSize: 18, handDrawn: true }, AmCoordinateChart: { colors: ["#FFFFFF", "#e384a6", "#f4d499", "#4d90d6", "#c7e38c", "#9986c8", "#edf28c", "#ffd1d4", "#5ee1dc", "#b0eead", "#fef85a", "#8badd2"] }, AmSlicedChart: { outlineAlpha: 1, labelTickColor: "#FFFFFF", labelTickAlpha: 0.3, colors: ["#FFFFFF", "#e384a6", "#f4d499", "#4d90d6", "#c7e38c", "#9986c8", "#edf28c", "#ffd1d4", "#5ee1dc", "#b0eead", "#fef85a", "#8badd2"] }, AmStockChart: { colors: ["#FFFFFF", "#e384a6", "#f4d499", "#4d90d6", "#c7e38c", "#9986c8", "#edf28c", "#ffd1d4", "#5ee1dc", "#b0eead", "#fef85a", "#8badd2"] }, AmRectangularChart: { zoomOutButtonColor: '#FFFFFF', zoomOutButtonRollOverAlpha: 0.15, zoomOutButtonImage: "lensWhite.png" }, AxisBase: { axisColor: "#FFFFFF", gridColor: "#FFFFFF" }, ChartScrollbar: { backgroundColor: "#FFFFFF", backgroundAlpha: 0.2, graphFillAlpha: 0.5, graphLineAlpha: 0, selectedBackgroundColor: "#000000", selectedBackgroundAlpha: 0.25, fontSize: 15, gridAlpha: 0.15 }, ChartCursor: { cursorColor: "#FFFFFF", color: "#000000" }, AmLegend: { color: "#e7e7e7", markerSize: 20 }, AmGraph: { lineAlpha: 0.8 }, GaugeArrow: { color: "#FFFFFF", alpha: 0.1, nailAlpha: 0, innerRadius: "40%", nailRadius: 15, startWidth: 15, borderAlpha: 0.8, nailBorderAlpha: 0 }, GaugeAxis: { tickColor: "#FFFFFF", tickAlpha: 0.8, tickLength: 15, minorTickLength: 8, axisThickness: 3, axisColor: '#FFFFFF', axisAlpha: 0.8, bandAlpha: 0.4 }, TrendLine: { lineColor: "#c03246", lineAlpha: 0.8 }, // ammap AmMap: { handDrawn: false }, AreasSettings: { alpha: 0.8, color: "#FFFFFF", colorSolid: "#000000", unlistedAreasAlpha: 0.4, unlistedAreasColor: "#FFFFFF", outlineColor: "#000000", outlineAlpha: 0.5, outlineThickness: 0.5, rollOverColor: "#4d90d6", rollOverOutlineColor: "#000000", selectedOutlineColor: "#000000", selectedColor: "#e384a6", unlistedAreasOutlineColor: "#000000", unlistedAreasOutlineAlpha: 0.5 }, LinesSettings: { color: "#FFFFFF", alpha: 0.8 }, ImagesSettings: { alpha: 0.8, labelFontSize: 16, labelColor: "#FFFFFF", color: "#FFFFFF", labelRollOverColor: "#4d90d6" }, ZoomControl: { buttonRollOverColor: "#4d90d6", buttonFillColor: "#e384a6", buttonFillAlpha: 0.8, buttonBorderColor: "#FFFFFF", gridBackgroundColor: "#FFFFFF", gridAlpha: 0.8 }, SmallMap: { mapColor: "#FFFFFF", rectangleColor: "#FFFFFF", backgroundColor: "#000000", backgroundAlpha: 0.7, borderThickness: 1, borderAlpha: 0.8 }, // the defaults below are set using CSS syntax, you can use any existing css property // if you don't use Stock chart, you can delete lines below PeriodSelector: { fontFamily: "Covered By Your Grace", fontSize:"16px", color: "#e7e7e7" }, PeriodButton: { fontFamily: "Covered By Your Grace", fontSize:"16px", color: "#e7e7e7", background: "transparent", opacity: 0.7, border: "1px solid rgba(255, 255, 255, .15)", MozBorderRadius: "5px", borderRadius: "5px", margin: "1px", outline: "none", boxSizing: "border-box" }, PeriodButtonSelected: { fontFamily: "Covered By Your Grace", fontSize:"16px", color: "#e7e7e7", backgroundColor: "rgba(255, 255, 255, 0.1)", border: "1px solid rgba(255, 255, 255, .3)", MozBorderRadius: "5px", borderRadius: "5px", margin: "1px", outline: "none", opacity: 1, boxSizing: "border-box" }, PeriodInputField: { fontFamily: "Covered By Your Grace", fontSize:"16px", color: "#e7e7e7", background: "transparent", border: "1px solid rgba(255, 255, 255, .15)", outline: "none" }, DataSetSelector: { fontFamily: "Covered By Your Grace", fontSize:"16px", color: "#e7e7e7", selectedBackgroundColor: "rgba(255, 255, 255, .25)", rollOverBackgroundColor: "rgba(255, 255, 255, .15)" }, DataSetCompareList: { fontFamily: "Covered By Your Grace", fontSize:"16px", color: "#e7e7e7", lineHeight: "100%", boxSizing: "initial", webkitBoxSizing: "initial", border: "1px solid rgba(255, 255, 255, .15)" }, DataSetSelect: { fontFamily: "Covered By Your Grace", fontSize:"16px", border: "1px solid rgba(255, 255, 255, .15)", outline: "none" } };
JavaScript
AmCharts.themes.black = { themeName: "black", AmChart: { color: "#e7e7e7" }, AmCoordinateChart: { colors: ["#de4c4f", "#d8854f", "#eea638", "#a7a737", "#86a965", "#8aabb0", "#69c8ff", "#cfd27e", "#9d9888", "#916b8a", "#724887", "#7256bc"] }, AmStockChart: { colors: ["#de4c4f", "#d8854f", "#eea638", "#a7a737", "#86a965", "#8aabb0", "#69c8ff", "#cfd27e", "#9d9888", "#916b8a", "#724887", "#7256bc"] }, AmSlicedChart: { outlineAlpha: 1, outlineThickness: 2, labelTickColor: "#FFFFFF", labelTickAlpha: 0.3, colors: ["#de4c4f", "#d8854f", "#eea638", "#a7a737", "#86a965", "#8aabb0", "#69c8ff", "#cfd27e", "#9d9888", "#916b8a", "#724887", "#7256bc"] }, AmRectangularChart: { zoomOutButtonColor: '#FFFFFF', zoomOutButtonRollOverAlpha: 0.15, zoomOutButtonImage: "lensWhite.png" }, AxisBase: { axisColor: "#FFFFFF", axisAlpha: 0.3, gridAlpha: 0.1, gridColor: "#FFFFFF", dashLength: 3 }, ChartScrollbar: { backgroundColor: "#000000", backgroundAlpha: 0.2, graphFillAlpha: 0.2, graphLineAlpha: 0, graphFillColor: "#FFFFFF", selectedGraphFillColor: "#FFFFFF", selectedGraphFillAlpha: 0.4, selectedGraphLineColor: "#FFFFFF", selectedBackgroundColor: "#FFFFFF", selectedBackgroundAlpha: 0.09, gridAlpha: 0.15 }, ChartCursor: { cursorColor: "#FFFFFF", color: "#000000", cursorAlpha: 0.5 }, AmLegend: { color: "#e7e7e7" }, AmGraph: { lineAlpha: 0.9 }, GaugeArrow: { color: "#FFFFFF", alpha: 0.8, nailAlpha: 0, innerRadius: "40%", nailRadius: 15, startWidth: 15, borderAlpha: 0.8, nailBorderAlpha: 0 }, GaugeAxis: { tickColor: "#FFFFFF", tickAlpha: 1, tickLength: 15, minorTickLength: 8, axisThickness: 3, axisColor: '#FFFFFF', axisAlpha: 1, bandAlpha: 0.8 }, TrendLine: { lineColor: "#c03246", lineAlpha: 0.8 }, // ammap AreasSettings: { alpha: 0.8, color: "#FFFFFF", colorSolid: "#000000", unlistedAreasAlpha: 0.4, unlistedAreasColor: "#FFFFFF", outlineColor: "#000000", outlineAlpha: 0.5, outlineThickness: 0.5, rollOverColor: "#3c5bdc", rollOverOutlineColor: "#000000", selectedOutlineColor: "#000000", selectedColor: "#f15135", unlistedAreasOutlineColor: "#000000", unlistedAreasOutlineAlpha: 0.5 }, LinesSettings: { color: "#FFFFFF", alpha: 0.8 }, ImagesSettings: { alpha: 0.8, labelColor: "#FFFFFF", color: "#FFFFFF", labelRollOverColor: "#3c5bdc" }, ZoomControl: { buttonRollOverColor: "#3c5bdc", buttonFillColor: "#738f58", buttonBorderColor: "#738f58", buttonFillAlpha: 0.8, gridBackgroundColor: "#FFFFFF", buttonBorderAlpha:0, buttonCornerRadius:2, gridAlpha:0.5, gridBackgroundColor:"#FFFFFF", homeIconFile:"homeIconWhite.gif", buttonIconAlpha:0.6, gridAlpha: 0.2, buttonSize:20 }, SmallMap: { mapColor: "#FFFFFF", rectangleColor: "#FFFFFF", backgroundColor: "#000000", backgroundAlpha: 0.7, borderThickness: 1, borderAlpha: 0.8 }, // the defaults below are set using CSS syntax, you can use any existing css property // if you don't use Stock chart, you can delete lines below PeriodSelector: { color: "#e7e7e7" }, PeriodButton: { color: "#e7e7e7", background: "transparent", opacity: 0.7, border: "1px solid rgba(255, 255, 255, .15)", MozBorderRadius: "5px", borderRadius: "5px", margin: "1px", outline: "none", boxSizing: "border-box" }, PeriodButtonSelected: { color: "#e7e7e7", backgroundColor: "rgba(255, 255, 255, 0.1)", border: "1px solid rgba(255, 255, 255, .3)", MozBorderRadius: "5px", borderRadius: "5px", margin: "1px", outline: "none", opacity: 1, boxSizing: "border-box" }, PeriodInputField: { color: "#e7e7e7", background: "transparent", border: "1px solid rgba(255, 255, 255, .15)", outline: "none" }, DataSetSelector: { color: "#e7e7e7", selectedBackgroundColor: "rgba(255, 255, 255, .25)", rollOverBackgroundColor: "rgba(255, 255, 255, .15)" }, DataSetCompareList: { color: "#e7e7e7", lineHeight: "100%", boxSizing: "initial", webkitBoxSizing: "initial", border: "1px solid rgba(255, 255, 255, .15)" }, DataSetSelect: { border: "1px solid rgba(255, 255, 255, .15)", outline: "none" } };
JavaScript
// (c) ammap.com | SVG (in JSON format) map of Belgium // areas: {id:"BE-VAN"},{id:"BE-BWR"},{id:"BE-BRU"},{id:"BE-WHT"},{id:"BE-WLG"},{id:"BE-VLI"},{id:"BEW-LX"},{id:"BE-WNA"},{id:"BE-VOV"},{id:"BE-VBR"},{id:"BE-VWV"} AmCharts.maps.belgiumLow={ "svg": { "defs": { "amcharts:ammap": { "projection":"mercator", "leftLongitude":"2.543698", "topLatitude":"51.499939", "rightLongitude":"6.408540", "bottomLatitude":"49.497691" } }, "g":{ "path":[ { "id":"BE-VAN", "title":"Antwerp", "d":"M435.75,1.31l11.07,5.98l1.3,18.09l-14.38,2.36l22.27,-0.87l6.24,7.37l21.16,-28.48l9.67,4.64l5.1,12.2l-6.34,11.98l12.24,24.36l20.56,3.44l-0.62,13.46l0,0l-4.49,12.64l9.3,21.54l-48.55,23.15l-6.09,12.47l0,0l-31.92,7.25l-5.06,-8.57l-18.38,12.34l-2.57,-8.05l-19.61,10.45l-36.53,-1.36l-2.88,-10.76l-27.31,-2.13l0,0l-9.63,-1.02l-3.05,-18.77l27.04,-7.7l3.35,-9.06l-8.19,-30.53l6.24,-9.27l-16.4,-21.42l0,0l-4.08,-6.56l41.88,3.11L356.72,18l18.44,-9.75l12.66,-1.28l-0.49,18.24l20.25,0.12L435.75,1.31z" }, { "id":"BE-WBR", "title":"Walloon Brabant", "d":"M302.66,246.58L313.34,239.28L331.33,251.94L348.45,238L355.88,243.42L379.34,231.41L385.53,239.93L399.24,228.83L406.81,235.36L408.44,218.03L431.34,215.73L463.43,235.21L474.48,226.96L481.78,233.03L481.78,233.03L474.66,266.23L474.66,266.23L437.15,282.31L412.45,277.36L413.42,289.64L400.16,288.76L395.72,297.19L395.72,297.19L374.09,301.21L374.69,291.9L363.45,289.92L347.91,296.39L318.55,260.26L303.87,269.26z" }, { "id":"BE-BRU", "title":"Brussels Capital Region", "d":"M366.21,187.61L366.99,188.19L366.99,188.19L378.5,220.21L358,228.61L330.96,212.1L341.25,192.28L356.93,187.64L356.93,187.64L356.93,187.64L356.93,187.64L365.59,186.22L365.59,186.22z" }, { "id":"BE-WHT", "title":"Hainaut", "d":"M178.07,227.85l33.19,14.35l9.22,-15.76l15.85,-2.7l3.21,10.27l23.56,4.72l0,0l3.11,12.74l36.45,-4.9l0,0l1.21,22.68l14.69,-8.99l29.35,36.13l15.54,-6.47l11.24,1.99l-0.6,9.31l21.63,-4.03l0,0l-1.36,30.58l8.91,5.12l-4.55,29.48l-37.02,4.68l-22.45,16.94l21.96,7.04l-7.37,19.33l13.67,68.37l0,0l-56.49,-11.19l3.52,-20.77l13.64,-6.38l-5.88,-19.26l-13.97,-0.21l15.56,-42.01l-8.99,-5.19l-4.8,9.47l-22,-30.68l-23.85,9.73l-30.07,-7.36l-7.7,14.01l-9.69,-19.6l0.31,-26.39l-10.13,-12.01l-21.01,2.68l3.54,-11.07l-8.58,-2.93l-19.2,12.81l-16.44,-10.13l-10.15,-40.79l4.16,-13.35l-16.17,-16.73l0,0l25,0.18l10.5,14.04L178.07,227.85zM61.92,246.39l-4.07,-13.33l23.17,-7.24l-4.61,-6.08l12.39,-5.19l3.62,11.51l0,0l-15.46,8.86l-5.82,15.75L61.92,246.39z" }, { "id":"BE-WLG", "title":"Liege", "d":"M612.63,214.16L610.61,230.61L610.61,230.61L649.55,245.57L651.44,231.37L651.44,231.37L676.4,231.47L680.21,242.69L695.23,241.61L706.98,271L724.8,270.97L707.19,296.7L716.45,310.98L740.65,312.99L745.63,329.08L738.78,346.22L751.62,359.84L742.63,369.32L732.13,364.79L726.84,380.46L706.71,390.08L709.53,405.99L700.83,408.2L699.57,422.04L694.51,411.02L684.3,414.98L677.22,405.84L677.22,405.84L668.4,361.27L645.7,356.07L642.32,376.24L649.3,376.7L635,384.31L618.72,382.16L618.31,353.03L582.29,342.53L577.5,332.64L568.96,338L559.72,331.24L554.49,346.67L554.49,346.67L535.82,350.99L523.66,339.28L516.4,316.16L509.59,319.33L505.33,305.91L484.73,299.66L474.66,266.23L474.66,266.23L481.78,233.03L481.78,233.03L497.46,245.66L497.46,245.66L510.08,249.73L511.87,241L537.14,243.36L553.19,233.74L559.18,242.62L570.62,241.15L611.54,214.13L611.54,214.13z" }, { "id":"BE-VLI", "title":"Limburg", "d":"M630.3,227.39l21.14,3.99l0,0l-1.89,14.19l-38.94,-14.96l0,0L630.3,227.39zM581.9,70.45l5.1,17.2l56.92,24.11l-26.01,56.17l7.12,3.79l-21.88,24.15l8.4,18.25l0,0l-40.93,27.02l-11.44,1.47l-5.99,-8.89l-16.05,9.62L511.87,241l-1.79,8.73l-12.63,-4.07l0,0l16.55,-59.62l-18.38,-1.66l-9.43,-10.31l14.34,-24.04l8.05,-1.11l-7.84,-7.9l-11.65,10.83l-14.9,-6.2l0,0l6.09,-12.47l48.55,-23.15l-9.3,-21.54l4.49,-12.64l0,0l34.94,-0.56l13.34,-11.82L581.9,70.45z" }, { "id":"BE-WLX", "title":"Luxembourg", "d":"M554.49,346.67L559.72,331.24L568.96,338L577.5,332.64L582.29,342.53L618.31,353.03L618.72,382.16L635,384.31L649.3,376.7L642.32,376.24L645.7,356.07L668.4,361.27L677.22,405.84L677.22,405.84L652.43,427.39L637.26,457.43L640.65,467.02L628.76,473.09L620.9,491.68L630.38,497.82L621.89,510.7L624.58,524.29L631.17,523L638.51,544.86L649.96,548.91L645.96,558.65L654.79,562.46L641.29,595.59L604.11,596.01L596.64,609.19L585.98,602.41L569.66,612L561.26,582.67L545.6,572.22L538.79,578.12L542.2,565.3L531.4,553.76L510.04,553.52L496,532.67L471.58,521.01L471.58,521.01L475.61,505.53L501.07,484.63L472.54,452.72L485.96,445.32L490.61,424.37L492.61,433.38L530.23,427.24L525.02,421.1L532.53,413.32L518.21,396.14L554.55,374.3L553.48,365.88L544.53,366.28L554.59,359.81z" }, { "id":"BE-WNA", "title":"Namur", "d":"M395.72,297.19L400.16,288.76L413.42,289.64L412.45,277.36L437.15,282.31L474.66,266.23L474.66,266.23L484.73,299.66L505.33,305.91L509.59,319.33L516.4,316.16L523.66,339.28L535.82,350.99L554.49,346.67L554.49,346.67L554.59,359.81L544.53,366.28L553.48,365.88L554.55,374.3L518.21,396.14L532.53,413.32L525.02,421.1L530.23,427.24L492.61,433.38L490.61,424.37L485.96,445.32L472.54,452.72L501.07,484.63L475.61,505.53L471.58,521.01L471.58,521.01L448.75,523.54L447.89,501.4L455.89,488.52L436.69,470.67L446.72,449.76L442.62,441.63L457.44,419.95L443.92,410.35L418.03,435.56L417.86,462.5L367.51,478.72L367.51,478.72L353.84,410.35L361.21,391.02L339.25,383.98L361.7,367.04L398.72,362.36L403.27,332.88L394.36,327.77z" }, { "id":"BE-VOV", "title":"East Flanders", "d":"M329.29,47.05L345.69,68.47L339.44,77.74L347.63,108.27L344.29,117.33L317.25,125.03L320.3,143.8L329.93,144.82L329.93,144.82L328.51,155.8L311.39,166.06L314.97,177.15L301.77,177.02L291.34,205.99L295.42,221.01L273.44,225.27L273.99,238.73L263.09,238.73L263.09,238.73L239.54,234.01L236.33,223.74L220.47,226.44L211.25,242.2L178.07,227.85L178.07,227.85L190.13,216.09L176.73,197.02L181.78,187.82L169.64,185.61L178.32,173.76L169.26,169.48L175.56,141.61L153.21,125.68L168.63,106.66L158.77,96.98L162.91,71.35L162.91,71.35L172.06,80.62L191.26,80.25L189,67.48L203.73,61.61L240,74.86L242.65,89.89L261.36,87.22L261.27,94.25L295.13,80.72z" }, { "id":"BE-VBR", "title":"Flemish Brabant", "d":"M474.19,145.65l14.9,6.2l11.65,-10.83l7.84,7.9l-8.05,1.11l-14.34,24.04l9.43,10.31l18.38,1.66l-16.55,59.62l0,0l-15.68,-12.63l0,0l-7.29,-6.07l-11.05,8.25l-32.1,-19.48l-22.9,2.3l-1.63,17.33l-7.57,-6.53l-13.71,11.1l-6.19,-8.52l-23.46,12.02l-7.43,-5.42l-17.12,13.94l-17.99,-12.65l-10.68,7.29l0,0l-36.45,4.9l-3.11,-12.74l0,0h10.89l-0.54,-13.46l21.98,-4.26l-4.08,-15.01l10.43,-28.97l13.21,0.12l-3.58,-11.09l17.12,-10.26l1.42,-10.98l0,0l27.31,2.13l2.88,10.76l36.53,1.36l19.61,-10.45l2.57,8.05l18.38,-12.34l5.06,8.57L474.19,145.65zM365.59,186.22L365.59,186.22l-20.99,2.95l-13.52,23.29L358,228.61l20.5,-8.41l-11.52,-32.01L365.59,186.22z" }, { "id":"BE-VWV", "title":"West Flanders", "d":"M160.4,42.39L162.91,71.35L162.91,71.35L158.77,96.98L168.63,106.66L153.21,125.68L175.56,141.61L169.26,169.48L178.32,173.76L169.64,185.61L181.78,187.82L176.73,197.02L190.13,216.09L178.07,227.85L178.07,227.85L158.63,245.6L148.13,231.56L123.13,231.37L123.13,231.37L117.84,220.98L92.42,226.07L92.42,226.07L88.8,214.56L76.41,219.75L81.02,225.82L57.85,233.06L61.92,246.39L61.92,246.39L47.74,240.45L34.84,214.74L17.8,214.1L10.85,202.67L9.05,181.12L17.14,172.59L0,128.86L124.26,53.82L124.77,43.66L127.12,54.29L127.18,43.41L132.98,50.62z" } ] } } };
JavaScript
AmCharts.mapTranslations.gv = {"United Kingdom":"Rywvaneth Unys"}
JavaScript
AmCharts.mapTranslations.ky = {"Kyrgyzstan":"Кыргызстан"}
JavaScript
AmCharts.mapTranslations.rw = {"Tonga":"Igitonga"}
JavaScript
AmCharts.mapTranslations.si = {"Sri Lanka":"ශ්‍රී ලංකාව"}
JavaScript
AmCharts.mapTranslations.dv = {"Maldives":"ދިވެހި ރާއްޖެ"}
JavaScript
AmCharts.mapTranslations.yo = {"Botswana":"BW","Nigeria":"NG","Tonga":"Tonga"}
JavaScript
AmCharts.mapTranslations.tg = {"Afghanistan":"Афғонистан","Tonga":"Тонга"}
JavaScript
AmCharts.mapTranslations.tt = {"Russia":"Россия"}
JavaScript
AmCharts.mapTranslations.sa = {"India":"भारतम्"}
JavaScript
AmCharts.mapTranslations.ku = {"Africa":"Cîhan","Turkey":"Tirkiye"}
JavaScript
AmCharts.mapTranslations.kw = {"United Kingdom":"Rywvaneth Unys"}
JavaScript
AmCharts.mapTranslations.ha = {"Ghana":"Gaana","Niger":"Nijer","Nigeria":"Nijeriya"}
JavaScript
AmCharts.mapTranslations.kk = {"Kazakhstan":"Қазақстан","Tonga":"Тонга"}
JavaScript
AmCharts.mapTranslations.kl = {"Greenland":"Kalaallit Nunaat"}
JavaScript
AmCharts.mapTranslations.kok = {"India":"भारत"}
JavaScript
AmCharts.mapTranslations.syr = {"Syria":"ܣܘܪܝܝܐ"}
JavaScript
AmCharts.mapTranslations.zu = {"South Africa":"iNingizimu Afrika"}
JavaScript
(function($) { var aux = { // navigates left / right navigate : function( dir, $el, $wrapper, opts, cache ) { var scroll = opts.scroll, factor = 1, idxClicked = 0; if( cache.expanded ) { scroll = 1; // scroll is always 1 in full mode factor = 3; // the width of the expanded item will be 3 times bigger than 1 collapsed item idxClicked = cache.idxClicked; // the index of the clicked item } // clone the elements on the right / left and append / prepend them according to dir and scroll if( dir === 1 ) { $wrapper.find('div.ca-item:lt(' + scroll + ')').each(function(i) { $(this).clone(true).css( 'left', ( cache.totalItems - idxClicked + i ) * cache.itemW * factor + 'px' ).appendTo( $wrapper ); }); } else { var $first = $wrapper.children().eq(0); $wrapper.find('div.ca-item:gt(' + ( cache.totalItems - 1 - scroll ) + ')').each(function(i) { // insert before $first so they stay in the right order $(this).clone(true).css( 'left', - ( scroll - i + idxClicked ) * cache.itemW * factor + 'px' ).insertBefore( $first ); }); } // animate the left of each item // the calculations are dependent on dir and on the cache.expanded value $wrapper.find('div.ca-item').each(function(i) { var $item = $(this); $item.stop().animate({ left : ( dir === 1 ) ? '-=' + ( cache.itemW * factor * scroll ) + 'px' : '+=' + ( cache.itemW * factor * scroll ) + 'px' }, opts.sliderSpeed, opts.sliderEasing, function() { if( ( dir === 1 && $item.position().left < - idxClicked * cache.itemW * factor ) || ( dir === -1 && $item.position().left > ( ( cache.totalItems - 1 - idxClicked ) * cache.itemW * factor ) ) ) { // remove the item that was cloned $item.remove(); } cache.isAnimating = false; }); }); }, // opens an item (animation) -> opens all the others openItem : function( $wrapper, $item, opts, cache ) { cache.idxClicked = $item.index(); // the item's position (1, 2, or 3) on the viewport (the visible items) cache.winpos = aux.getWinPos( $item.position().left, cache ); $wrapper.find('div.ca-item').not( $item ).hide(); $item.find('div.ca-content-wrapper').css( 'left', cache.itemW + 'px' ).stop().animate({ width : cache.itemW * 2 + 'px', left : cache.itemW + 'px' }, opts.itemSpeed, opts.itemEasing) .end() .stop() .animate({ left : '0px' }, opts.itemSpeed, opts.itemEasing, function() { cache.isAnimating = false; cache.expanded = true; aux.openItems( $wrapper, $item, opts, cache ); }); }, // opens all the items openItems : function( $wrapper, $openedItem, opts, cache ) { var openedIdx = $openedItem.index(); $wrapper.find('div.ca-item').each(function(i) { var $item = $(this), idx = $item.index(); if( idx !== openedIdx ) { $item.css( 'left', - ( openedIdx - idx ) * ( cache.itemW * 3 ) + 'px' ).show().find('div.ca-content-wrapper').css({ left : cache.itemW + 'px', width : cache.itemW * 2 + 'px' }); // hide more link aux.toggleMore( $item, false ); } }); }, // show / hide the item's more button toggleMore : function( $item, show ) { ( show ) ? $item.find('a.ca-more').show() : $item.find('a.ca-more').hide(); }, // close all the items // the current one is animated closeItems : function( $wrapper, $openedItem, opts, cache ) { var openedIdx = $openedItem.index(); $openedItem.find('div.ca-content-wrapper').stop().animate({ width : '0px' }, opts.itemSpeed, opts.itemEasing) .end() .stop() .animate({ left : cache.itemW * ( cache.winpos - 1 ) + 'px' }, opts.itemSpeed, opts.itemEasing, function() { cache.isAnimating = false; cache.expanded = false; }); // show more link aux.toggleMore( $openedItem, true ); $wrapper.find('div.ca-item').each(function(i) { var $item = $(this), idx = $item.index(); if( idx !== openedIdx ) { $item.find('div.ca-content-wrapper').css({ width : '0px' }) .end() .css( 'left', ( ( cache.winpos - 1 ) - ( openedIdx - idx ) ) * cache.itemW + 'px' ) .show(); // show more link aux.toggleMore( $item, true ); } }); }, // gets the item's position (1, 2, or 3) on the viewport (the visible items) // val is the left of the item getWinPos : function( val, cache ) { switch( val ) { case 0 : return 1; break; case cache.itemW : return 2; break; case cache.itemW * 2 : return 3; break; } } }, methods = { init : function( options ) { if( this.length ) { var settings = { sliderSpeed : 500, // speed for the sliding animation sliderEasing : 'easeOutExpo',// easing for the sliding animation itemSpeed : 500, // speed for the item animation (open / close) itemEasing : 'easeOutExpo',// easing for the item animation (open / close) scroll : 1 // number of items to scroll at a time }; return this.each(function() { // if options exist, lets merge them with our default settings if ( options ) { $.extend( settings, options ); } var $el = $(this), $wrapper = $el.find('div.ca-wrapper'), $items = $wrapper.children('div.ca-item'), cache = {}; // save the with of one item cache.itemW = $items.width(); // save the number of total items cache.totalItems = $items.length; // add navigation buttons if( cache.totalItems > 3 ) $el.prepend('<div class="ca-nav"><span class="ca-nav-prev">Previous</span><span class="ca-nav-next">Next</span></div>') // control the scroll value if( settings.scroll < 1 ) settings.scroll = 1; else if( settings.scroll > 3 ) settings.scroll = 3; var $navPrev = $el.find('span.ca-nav-prev'), $navNext = $el.find('span.ca-nav-next'); // hide the items except the first 3 $wrapper.css( 'overflow', 'hidden' ); // the items will have position absolute // calculate the left of each item $items.each(function(i) { $(this).css({ position : 'absolute', left : i * cache.itemW + 'px' }); }); // click to open the item(s) $el.find('a.ca-more').live('click.contentcarousel', function( event ) { if( cache.isAnimating ) return false; cache.isAnimating = true; $(this).hide(); var $item = $(this).closest('div.ca-item'); aux.openItem( $wrapper, $item, settings, cache ); return false; }); // click to close the item(s) $el.find('a.ca-close').live('click.contentcarousel', function( event ) { if( cache.isAnimating ) return false; cache.isAnimating = true; var $item = $(this).closest('div.ca-item'); aux.closeItems( $wrapper, $item, settings, cache ); return false; }); // navigate left $navPrev.bind('click.contentcarousel', function( event ) { if( cache.isAnimating ) return false; cache.isAnimating = true; aux.navigate( -1, $el, $wrapper, settings, cache ); }); // navigate right $navNext.bind('click.contentcarousel', function( event ) { if( cache.isAnimating ) return false; cache.isAnimating = true; aux.navigate( 1, $el, $wrapper, settings, cache ); }); // adds events to the mouse $el.bind('mousewheel.contentcarousel', function(e, delta) { if(delta > 0) { if( cache.isAnimating ) return false; cache.isAnimating = true; aux.navigate( -1, $el, $wrapper, settings, cache ); } else { if( cache.isAnimating ) return false; cache.isAnimating = true; aux.navigate( 1, $el, $wrapper, settings, cache ); } return false; }); }); } } }; $.fn.contentcarousel = function(method) { if ( methods[method] ) { return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 )); } else if ( typeof method === 'object' || ! method ) { return methods.init.apply( this, arguments ); } else { $.error( 'Method ' + method + ' does not exist on jQuery.contentcarousel' ); } }; })(jQuery);
JavaScript
/* Plugin: 3D Tag Sphere Version: 0.1 Author: Ian George Website: http://www.iangeorge.net Tools: Emacs, js2-mode Tested on: IE6, IE7, IE8, Firefox 3.6 Linux, Firefox 3.5 Windows, Chrome Linux / Windows Requirements: Optional jquery.mousewheel for zooming Description: 3d tag cloud, rotates with the mouse and zooms in and out. Fixed camera position to simplify calculations Known issues: Breaks badly on IE5.5 Looks a bit rough on page load TODO: Performance is horrible when more than one instance is present in the page Would be much quicker if instead of recalculating all values on mouse move a global phi/theta value pair is stored and the values calculated on-the-fly in Draw() Options: Option default Comments -------------------------------------------------- zoom 75 Initial zoom level min_zoom 0 max_zoom 100 zoom_factor 2 Speed of zoom by the mouse wheel rotate_by -1.75 In degrees, the amount that the sphere rotates. Negative values reverse the direction. fps 10 Defines the (target) number of times the animation will be updated per second centrex 250 Horizontal rotation centre in the container <div> centrey 250 Vertical rotation centre in the container <div> min_font_size 12 max_font_size 32 font_units 'px' random_points 50 Adds some random points on to the sphere to enhance the effect Usage: Vanilla: $('.tags').tagcloud(); Centreed in a 200 x 200 container: $('.tags').tagcloud({centrex:100,centrey:100}); With a different update speed $('.selector').tagcloud({fps:24}); Markup: Must be an unordered list in a div with links in the list items. rel="[number]" is optional but necessary for ranking by font-size. <div class="tags"> <ul> <li><a href="#" rel="20">link 1</a></li> <li><a href="#" rel="20">link 2</a></li> <li><a href="#" rel="20">link 3</a></li> <li><a href="#" rel="20">link 4</a></li> <li><a href="#" rel="20">link 5</a></li> </ul> */ (function($){ // jquery plugin hook $.fn.tagcloud = function(options){ // overwrite defaults with user-specified var opts = $.extend($.fn.tagcloud.defaults, options); opts.drawing_interval = 1/(opts.fps/1000); //create a new class for every matching element $(this).each(function(){ new TagCloudClass($(this), opts); }); return this; }; //default values for setup $.fn.tagcloud.defaults = { zoom: 75, max_zoom: 120, min_zoom: 25, zoom_factor: 2, //multiplication factor for wheel delta rotate_by: -1.75, // degrees fps: 10, // frames per second centrex: 250, // set centre of display centrey: 250, min_font_size: 12, //font limits and units max_font_size: 32, font_units: 'px', random_points: 0 }; var TagCloudClass = function(el, options){ $(el).css('position', 'relative'); $('ul', el).css('display', 'none'); // general values var eyez = -500; // set rotation (in this case, 5degrees) var rad = Math.PI/180; var basecos = Math.cos(options.rotate_by*rad); var basesin = Math.sin(options.rotate_by*rad); // initial rotation var sin = basesin; var cos = basecos; var hex = new Array("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"); // per-instance values var container = $(el); var id_stub = 'tc_' + $(this).attr('id') + "_"; var opts = options; var zoom = opts.zoom; var depth; var lastx = 0; var lasty = 0; var points = []; points['data'] = []; var drawing_interval; var cmx = options.centrex; var cmy = options.centrey; function getgrey(num){ if(num>256){num=256;} if(num<0){num=0;} var rem = num%16; var div = (num-rem)/16; var dig = hex[div] + hex[Math.floor(rem)]; return dig+dig+dig; } //drawing and rotation... function rotx(){ for(var p in points.data) { var temp = sin * points.data[p].y + cos * points.data[p].z; points.data[p].y = cos * points.data[p].y - sin * points.data[p].z; points.data[p].z = temp; } } function roty(){ for(var p in points.data){ var temp = - sin * points.data[p].x + cos * points.data[p].z; points.data[p].x = cos * points.data[p].x + sin * points.data[p].z; points.data[p].z = temp; } } function rotz(){ for(var p in points.data) { var temp = sin * points.data[p].x + cos * points.data[p].y; points.data[p].x = cos * points.data[p].x - sin * points.data[p].y; points.data[p].y = temp; } } function zoomed(by){ zoom += by*opts.zoom_factor; if (zoom>opts.max_zoom) { zoom = opts.max_zoom; } if (zoom<opts.min_zoom) { zoom = opts.min_zoom; } depth = -(zoom*(eyez-opts.max_zoom)/100)+eyez; } function moved(mx,my){ if(mx>lastx){ sin=-basesin; roty(); } if(mx<lastx){ sin=basesin; roty(); } if(my>lasty){ sin=basesin; rotx(); } if(my<lasty){ sin=-basesin; rotx(); } lastx = mx; lasty = my; } function draw(){ // calculate 2D coordinates var normalz = depth * depth; var minz = 0; var maxz = 0; for(var r_p in points.data){ if(points.data[r_p].z < minz){minz = points.data[r_p].z;} if(points.data[r_p].z > maxz){maxz = points.data[r_p].z;} } var diffz = minz-maxz; for(var s_p in points.data){ //normalise depth var u = (depth - eyez)/(points.data[s_p].z - eyez); // calculate normalised grey value var grey = parseInt((points.data[s_p].z/diffz)*165+80); var grey_hex = getgrey(grey); //set new 2d positions for the data $('#'+points.data[s_p].id + ' a', container).css('color','#'+grey_hex); $('#'+points.data[s_p].id, container).css('z-index',grey); $('#'+points.data[s_p].id, container).css('left', u * points.data[s_p].x + cmx - points.data[s_p].cwidth); $('#'+points.data[s_p].id, container).css('top', u * points.data[s_p].y + cmy); } } // number of elements we're adding and placeholders for range values points.count = $('li a', container).length; points.largest = 1; points.smallest = 0; // Run through each li > a in the container and create an absolutely-positioned div in its place // Also need to create a data structure to keep state between calls to draw() // Data structure is as follows: // // points{ // 'count':0, //Total number of points // 'largest':0, //largest 'size' value // 'smallest':0, //Smallest 'size' value // 'data':{ // 'id':"", //HTML id for element // 'size':0, //Size (from rel attribute on <a>) // 'theta':0.0, //Angle on sphere (used to calculate initial cartesian position) // 'phi': 0.0, //Angle on sphere (used to calculate initial cartesian position) // 'x':0.0, //Cartesian position in 3d space // 'y':0.0, //Cartesian position in 3d space // 'z':0.0, //Cartesian position in 3d space // } // } $('li a', container).each(function(idx, val){ var sz = parseInt($(this).attr('rel')); if(sz == 0) sz = 1; points.data[idx] = { id:id_stub + idx, size:sz }; // plot the points on a sphere // from: http://www.math.niu.edu/~rusin/known-math/97/spherefaq // for k=1 to N do // h = -1 + 2*(k-1)/(N-1) // theta[k] = arccos(h) // if k=1 or k=N then phi[k] = 0 // else phi[k] = (phi[k-1] + 3.6/sqrt(N*(1-h^2))) mod (2*pi) // endfor // In Cartesian coordinates the required point on a sphere of radius 1 is // (cos(theta)*sin(phi), sin(theta)*sin(phi), cos(phi)) var h = -1 + 2*(idx)/(points.count-1); points.data[idx].theta = Math.acos(h); if(idx == 0 || idx == points.count-1){ points.data[idx].phi = 0; } else{ points.data[idx].phi = (points.data[idx-1].phi + 3.6/Math.sqrt(points.count*(1-Math.pow(h,2)))) % (2 * Math.PI); } points.data[idx].x = Math.cos(points.data[idx].phi) * Math.sin(points.data[idx].theta) * (cmx/2); points.data[idx].y = Math.sin(points.data[idx].phi) * Math.sin(points.data[idx].theta) * (cmy/2); points.data[idx].z = Math.cos(points.data[idx].theta) * (cmx/2); if(sz > points.largest) points.largest = sz; if(sz < points.smallest) points.smallest = sz; container.append('<div id="'+ id_stub + idx +'" class="point" style="position:absolute;"><a href=' + $(this).attr('href') + '>' + $(this).html() + '</a></div>'); }); //if required to do so (by opts.random_points being > 0) we need to generate some random points on the sphere //bit cheezy, but can make more sparse data sets look a bit more believable if(opts.random_points > 0){ for(b=0; b<opts.random_points; b++){ points.count++; points.data[points.count] = { id:id_stub + points.count, size:1 }; points.data[points.count].theta = Math.random() * 2 * Math.PI; points.data[points.count].phi = Math.random() * 2 * Math.PI; points.data[points.count].x = Math.cos(points.data[points.count].phi) * Math.sin(points.data[points.count].theta) * (cmx/2); points.data[points.count].y = Math.sin(points.data[points.count].phi) * Math.sin(points.data[points.count].theta) * (cmy/2); points.data[points.count].z = Math.cos(points.data[points.count].theta) * (cmx/2); container.append('<div id="'+ id_stub + points.count +'" class="point" style="position:absolute;"><a>.</a></div>'); } } //tag size and font size ranges var sz_range = points.largest - points.smallest + 1; var sz_n_range = opts.max_font_size - opts.min_font_size + 1; //set font size to normalised tag size for(var p in points.data){ var sz = points.data[p].size; var sz_n = parseInt((sz / sz_range) * sz_n_range) + opts.min_font_size; if(!$('#' + points.data[p].id, container).hasClass('background')){ $('#' + points.data[p].id, container).css('font-size', sz_n); } //store element width / 2 so we can centre the text around the point later. points.data[p].cwidth = $('#' + points.data[p].id, container).width()/2; } // bin original html $('ul', container).remove(); //set up initial view zoomed(opts.zoom); moved(cmx, cmy); //call draw every so often drawing_interval = setInterval(draw, opts.drawing_interval); //events to change position of items container.mousemove(function(evt){ moved(evt.clientX, evt.clientY); }); container.mousewheel(function(evt, delta){ zoomed(delta); evt.preventDefault(); return false; }); }; })(jQuery);
JavaScript
/** * SWFObject v1.4: Flash Player detection and embed - http://blog.deconcept.com/swfobject/ * * SWFObject is (c) 2006 Geoff Stearns and is released under the MIT License: * http://www.opensource.org/licenses/mit-license.php * * **SWFObject is the SWF embed script formarly known as FlashObject. The name was changed for * legal reasons. */ if(typeof deconcept=="undefined"){var deconcept=new Object();} if(typeof deconcept.util=="undefined"){deconcept.util=new Object();} if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();} deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a,_b){ if(!document.createElement||!document.getElementById){return;} this.DETECT_KEY=_b?_b:"detectflash"; this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY); this.params=new Object(); this.variables=new Object(); this.attributes=new Array(); if(_1){this.setAttribute("swf",_1);} if(id){this.setAttribute("id",id);} if(w){this.setAttribute("width",w);} if(h){this.setAttribute("height",h);} if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));} this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion(this.getAttribute("version"),_7); if(c){this.addParam("bgcolor",c);} var q=_8?_8:"high"; this.addParam("quality",q); this.setAttribute("useExpressInstall",_7); this.setAttribute("doExpressInstall",false); var _d=(_9)?_9:window.location; this.setAttribute("xiRedirectUrl",_d); this.setAttribute("redirectUrl",""); if(_a){this.setAttribute("redirectUrl",_a);}}; deconcept.SWFObject.prototype={setAttribute:function(_e,_f){ this.attributes[_e]=_f; },getAttribute:function(_10){ return this.attributes[_10]; },addParam:function(_11,_12){ this.params[_11]=_12; },getParams:function(){ return this.params; },addVariable:function(_13,_14){ this.variables[_13]=_14; },getVariable:function(_15){ return this.variables[_15]; },getVariables:function(){ return this.variables; },getVariablePairs:function(){ var _16=new Array(); var key; var _18=this.getVariables(); for(key in _18){ _16.push(key+"="+_18[key]);} return _16; },getSWFHTML:function(){ var _19=""; if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){ if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");} _19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\""; _19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" "; var _1a=this.getParams(); for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";} var _1c=this.getVariablePairs().join("&"); if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";} _19+="/>"; }else{ if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");} _19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\">"; _19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />"; var _1d=this.getParams(); for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";} var _1f=this.getVariablePairs().join("&"); if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";} _19+="</object>";} return _19; },write:function(_20){ if(this.getAttribute("useExpressInstall")){ var _21=new deconcept.PlayerVersion([6,0,65]); if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){ this.setAttribute("doExpressInstall",true); this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl"))); document.title=document.title.slice(0,47)+" - Flash Player Installation"; this.addVariable("MMdoctitle",document.title);}} if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){ var n=(typeof _20=="string")?document.getElementById(_20):_20; n.innerHTML=this.getSWFHTML(); return true; }else{ if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}} return false;}}; deconcept.SWFObjectUtil.getPlayerVersion=function(_23,_24){ var _25=new deconcept.PlayerVersion([0,0,0]); if(navigator.plugins&&navigator.mimeTypes.length){ var x=navigator.plugins["Shockwave Flash"]; if(x&&x.description){_25=new deconcept.PlayerVersion(x.description.replace(/([a-z]|[A-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));} }else{try{ var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash"); for(var i=3;axo!=null;i++){ axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+i); _25=new deconcept.PlayerVersion([i,0,0]);}} catch(e){} if(_23&&_25.major>_23.major){return _25;} if(!_23||((_23.minor!=0||_23.rev!=0)&&_25.major==_23.major)||_25.major!=6||_24){ try{_25=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));} catch(e){}}} return _25;}; deconcept.PlayerVersion=function(_29){ this.major=parseInt(_29[0])!=null?parseInt(_29[0]):0; this.minor=parseInt(_29[1])||0; this.rev=parseInt(_29[2])||0;}; deconcept.PlayerVersion.prototype.versionIsValid=function(fv){ if(this.major<fv.major){return false;} if(this.major>fv.major){return true;} if(this.minor<fv.minor){return false;} if(this.minor>fv.minor){return true;} if(this.rev<fv.rev){return false;}return true;}; deconcept.util={getRequestParameter:function(_2b){ var q=document.location.search||document.location.hash; if(q){ var _2d=q.indexOf(_2b+"="); var _2e=(q.indexOf("&",_2d)>-1)?q.indexOf("&",_2d):q.length; if(q.length>1&&_2d>-1){ return q.substring(q.indexOf("=",_2d)+1,_2e); }}return "";}}; if(Array.prototype.push==null){ Array.prototype.push=function(_2f){ this[this.length]=_2f; return this.length;};} var getQueryParamValue=deconcept.util.getRequestParameter; var FlashObject=deconcept.SWFObject; // for backwards compatibility var SWFObject=deconcept.SWFObject;
JavaScript
// Copyright 2006 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Known Issues: // // * Patterns only support repeat. // * Radial gradient are not implemented. The VML version of these look very // different from the canvas one. // * Clipping paths are not implemented. // * Coordsize. The width and height attribute have higher priority than the // width and height style values which isn't correct. // * Painting mode isn't implemented. // * Canvas width/height should is using content-box by default. IE in // Quirks mode will draw the canvas using border-box. Either change your // doctype to HTML5 // (http://www.whatwg.org/specs/web-apps/current-work/#the-doctype) // or use Box Sizing Behavior from WebFX // (http://webfx.eae.net/dhtml/boxsizing/boxsizing.html) // * Non uniform scaling does not correctly scale strokes. // * Optimize. There is always room for speed improvements. // Only add this code if we do not already have a canvas implementation if (!document.createElement('canvas').getContext) { (function() { // alias some functions to make (compiled) code shorter var m = Math; var mr = m.round; var ms = m.sin; var mc = m.cos; var abs = m.abs; var sqrt = m.sqrt; // this is used for sub pixel precision var Z = 10; var Z2 = Z / 2; var IE_VERSION = +navigator.userAgent.match(/MSIE ([\d.]+)?/)[1]; /** * This funtion is assigned to the <canvas> elements as element.getContext(). * @this {HTMLElement} * @return {CanvasRenderingContext2D_} */ function getContext() { return this.context_ || (this.context_ = new CanvasRenderingContext2D_(this)); } var slice = Array.prototype.slice; /** * Binds a function to an object. The returned function will always use the * passed in {@code obj} as {@code this}. * * Example: * * g = bind(f, obj, a, b) * g(c, d) // will do f.call(obj, a, b, c, d) * * @param {Function} f The function to bind the object to * @param {Object} obj The object that should act as this when the function * is called * @param {*} var_args Rest arguments that will be used as the initial * arguments when the function is called * @return {Function} A new function that has bound this */ function bind(f, obj, var_args) { var a = slice.call(arguments, 2); return function() { return f.apply(obj, a.concat(slice.call(arguments))); }; } function encodeHtmlAttribute(s) { return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;'); } function addNamespace(doc, prefix, urn) { if (!doc.namespaces[prefix]) { doc.namespaces.add(prefix, urn, '#default#VML'); } } function addNamespacesAndStylesheet(doc) { addNamespace(doc, 'g_vml_', 'urn:schemas-microsoft-com:vml'); addNamespace(doc, 'g_o_', 'urn:schemas-microsoft-com:office:office'); // Setup default CSS. Only add one style sheet per document if (!doc.styleSheets['ex_canvas_']) { var ss = doc.createStyleSheet(); ss.owningElement.id = 'ex_canvas_'; ss.cssText = 'canvas{display:inline-block;overflow:hidden;' + // default size is 300x150 in Gecko and Opera 'text-align:left;width:300px;height:150px}'; } } // Add namespaces and stylesheet at startup. addNamespacesAndStylesheet(document); var G_vmlCanvasManager_ = { init: function(opt_doc) { var doc = opt_doc || document; // Create a dummy element so that IE will allow canvas elements to be // recognized. doc.createElement('canvas'); doc.attachEvent('onreadystatechange', bind(this.init_, this, doc)); }, init_: function(doc) { // find all canvas elements var els = doc.getElementsByTagName('canvas'); for (var i = 0; i < els.length; i++) { this.initElement(els[i]); } }, /** * Public initializes a canvas element so that it can be used as canvas * element from now on. This is called automatically before the page is * loaded but if you are creating elements using createElement you need to * make sure this is called on the element. * @param {HTMLElement} el The canvas element to initialize. * @return {HTMLElement} the element that was created. */ initElement: function(el) { if (!el.getContext) { el.getContext = getContext; // Add namespaces and stylesheet to document of the element. addNamespacesAndStylesheet(el.ownerDocument); // Remove fallback content. There is no way to hide text nodes so we // just remove all childNodes. We could hide all elements and remove // text nodes but who really cares about the fallback content. el.innerHTML = ''; // do not use inline function because that will leak memory el.attachEvent('onpropertychange', onPropertyChange); el.attachEvent('onresize', onResize); var attrs = el.attributes; if (attrs.width && attrs.width.specified) { // TODO: use runtimeStyle and coordsize // el.getContext().setWidth_(attrs.width.nodeValue); el.style.width = attrs.width.nodeValue + 'px'; } else { el.width = el.clientWidth; } if (attrs.height && attrs.height.specified) { // TODO: use runtimeStyle and coordsize // el.getContext().setHeight_(attrs.height.nodeValue); el.style.height = attrs.height.nodeValue + 'px'; } else { el.height = el.clientHeight; } //el.getContext().setCoordsize_() } return el; } }; function onPropertyChange(e) { var el = e.srcElement; switch (e.propertyName) { case 'width': el.getContext().clearRect(); el.style.width = el.attributes.width.nodeValue + 'px'; // In IE8 this does not trigger onresize. el.firstChild.style.width = el.clientWidth + 'px'; break; case 'height': el.getContext().clearRect(); el.style.height = el.attributes.height.nodeValue + 'px'; el.firstChild.style.height = el.clientHeight + 'px'; break; } } function onResize(e) { var el = e.srcElement; if (el.firstChild) { el.firstChild.style.width = el.clientWidth + 'px'; el.firstChild.style.height = el.clientHeight + 'px'; } } G_vmlCanvasManager_.init(); // precompute "00" to "FF" var decToHex = []; for (var i = 0; i < 16; i++) { for (var j = 0; j < 16; j++) { decToHex[i * 16 + j] = i.toString(16) + j.toString(16); } } function createMatrixIdentity() { return [ [1, 0, 0], [0, 1, 0], [0, 0, 1] ]; } function matrixMultiply(m1, m2) { var result = createMatrixIdentity(); for (var x = 0; x < 3; x++) { for (var y = 0; y < 3; y++) { var sum = 0; for (var z = 0; z < 3; z++) { sum += m1[x][z] * m2[z][y]; } result[x][y] = sum; } } return result; } function copyState(o1, o2) { o2.fillStyle = o1.fillStyle; o2.lineCap = o1.lineCap; o2.lineJoin = o1.lineJoin; o2.lineWidth = o1.lineWidth; o2.miterLimit = o1.miterLimit; o2.shadowBlur = o1.shadowBlur; o2.shadowColor = o1.shadowColor; o2.shadowOffsetX = o1.shadowOffsetX; o2.shadowOffsetY = o1.shadowOffsetY; o2.strokeStyle = o1.strokeStyle; o2.globalAlpha = o1.globalAlpha; o2.font = o1.font; o2.textAlign = o1.textAlign; o2.textBaseline = o1.textBaseline; o2.arcScaleX_ = o1.arcScaleX_; o2.arcScaleY_ = o1.arcScaleY_; o2.lineScale_ = o1.lineScale_; } var colorData = { aliceblue: '#F0F8FF', antiquewhite: '#FAEBD7', aquamarine: '#7FFFD4', azure: '#F0FFFF', beige: '#F5F5DC', bisque: '#FFE4C4', black: '#000000', blanchedalmond: '#FFEBCD', blueviolet: '#8A2BE2', brown: '#A52A2A', burlywood: '#DEB887', cadetblue: '#5F9EA0', chartreuse: '#7FFF00', chocolate: '#D2691E', coral: '#FF7F50', cornflowerblue: '#6495ED', cornsilk: '#FFF8DC', crimson: '#DC143C', cyan: '#00FFFF', darkblue: '#00008B', darkcyan: '#008B8B', darkgoldenrod: '#B8860B', darkgray: '#A9A9A9', darkgreen: '#006400', darkgrey: '#A9A9A9', darkkhaki: '#BDB76B', darkmagenta: '#8B008B', darkolivegreen: '#556B2F', darkorange: '#FF8C00', darkorchid: '#9932CC', darkred: '#8B0000', darksalmon: '#E9967A', darkseagreen: '#8FBC8F', darkslateblue: '#483D8B', darkslategray: '#2F4F4F', darkslategrey: '#2F4F4F', darkturquoise: '#00CED1', darkviolet: '#9400D3', deeppink: '#FF1493', deepskyblue: '#00BFFF', dimgray: '#696969', dimgrey: '#696969', dodgerblue: '#1E90FF', firebrick: '#B22222', floralwhite: '#FFFAF0', forestgreen: '#228B22', gainsboro: '#DCDCDC', ghostwhite: '#F8F8FF', gold: '#FFD700', goldenrod: '#DAA520', grey: '#808080', greenyellow: '#ADFF2F', honeydew: '#F0FFF0', hotpink: '#FF69B4', indianred: '#CD5C5C', indigo: '#4B0082', ivory: '#FFFFF0', khaki: '#F0E68C', lavender: '#E6E6FA', lavenderblush: '#FFF0F5', lawngreen: '#7CFC00', lemonchiffon: '#FFFACD', lightblue: '#ADD8E6', lightcoral: '#F08080', lightcyan: '#E0FFFF', lightgoldenrodyellow: '#FAFAD2', lightgreen: '#90EE90', lightgrey: '#D3D3D3', lightpink: '#FFB6C1', lightsalmon: '#FFA07A', lightseagreen: '#20B2AA', lightskyblue: '#87CEFA', lightslategray: '#778899', lightslategrey: '#778899', lightsteelblue: '#B0C4DE', lightyellow: '#FFFFE0', limegreen: '#32CD32', linen: '#FAF0E6', magenta: '#FF00FF', mediumaquamarine: '#66CDAA', mediumblue: '#0000CD', mediumorchid: '#BA55D3', mediumpurple: '#9370DB', mediumseagreen: '#3CB371', mediumslateblue: '#7B68EE', mediumspringgreen: '#00FA9A', mediumturquoise: '#48D1CC', mediumvioletred: '#C71585', midnightblue: '#191970', mintcream: '#F5FFFA', mistyrose: '#FFE4E1', moccasin: '#FFE4B5', navajowhite: '#FFDEAD', oldlace: '#FDF5E6', olivedrab: '#6B8E23', orange: '#FFA500', orangered: '#FF4500', orchid: '#DA70D6', palegoldenrod: '#EEE8AA', palegreen: '#98FB98', paleturquoise: '#AFEEEE', palevioletred: '#DB7093', papayawhip: '#FFEFD5', peachpuff: '#FFDAB9', peru: '#CD853F', pink: '#FFC0CB', plum: '#DDA0DD', powderblue: '#B0E0E6', rosybrown: '#BC8F8F', royalblue: '#4169E1', saddlebrown: '#8B4513', salmon: '#FA8072', sandybrown: '#F4A460', seagreen: '#2E8B57', seashell: '#FFF5EE', sienna: '#A0522D', skyblue: '#87CEEB', slateblue: '#6A5ACD', slategray: '#708090', slategrey: '#708090', snow: '#FFFAFA', springgreen: '#00FF7F', steelblue: '#4682B4', tan: '#D2B48C', thistle: '#D8BFD8', tomato: '#FF6347', turquoise: '#40E0D0', violet: '#EE82EE', wheat: '#F5DEB3', whitesmoke: '#F5F5F5', yellowgreen: '#9ACD32' }; function getRgbHslContent(styleString) { var start = styleString.indexOf('(', 3); var end = styleString.indexOf(')', start + 1); var parts = styleString.substring(start + 1, end).split(','); // add alpha if needed if (parts.length != 4 || styleString.charAt(3) != 'a') { parts[3] = 1; } return parts; } function percent(s) { return parseFloat(s) / 100; } function clamp(v, min, max) { return Math.min(max, Math.max(min, v)); } function hslToRgb(parts){ var r, g, b, h, s, l; h = parseFloat(parts[0]) / 360 % 360; if (h < 0) h++; s = clamp(percent(parts[1]), 0, 1); l = clamp(percent(parts[2]), 0, 1); if (s == 0) { r = g = b = l; // achromatic } else { var q = l < 0.5 ? l * (1 + s) : l + s - l * s; var p = 2 * l - q; r = hueToRgb(p, q, h + 1 / 3); g = hueToRgb(p, q, h); b = hueToRgb(p, q, h - 1 / 3); } return '#' + decToHex[Math.floor(r * 255)] + decToHex[Math.floor(g * 255)] + decToHex[Math.floor(b * 255)]; } function hueToRgb(m1, m2, h) { if (h < 0) h++; if (h > 1) h--; if (6 * h < 1) return m1 + (m2 - m1) * 6 * h; else if (2 * h < 1) return m2; else if (3 * h < 2) return m1 + (m2 - m1) * (2 / 3 - h) * 6; else return m1; } var processStyleCache = {}; function processStyle(styleString) { if (styleString in processStyleCache) { return processStyleCache[styleString]; } var str, alpha = 1; styleString = String(styleString); if (styleString.charAt(0) == '#') { str = styleString; } else if (/^rgb/.test(styleString)) { var parts = getRgbHslContent(styleString); var str = '#', n; for (var i = 0; i < 3; i++) { if (parts[i].indexOf('%') != -1) { n = Math.floor(percent(parts[i]) * 255); } else { n = +parts[i]; } str += decToHex[clamp(n, 0, 255)]; } alpha = +parts[3]; } else if (/^hsl/.test(styleString)) { var parts = getRgbHslContent(styleString); str = hslToRgb(parts); alpha = parts[3]; } else { str = colorData[styleString] || styleString; } return processStyleCache[styleString] = {color: str, alpha: alpha}; } var DEFAULT_STYLE = { style: 'normal', variant: 'normal', weight: 'normal', size: 10, family: 'sans-serif' }; // Internal text style cache var fontStyleCache = {}; function processFontStyle(styleString) { if (fontStyleCache[styleString]) { return fontStyleCache[styleString]; } var el = document.createElement('div'); var style = el.style; try { style.font = styleString; } catch (ex) { // Ignore failures to set to invalid font. } return fontStyleCache[styleString] = { style: style.fontStyle || DEFAULT_STYLE.style, variant: style.fontVariant || DEFAULT_STYLE.variant, weight: style.fontWeight || DEFAULT_STYLE.weight, size: style.fontSize || DEFAULT_STYLE.size, family: style.fontFamily || DEFAULT_STYLE.family }; } function getComputedStyle(style, element) { var computedStyle = {}; for (var p in style) { computedStyle[p] = style[p]; } // Compute the size var canvasFontSize = parseFloat(element.currentStyle.fontSize), fontSize = parseFloat(style.size); if (typeof style.size == 'number') { computedStyle.size = style.size; } else if (style.size.indexOf('px') != -1) { computedStyle.size = fontSize; } else if (style.size.indexOf('em') != -1) { computedStyle.size = canvasFontSize * fontSize; } else if(style.size.indexOf('%') != -1) { computedStyle.size = (canvasFontSize / 100) * fontSize; } else if (style.size.indexOf('pt') != -1) { computedStyle.size = fontSize / .75; } else { computedStyle.size = canvasFontSize; } // Different scaling between normal text and VML text. This was found using // trial and error to get the same size as non VML text. computedStyle.size *= 0.981; return computedStyle; } function buildStyle(style) { return style.style + ' ' + style.variant + ' ' + style.weight + ' ' + style.size + 'px ' + style.family; } var lineCapMap = { 'butt': 'flat', 'round': 'round' }; function processLineCap(lineCap) { return lineCapMap[lineCap] || 'square'; } /** * This class implements CanvasRenderingContext2D interface as described by * the WHATWG. * @param {HTMLElement} canvasElement The element that the 2D context should * be associated with */ function CanvasRenderingContext2D_(canvasElement) { this.m_ = createMatrixIdentity(); this.mStack_ = []; this.aStack_ = []; this.currentPath_ = []; // Canvas context properties this.strokeStyle = '#000'; this.fillStyle = '#000'; this.lineWidth = 1; this.lineJoin = 'miter'; this.lineCap = 'butt'; this.miterLimit = Z * 1; this.globalAlpha = 1; this.font = '10px sans-serif'; this.textAlign = 'left'; this.textBaseline = 'alphabetic'; this.canvas = canvasElement; var cssText = 'width:' + canvasElement.clientWidth + 'px;height:' + canvasElement.clientHeight + 'px;overflow:hidden;position:absolute'; var el = canvasElement.ownerDocument.createElement('div'); el.style.cssText = cssText; canvasElement.appendChild(el); var overlayEl = el.cloneNode(false); // Use a non transparent background. overlayEl.style.backgroundColor = 'red'; overlayEl.style.filter = 'alpha(opacity=0)'; canvasElement.appendChild(overlayEl); this.element_ = el; this.arcScaleX_ = 1; this.arcScaleY_ = 1; this.lineScale_ = 1; } var contextPrototype = CanvasRenderingContext2D_.prototype; contextPrototype.clearRect = function() { if (this.textMeasureEl_) { this.textMeasureEl_.removeNode(true); this.textMeasureEl_ = null; } this.element_.innerHTML = ''; }; contextPrototype.beginPath = function() { // TODO: Branch current matrix so that save/restore has no effect // as per safari docs. this.currentPath_ = []; }; contextPrototype.moveTo = function(aX, aY) { var p = getCoords(this, aX, aY); this.currentPath_.push({type: 'moveTo', x: p.x, y: p.y}); this.currentX_ = p.x; this.currentY_ = p.y; }; contextPrototype.lineTo = function(aX, aY) { var p = getCoords(this, aX, aY); this.currentPath_.push({type: 'lineTo', x: p.x, y: p.y}); this.currentX_ = p.x; this.currentY_ = p.y; }; contextPrototype.bezierCurveTo = function(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) { var p = getCoords(this, aX, aY); var cp1 = getCoords(this, aCP1x, aCP1y); var cp2 = getCoords(this, aCP2x, aCP2y); bezierCurveTo(this, cp1, cp2, p); }; // Helper function that takes the already fixed cordinates. function bezierCurveTo(self, cp1, cp2, p) { self.currentPath_.push({ type: 'bezierCurveTo', cp1x: cp1.x, cp1y: cp1.y, cp2x: cp2.x, cp2y: cp2.y, x: p.x, y: p.y }); self.currentX_ = p.x; self.currentY_ = p.y; } contextPrototype.quadraticCurveTo = function(aCPx, aCPy, aX, aY) { // the following is lifted almost directly from // http://developer.mozilla.org/en/docs/Canvas_tutorial:Drawing_shapes var cp = getCoords(this, aCPx, aCPy); var p = getCoords(this, aX, aY); var cp1 = { x: this.currentX_ + 2.0 / 3.0 * (cp.x - this.currentX_), y: this.currentY_ + 2.0 / 3.0 * (cp.y - this.currentY_) }; var cp2 = { x: cp1.x + (p.x - this.currentX_) / 3.0, y: cp1.y + (p.y - this.currentY_) / 3.0 }; bezierCurveTo(this, cp1, cp2, p); }; contextPrototype.arc = function(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) { aRadius *= Z; var arcType = aClockwise ? 'at' : 'wa'; var xStart = aX + mc(aStartAngle) * aRadius - Z2; var yStart = aY + ms(aStartAngle) * aRadius - Z2; var xEnd = aX + mc(aEndAngle) * aRadius - Z2; var yEnd = aY + ms(aEndAngle) * aRadius - Z2; // IE won't render arches drawn counter clockwise if xStart == xEnd. if (xStart == xEnd && !aClockwise) { xStart += 0.125; // Offset xStart by 1/80 of a pixel. Use something // that can be represented in binary } var p = getCoords(this, aX, aY); var pStart = getCoords(this, xStart, yStart); var pEnd = getCoords(this, xEnd, yEnd); this.currentPath_.push({type: arcType, x: p.x, y: p.y, radius: aRadius, xStart: pStart.x, yStart: pStart.y, xEnd: pEnd.x, yEnd: pEnd.y}); }; contextPrototype.rect = function(aX, aY, aWidth, aHeight) { this.moveTo(aX, aY); this.lineTo(aX + aWidth, aY); this.lineTo(aX + aWidth, aY + aHeight); this.lineTo(aX, aY + aHeight); this.closePath(); }; contextPrototype.strokeRect = function(aX, aY, aWidth, aHeight) { var oldPath = this.currentPath_; this.beginPath(); this.moveTo(aX, aY); this.lineTo(aX + aWidth, aY); this.lineTo(aX + aWidth, aY + aHeight); this.lineTo(aX, aY + aHeight); this.closePath(); this.stroke(); this.currentPath_ = oldPath; }; contextPrototype.fillRect = function(aX, aY, aWidth, aHeight) { var oldPath = this.currentPath_; this.beginPath(); this.moveTo(aX, aY); this.lineTo(aX + aWidth, aY); this.lineTo(aX + aWidth, aY + aHeight); this.lineTo(aX, aY + aHeight); this.closePath(); this.fill(); this.currentPath_ = oldPath; }; contextPrototype.createLinearGradient = function(aX0, aY0, aX1, aY1) { var gradient = new CanvasGradient_('gradient'); gradient.x0_ = aX0; gradient.y0_ = aY0; gradient.x1_ = aX1; gradient.y1_ = aY1; return gradient; }; contextPrototype.createRadialGradient = function(aX0, aY0, aR0, aX1, aY1, aR1) { var gradient = new CanvasGradient_('gradientradial'); gradient.x0_ = aX0; gradient.y0_ = aY0; gradient.r0_ = aR0; gradient.x1_ = aX1; gradient.y1_ = aY1; gradient.r1_ = aR1; return gradient; }; contextPrototype.drawImage = function(image, var_args) { var dx, dy, dw, dh, sx, sy, sw, sh; // to find the original width we overide the width and height var oldRuntimeWidth = image.runtimeStyle.width; var oldRuntimeHeight = image.runtimeStyle.height; image.runtimeStyle.width = 'auto'; image.runtimeStyle.height = 'auto'; // get the original size var w = image.width; var h = image.height; // and remove overides image.runtimeStyle.width = oldRuntimeWidth; image.runtimeStyle.height = oldRuntimeHeight; if (arguments.length == 3) { dx = arguments[1]; dy = arguments[2]; sx = sy = 0; sw = dw = w; sh = dh = h; } else if (arguments.length == 5) { dx = arguments[1]; dy = arguments[2]; dw = arguments[3]; dh = arguments[4]; sx = sy = 0; sw = w; sh = h; } else if (arguments.length == 9) { sx = arguments[1]; sy = arguments[2]; sw = arguments[3]; sh = arguments[4]; dx = arguments[5]; dy = arguments[6]; dw = arguments[7]; dh = arguments[8]; } else { throw Error('Invalid number of arguments'); } var d = getCoords(this, dx, dy); var w2 = sw / 2; var h2 = sh / 2; var vmlStr = []; var W = 10; var H = 10; // For some reason that I've now forgotten, using divs didn't work vmlStr.push(' <g_vml_:group', ' coordsize="', Z * W, ',', Z * H, '"', ' coordorigin="0,0"' , ' style="width:', W, 'px;height:', H, 'px;position:absolute;'); // If filters are necessary (rotation exists), create them // filters are bog-slow, so only create them if abbsolutely necessary // The following check doesn't account for skews (which don't exist // in the canvas spec (yet) anyway. if (this.m_[0][0] != 1 || this.m_[0][1] || this.m_[1][1] != 1 || this.m_[1][0]) { var filter = []; // Note the 12/21 reversal filter.push('M11=', this.m_[0][0], ',', 'M12=', this.m_[1][0], ',', 'M21=', this.m_[0][1], ',', 'M22=', this.m_[1][1], ',', 'Dx=', mr(d.x / Z), ',', 'Dy=', mr(d.y / Z), ''); // Bounding box calculation (need to minimize displayed area so that // filters don't waste time on unused pixels. var max = d; var c2 = getCoords(this, dx + dw, dy); var c3 = getCoords(this, dx, dy + dh); var c4 = getCoords(this, dx + dw, dy + dh); max.x = m.max(max.x, c2.x, c3.x, c4.x); max.y = m.max(max.y, c2.y, c3.y, c4.y); vmlStr.push('padding:0 ', mr(max.x / Z), 'px ', mr(max.y / Z), 'px 0;filter:progid:DXImageTransform.Microsoft.Matrix(', filter.join(''), ", sizingmethod='clip');"); } else { vmlStr.push('top:', mr(d.y / Z), 'px;left:', mr(d.x / Z), 'px;'); } vmlStr.push(' ">' , '<g_vml_:image src="', image.src, '"', ' style="width:', Z * dw, 'px;', ' height:', Z * dh, 'px"', ' cropleft="', sx / w, '"', ' croptop="', sy / h, '"', ' cropright="', (w - sx - sw) / w, '"', ' cropbottom="', (h - sy - sh) / h, '"', ' />', '</g_vml_:group>'); this.element_.insertAdjacentHTML('BeforeEnd', vmlStr.join('')); }; contextPrototype.stroke = function(aFill) { var lineStr = []; var lineOpen = false; var W = 10; var H = 10; lineStr.push('<g_vml_:shape', ' filled="', !!aFill, '"', ' style="position:absolute;width:', W, 'px;height:', H, 'px;"', ' coordorigin="0,0"', ' coordsize="', Z * W, ',', Z * H, '"', ' stroked="', !aFill, '"', ' path="'); var newSeq = false; var min = {x: null, y: null}; var max = {x: null, y: null}; for (var i = 0; i < this.currentPath_.length; i++) { var p = this.currentPath_[i]; var c; switch (p.type) { case 'moveTo': c = p; lineStr.push(' m ', mr(p.x), ',', mr(p.y)); break; case 'lineTo': lineStr.push(' l ', mr(p.x), ',', mr(p.y)); break; case 'close': lineStr.push(' x '); p = null; break; case 'bezierCurveTo': lineStr.push(' c ', mr(p.cp1x), ',', mr(p.cp1y), ',', mr(p.cp2x), ',', mr(p.cp2y), ',', mr(p.x), ',', mr(p.y)); break; case 'at': case 'wa': lineStr.push(' ', p.type, ' ', mr(p.x - this.arcScaleX_ * p.radius), ',', mr(p.y - this.arcScaleY_ * p.radius), ' ', mr(p.x + this.arcScaleX_ * p.radius), ',', mr(p.y + this.arcScaleY_ * p.radius), ' ', mr(p.xStart), ',', mr(p.yStart), ' ', mr(p.xEnd), ',', mr(p.yEnd)); break; } // TODO: Following is broken for curves due to // move to proper paths. // Figure out dimensions so we can do gradient fills // properly if (p) { if (min.x == null || p.x < min.x) { min.x = p.x; } if (max.x == null || p.x > max.x) { max.x = p.x; } if (min.y == null || p.y < min.y) { min.y = p.y; } if (max.y == null || p.y > max.y) { max.y = p.y; } } } lineStr.push(' ">'); if (!aFill) { appendStroke(this, lineStr); } else { appendFill(this, lineStr, min, max); } lineStr.push('</g_vml_:shape>'); this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); }; function appendStroke(ctx, lineStr) { var a = processStyle(ctx.strokeStyle); var color = a.color; var opacity = a.alpha * ctx.globalAlpha; var lineWidth = ctx.lineScale_ * ctx.lineWidth; // VML cannot correctly render a line if the width is less than 1px. // In that case, we dilute the color to make the line look thinner. if (lineWidth < 1) { opacity *= lineWidth; } lineStr.push( '<g_vml_:stroke', ' opacity="', opacity, '"', ' joinstyle="', ctx.lineJoin, '"', ' miterlimit="', ctx.miterLimit, '"', ' endcap="', processLineCap(ctx.lineCap), '"', ' weight="', lineWidth, 'px"', ' color="', color, '" />' ); } function appendFill(ctx, lineStr, min, max) { var fillStyle = ctx.fillStyle; var arcScaleX = ctx.arcScaleX_; var arcScaleY = ctx.arcScaleY_; var width = max.x - min.x; var height = max.y - min.y; if (fillStyle instanceof CanvasGradient_) { // TODO: Gradients transformed with the transformation matrix. var angle = 0; var focus = {x: 0, y: 0}; // additional offset var shift = 0; // scale factor for offset var expansion = 1; if (fillStyle.type_ == 'gradient') { var x0 = fillStyle.x0_ / arcScaleX; var y0 = fillStyle.y0_ / arcScaleY; var x1 = fillStyle.x1_ / arcScaleX; var y1 = fillStyle.y1_ / arcScaleY; var p0 = getCoords(ctx, x0, y0); var p1 = getCoords(ctx, x1, y1); var dx = p1.x - p0.x; var dy = p1.y - p0.y; angle = Math.atan2(dx, dy) * 180 / Math.PI; // The angle should be a non-negative number. if (angle < 0) { angle += 360; } // Very small angles produce an unexpected result because they are // converted to a scientific notation string. if (angle < 1e-6) { angle = 0; } } else { var p0 = getCoords(ctx, fillStyle.x0_, fillStyle.y0_); focus = { x: (p0.x - min.x) / width, y: (p0.y - min.y) / height }; width /= arcScaleX * Z; height /= arcScaleY * Z; var dimension = m.max(width, height); shift = 2 * fillStyle.r0_ / dimension; expansion = 2 * fillStyle.r1_ / dimension - shift; } // We need to sort the color stops in ascending order by offset, // otherwise IE won't interpret it correctly. var stops = fillStyle.colors_; stops.sort(function(cs1, cs2) { return cs1.offset - cs2.offset; }); var length = stops.length; var color1 = stops[0].color; var color2 = stops[length - 1].color; var opacity1 = stops[0].alpha * ctx.globalAlpha; var opacity2 = stops[length - 1].alpha * ctx.globalAlpha; var colors = []; for (var i = 0; i < length; i++) { var stop = stops[i]; colors.push(stop.offset * expansion + shift + ' ' + stop.color); } // When colors attribute is used, the meanings of opacity and o:opacity2 // are reversed. lineStr.push('<g_vml_:fill type="', fillStyle.type_, '"', ' method="none" focus="100%"', ' color="', color1, '"', ' color2="', color2, '"', ' colors="', colors.join(','), '"', ' opacity="', opacity2, '"', ' g_o_:opacity2="', opacity1, '"', ' angle="', angle, '"', ' focusposition="', focus.x, ',', focus.y, '" />'); } else if (fillStyle instanceof CanvasPattern_) { if (width && height) { var deltaLeft = -min.x; var deltaTop = -min.y; lineStr.push('<g_vml_:fill', ' position="', deltaLeft / width * arcScaleX * arcScaleX, ',', deltaTop / height * arcScaleY * arcScaleY, '"', ' type="tile"', // TODO: Figure out the correct size to fit the scale. //' size="', w, 'px ', h, 'px"', ' src="', fillStyle.src_, '" />'); } } else { var a = processStyle(ctx.fillStyle); var color = a.color; var opacity = a.alpha * ctx.globalAlpha; lineStr.push('<g_vml_:fill color="', color, '" opacity="', opacity, '" />'); } } contextPrototype.fill = function() { this.stroke(true); }; contextPrototype.closePath = function() { this.currentPath_.push({type: 'close'}); }; function getCoords(ctx, aX, aY) { var m = ctx.m_; return { x: Z * (aX * m[0][0] + aY * m[1][0] + m[2][0]) - Z2, y: Z * (aX * m[0][1] + aY * m[1][1] + m[2][1]) - Z2 }; }; contextPrototype.save = function() { var o = {}; copyState(this, o); this.aStack_.push(o); this.mStack_.push(this.m_); this.m_ = matrixMultiply(createMatrixIdentity(), this.m_); }; contextPrototype.restore = function() { if (this.aStack_.length) { copyState(this.aStack_.pop(), this); this.m_ = this.mStack_.pop(); } }; function matrixIsFinite(m) { return isFinite(m[0][0]) && isFinite(m[0][1]) && isFinite(m[1][0]) && isFinite(m[1][1]) && isFinite(m[2][0]) && isFinite(m[2][1]); } function setM(ctx, m, updateLineScale) { if (!matrixIsFinite(m)) { return; } ctx.m_ = m; if (updateLineScale) { // Get the line scale. // Determinant of this.m_ means how much the area is enlarged by the // transformation. So its square root can be used as a scale factor // for width. var det = m[0][0] * m[1][1] - m[0][1] * m[1][0]; ctx.lineScale_ = sqrt(abs(det)); } } contextPrototype.translate = function(aX, aY) { var m1 = [ [1, 0, 0], [0, 1, 0], [aX, aY, 1] ]; setM(this, matrixMultiply(m1, this.m_), false); }; contextPrototype.rotate = function(aRot) { var c = mc(aRot); var s = ms(aRot); var m1 = [ [c, s, 0], [-s, c, 0], [0, 0, 1] ]; setM(this, matrixMultiply(m1, this.m_), false); }; contextPrototype.scale = function(aX, aY) { this.arcScaleX_ *= aX; this.arcScaleY_ *= aY; var m1 = [ [aX, 0, 0], [0, aY, 0], [0, 0, 1] ]; setM(this, matrixMultiply(m1, this.m_), true); }; contextPrototype.transform = function(m11, m12, m21, m22, dx, dy) { var m1 = [ [m11, m12, 0], [m21, m22, 0], [dx, dy, 1] ]; setM(this, matrixMultiply(m1, this.m_), true); }; contextPrototype.setTransform = function(m11, m12, m21, m22, dx, dy) { var m = [ [m11, m12, 0], [m21, m22, 0], [dx, dy, 1] ]; setM(this, m, true); }; /** * The text drawing function. * The maxWidth argument isn't taken in account, since no browser supports * it yet. */ contextPrototype.drawText_ = function(text, x, y, maxWidth, stroke) { var m = this.m_, delta = 1000, left = 0, right = delta, offset = {x: 0, y: 0}, lineStr = []; var fontStyle = getComputedStyle(processFontStyle(this.font), this.element_); var fontStyleString = buildStyle(fontStyle); var elementStyle = this.element_.currentStyle; var textAlign = this.textAlign.toLowerCase(); switch (textAlign) { case 'left': case 'center': case 'right': break; case 'end': textAlign = elementStyle.direction == 'ltr' ? 'right' : 'left'; break; case 'start': textAlign = elementStyle.direction == 'rtl' ? 'right' : 'left'; break; default: textAlign = 'left'; } // 1.75 is an arbitrary number, as there is no info about the text baseline switch (this.textBaseline) { case 'hanging': case 'top': offset.y = fontStyle.size / 1.75; break; case 'middle': break; default: case null: case 'alphabetic': case 'ideographic': case 'bottom': offset.y = -fontStyle.size / 2.25; break; } switch(textAlign) { case 'right': left = delta; right = 0.05; break; case 'center': left = right = delta / 2; break; } var d = getCoords(this, x + offset.x, y + offset.y); lineStr.push('<g_vml_:line from="', -left ,' 0" to="', right ,' 0.05" ', ' coordsize="100 100" coordorigin="0 0"', ' filled="', !stroke, '" stroked="', !!stroke, '" style="position:absolute;width:1px;height:1px;">'); if (stroke) { appendStroke(this, lineStr); } else { // TODO: Fix the min and max params. appendFill(this, lineStr, {x: -left, y: 0}, {x: right, y: fontStyle.size}); } var skewM = m[0][0].toFixed(3) + ',' + m[1][0].toFixed(3) + ',' + m[0][1].toFixed(3) + ',' + m[1][1].toFixed(3) + ',0,0'; var skewOffset = mr(d.x / Z) + ',' + mr(d.y / Z); lineStr.push('<g_vml_:skew on="t" matrix="', skewM ,'" ', ' offset="', skewOffset, '" origin="', left ,' 0" />', '<g_vml_:path textpathok="true" />', '<g_vml_:textpath on="true" string="', encodeHtmlAttribute(text), '" style="v-text-align:', textAlign, ';font:', encodeHtmlAttribute(fontStyleString), '" /></g_vml_:line>'); this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); }; contextPrototype.fillText = function(text, x, y, maxWidth) { this.drawText_(text, x, y, maxWidth, false); }; contextPrototype.strokeText = function(text, x, y, maxWidth) { this.drawText_(text, x, y, maxWidth, true); }; contextPrototype.measureText = function(text) { if (!this.textMeasureEl_) { var s = '<span style="position:absolute;' + 'top:-20000px;left:0;padding:0;margin:0;border:none;' + 'white-space:pre;"></span>'; this.element_.insertAdjacentHTML('beforeEnd', s); this.textMeasureEl_ = this.element_.lastChild; } var doc = this.element_.ownerDocument; this.textMeasureEl_.innerHTML = ''; this.textMeasureEl_.style.font = this.font; // Don't use innerHTML or innerText because they allow markup/whitespace. this.textMeasureEl_.appendChild(doc.createTextNode(text)); return {width: this.textMeasureEl_.offsetWidth}; }; /******** STUBS ********/ contextPrototype.clip = function() { // TODO: Implement }; contextPrototype.arcTo = function() { // TODO: Implement }; contextPrototype.createPattern = function(image, repetition) { return new CanvasPattern_(image, repetition); }; // Gradient / Pattern Stubs function CanvasGradient_(aType) { this.type_ = aType; this.x0_ = 0; this.y0_ = 0; this.r0_ = 0; this.x1_ = 0; this.y1_ = 0; this.r1_ = 0; this.colors_ = []; } CanvasGradient_.prototype.addColorStop = function(aOffset, aColor) { aColor = processStyle(aColor); this.colors_.push({offset: aOffset, color: aColor.color, alpha: aColor.alpha}); }; function CanvasPattern_(image, repetition) { assertImageIsValid(image); switch (repetition) { case 'repeat': case null: case '': this.repetition_ = 'repeat'; break case 'repeat-x': case 'repeat-y': case 'no-repeat': this.repetition_ = repetition; break; default: throwException('SYNTAX_ERR'); } this.src_ = image.src; this.width_ = image.width; this.height_ = image.height; } function throwException(s) { throw new DOMException_(s); } function assertImageIsValid(img) { if (!img || img.nodeType != 1 || img.tagName != 'IMG') { throwException('TYPE_MISMATCH_ERR'); } if (img.readyState != 'complete') { throwException('INVALID_STATE_ERR'); } } function DOMException_(s) { this.code = this[s]; this.message = s +': DOM Exception ' + this.code; } var p = DOMException_.prototype = new Error; p.INDEX_SIZE_ERR = 1; p.DOMSTRING_SIZE_ERR = 2; p.HIERARCHY_REQUEST_ERR = 3; p.WRONG_DOCUMENT_ERR = 4; p.INVALID_CHARACTER_ERR = 5; p.NO_DATA_ALLOWED_ERR = 6; p.NO_MODIFICATION_ALLOWED_ERR = 7; p.NOT_FOUND_ERR = 8; p.NOT_SUPPORTED_ERR = 9; p.INUSE_ATTRIBUTE_ERR = 10; p.INVALID_STATE_ERR = 11; p.SYNTAX_ERR = 12; p.INVALID_MODIFICATION_ERR = 13; p.NAMESPACE_ERR = 14; p.INVALID_ACCESS_ERR = 15; p.VALIDATION_ERR = 16; p.TYPE_MISMATCH_ERR = 17; // set up externs G_vmlCanvasManager = G_vmlCanvasManager_; CanvasRenderingContext2D = CanvasRenderingContext2D_; CanvasGradient = CanvasGradient_; CanvasPattern = CanvasPattern_; DOMException = DOMException_; })(); } // if
JavaScript
/*! Copyright (c) 2010 Brandon Aaron (http://brandonaaron.net) * Licensed under the MIT License (LICENSE.txt). * * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers. * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix. * Thanks to: Seamus Leahy for adding deltaX and deltaY * * Version: 3.0.4 * * Requires: 1.2.2+ */ (function($) { var types = ['DOMMouseScroll', 'mousewheel']; $.event.special.mousewheel = { setup: function() { if ( this.addEventListener ) { for ( var i=types.length; i; ) { this.addEventListener( types[--i], handler, false ); } } else { this.onmousewheel = handler; } }, teardown: function() { if ( this.removeEventListener ) { for ( var i=types.length; i; ) { this.removeEventListener( types[--i], handler, false ); } } else { this.onmousewheel = null; } } }; $.fn.extend({ mousewheel: function(fn) { return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel"); }, unmousewheel: function(fn) { return this.unbind("mousewheel", fn); } }); function handler(event) { var orgEvent = event || window.event, args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true, deltaX = 0, deltaY = 0; event = $.event.fix(orgEvent); event.type = "mousewheel"; // Old school scrollwheel delta if ( event.wheelDelta ) { delta = event.wheelDelta/120; } if ( event.detail ) { delta = -event.detail/3; } // New school multidimensional scroll (touchpads) deltas deltaY = delta; // Gecko if ( orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) { deltaY = 0; deltaX = -1*delta; } // Webkit if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY/120; } if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = -1*orgEvent.wheelDeltaX/120; } // Add event and delta to the front of the arguments args.unshift(event, delta, deltaX, deltaY); return $.event.handle.apply(this, args); } })(jQuery);
JavaScript
/** * Copyright (C) 2010-2013 Graham Breach * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * TagCanvas 2.1.2 * For more information, please contact <graham@goat1000.com> */ (function(){ "use strict"; var i, j, abs = Math.abs, sin = Math.sin, cos = Math.cos, max = Math.max, min = Math.min, ceil = Math.ceil, hexlookup3 = {}, hexlookup2 = {}, hexlookup1 = { 0:"0,", 1:"17,", 2:"34,", 3:"51,", 4:"68,", 5:"85,", 6:"102,", 7:"119,", 8:"136,", 9:"153,", a:"170,", A:"170,", b:"187,", B:"187,", c:"204,", C:"204,", d:"221,", D:"221,", e:"238,", E:"238,", f:"255,", F:"255," }, Oproto, Tproto, TCproto, doc = document, ocanvas, handlers = {}; for(i = 0; i < 256; ++i) { j = i.toString(16); if(i < 16) j = '0' + j; hexlookup2[j] = hexlookup2[j.toUpperCase()] = i.toString() + ','; } function Defined(d) { return typeof(d) != 'undefined'; } function Clamp(v, mn, mx) { return isNaN(v) ? mx : min(mx, max(mn, v)); } function Nop() { return false; } function SortList(l, f) { var nl = [], tl = l.length, i; for(i = 0; i < tl; ++i) nl.push(l[i]); nl.sort(f); return nl; } function Shuffle(a) { var i = a.length-1, t, p; while(i) { p = ~~(Math.random()*i); t = a[i]; a[i] = a[p]; a[p] = t; --i; } } function Matrix(a) { this[1] = {1: a[0], 2: a[1], 3: a[2], 4: a[3]}; this[2] = {1: a[4], 2: a[5], 3: a[6], 4: a[7]}; this[3] = {1: a[8], 2: a[9], 3: a[10], 4: a[11]}; this[4] = {1: a[12], 2: a[13], 3: a[14], 4: a[15]}; } Matrix.Identity = function() { return new Matrix([1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1]); } Matrix.prototype.mul = function(m) { var a = [], i, j; for(i = 1; i <= 4; ++i) for(j = 1; j <= 4; ++j) a.push(this[i][1] * m[1][j] + this[i][2] * m[2][j] + this[i][3] * m[3][j] + this[i][4] * m[4][j]); return new Matrix(a); } Matrix.prototype.xform = function(p) { var a = {}, x = p.x, y = p.y, z = p.z, w = Defined(p.w) ? p.w : 1; a.x = x * this[1][1] + y * this[2][1] + z * this[3][1] + w * this[4][1]; a.y = x * this[1][2] + y * this[2][2] + z * this[3][2] + w * this[4][2]; a.z = x * this[1][3] + y * this[2][3] + z * this[3][3] + w * this[4][3]; a.w = x * this[1][4] + y * this[2][4] + z * this[3][4] + w * this[4][4]; return a; } function PointsOnSphere(n,xr,yr,zr) { var i, y, r, phi, pts = [], inc = Math.PI * (3-Math.sqrt(5)), off = 2/n; for(i = 0; i < n; ++i) { y = i * off - 1 + (off / 2); r = Math.sqrt(1 - y*y); phi = i * inc; pts.push([cos(phi) * r * xr, y * yr, sin(phi) * r * zr]); } return pts; } function Cylinder(n,o,xr,yr,zr) { var phi, pts = [], inc = Math.PI * (3-Math.sqrt(5)), off = 2/n, i, j, k, l; for(i = 0; i < n; ++i) { j = i * off - 1 + (off / 2); phi = i * inc; k = cos(phi); l = sin(phi); pts.push(o ? [j * xr, k * yr, l * zr] : [k * xr, j * yr, l * zr]); } return pts; } function Ring(o, n, xr, yr, zr, j) { var phi, pts = [], inc = Math.PI * 2 / n, i, k, l; for(i = 0; i < n; ++i) { phi = i * inc; k = cos(phi); l = sin(phi); pts.push(o ? [j * xr, k * yr, l * zr] : [k * xr, j * yr, l * zr]); } return pts; } function PointsOnCylinderV(n,xr,yr,zr) { return Cylinder(n, 0, xr, yr, zr) } function PointsOnCylinderH(n,xr,yr,zr) { return Cylinder(n, 1, xr, yr, zr) } function PointsOnRingV(n, xr, yr, zr, offset) { offset = isNaN(offset) ? 0 : offset * 1; return Ring(0, n, xr, yr, zr, offset); } function PointsOnRingH(n, xr, yr, zr, offset) { offset = isNaN(offset) ? 0 : offset * 1; return Ring(1, n, xr, yr, zr, offset); } function SetAlpha(c,a) { var d = c, p1, p2, ae = (a*1).toPrecision(3) + ')'; if(c[0] === '#') { if(!hexlookup3[c]) if(c.length === 4) hexlookup3[c] = 'rgba(' + hexlookup1[c[1]] + hexlookup1[c[2]] + hexlookup1[c[3]]; else hexlookup3[c] = 'rgba(' + hexlookup2[c.substr(1,2)] + hexlookup2[c.substr(3,2)] + hexlookup2[c.substr(5,2)]; d = hexlookup3[c] + ae; } else if(c.substr(0,4) === 'rgb(' || c.substr(0,4) === 'hsl(') { d = (c.replace('(','a(').replace(')', ',' + ae)); } else if(c.substr(0,5) === 'rgba(' || c.substr(0,5) === 'hsla(') { p1 = c.lastIndexOf(',') + 1, p2 = c.indexOf(')'); a *= parseFloat(c.substring(p1,p2)); d = c.substr(0,p1) + a.toPrecision(3) + ')'; } return d; } function NewCanvas(w,h) { // if using excanvas, give up now if(window.G_vmlCanvasManager) return null; var c = doc.createElement('canvas'); c.width = w; c.height = h; return c; } // I think all browsers pass this test now... function ShadowAlphaBroken() { var cv = NewCanvas(3,3), c, i; if(!cv) return false; c = cv.getContext('2d'); c.strokeStyle = '#000'; c.shadowColor = '#fff'; c.shadowBlur = 3; c.globalAlpha = 0; c.strokeRect(2,2,2,2); c.globalAlpha = 1; i = c.getImageData(2,2,1,1); cv = null; return (i.data[0] > 0); } function FindGradientColour(t,p) { var l = 1024, g = t.weightGradient, cv, c, i, gd, d; if(t.gCanvas) { c = t.gCanvas.getContext('2d'); } else { t.gCanvas = cv = NewCanvas(l,1); if(!cv) return null; c = cv.getContext('2d'); gd = c.createLinearGradient(0,0,l,0); for(i in g) gd.addColorStop(1-i, g[i]); c.fillStyle = gd; c.fillRect(0,0,l,1); } d = c.getImageData(~~((l-1)*p),0,1,1).data; return 'rgba(' + d[0] + ',' + d[1] + ',' + d[2] + ',' + (d[3]/255) + ')'; } function TextSet(c,f,l,s,sc,sb,so,wm,wl) { var xo = (sb || 0) + (so && so[0] < 0 ? abs(so[0]) : 0), yo = (sb || 0) + (so && so[1] < 0 ? abs(so[1]) : 0), i, xc; c.font = f; c.textBaseline = 'top'; c.fillStyle = l; sc && (c.shadowColor = sc); sb && (c.shadowBlur = sb); so && (c.shadowOffsetX = so[0], c.shadowOffsetY = so[1]); for(i = 0; i < s.length; ++i) { xc = wl ? (wm - wl[i]) / 2 : 0; c.fillText(s[i], xo + xc, yo); yo += parseInt(f); } } function TextToCanvas(s,f,ht,w,h,l,sc,sb,so,padx,pady,wmax,wlist) { var cw = w + abs(so[0]) + sb + sb, ch = h + abs(so[1]) + sb + sb, cv, c; cv = NewCanvas(cw+padx,ch+pady); if(!cv) return null; c = cv.getContext('2d'); TextSet(c,f,l,s,sc,sb,so,wmax,wlist); return cv; } function AddShadowToImage(i,sc,sb,so) { var sw = abs(so[0]), sh = abs(so[1]), cw = i.width + (sw > sb ? sw + sb : sb * 2), ch = i.height + (sh > sb ? sh + sb : sb * 2), xo = (sb || 0) + (so[0] < 0 ? sw : 0), yo = (sb || 0) + (so[1] < 0 ? sh : 0), cv, c; cv = NewCanvas(cw, ch); if(!cv) return null; c = cv.getContext('2d'); sc && (c.shadowColor = sc); sb && (c.shadowBlur = sb); so && (c.shadowOffsetX = so[0], c.shadowOffsetY = so[1]); c.drawImage(i, xo, yo, i.width, i.height); return cv; } function FindTextBoundingBox(s,f,ht) { var w = parseInt(s.toString().length * ht), h = parseInt(ht * 2 * s.length), cv = NewCanvas(w,h), c, idata, w1, h1, x, y, i, ex; if(!cv) return null; c = cv.getContext('2d'); c.fillStyle = '#000'; c.fillRect(0,0,w,h); TextSet(c,ht + 'px ' + f,'#fff',s,0,0,[]) idata = c.getImageData(0,0,w,h); w1 = idata.width; h1 = idata.height; ex = { min: { x: w1, y: h1 }, max: { x: -1, y: -1 } }; for(y = 0; y < h1; ++y) { for(x = 0; x < w1; ++x) { i = (y * w1 + x) * 4; if(idata.data[i+1] > 0) { if(x < ex.min.x) ex.min.x = x; if(x > ex.max.x) ex.max.x = x; if(y < ex.min.y) ex.min.y = y; if(y > ex.max.y) ex.max.y = y; } } } // device pixels might not be css pixels if(w1 != w) { ex.min.x *= (w / w1); ex.max.x *= (w / w1); } if(h1 != h) { ex.min.y *= (w / h1); ex.max.y *= (w / h1); } cv = null; return ex; } function FixFont(f) { return "'" + f.replace(/(\'|\")/g,'').replace(/\s*,\s*/g, "', '") + "'"; } function AddHandler(h,f,e) { e = e || doc; if(e.addEventListener) e.addEventListener(h,f,false); else e.attachEvent('on' + h, f); } function AddImage(i, o, t, tc) { var s = tc.imageScale, ic; // image not loaded, wait for image onload if(!o.complete) return AddHandler('load',function() { AddImage(i,o,t,tc); }, o); if(!i.complete) return AddHandler('load',function() { AddImage(i,o,t,tc); }, i); // Yes, this does look like nonsense, but it makes sure that both the // width and height are actually set and not just calculated. This is // required to keep proportional sizes when the images are hidden, so // the images can be used again for another cloud. o.width = o.width; o.height = o.height; if(s) { i.width = o.width * s; i.height = o.height * s; } t.w = i.width; t.h = i.height; if(tc.txtOpt && tc.shadow) { ic = AddShadowToImage(i, tc.shadow, tc.shadowBlur, tc.shadowOffset); if(ic) { t.image = ic; t.w = ic.width; t.h = ic.height; } } } function GetProperty(e,p) { var dv = doc.defaultView, pc = p.replace(/\-([a-z])/g,function(a){return a.charAt(1).toUpperCase()}); return (dv && dv.getComputedStyle && dv.getComputedStyle(e,null).getPropertyValue(p)) || (e.currentStyle && e.currentStyle[pc]); } function FindWeight(t,a) { var w = 1, p; if(t.weightFrom) { w = 1 * (a.getAttribute(t.weightFrom) || t.textHeight); } else if(p = GetProperty(a,'font-size')) { w = (p.indexOf('px') > -1 && p.replace('px','') * 1) || (p.indexOf('pt') > -1 && p.replace('pt','') * 1.25) || p * 3.3; } else { t.weight = false; } return w; } function EventToCanvasId(e) { return e.target && Defined(e.target.id) ? e.target.id : e.srcElement.parentNode.id; } function EventXY(e, c) { var xy, p, xmul = parseInt(GetProperty(c, 'width')) / c.width, ymul = parseInt(GetProperty(c, 'height')) / c.height; if(Defined(e.offsetX)) { xy = {x: e.offsetX, y: e.offsetY}; } else { p = AbsPos(c.id); if(Defined(e.changedTouches)) e = e.changedTouches[0]; if(e.pageX) xy = {x: e.pageX - p.x, y: e.pageY - p.y}; } if(xy && xmul && ymul) { xy.x /= xmul; xy.y /= ymul; } return xy; } function MouseOut(e) { var cv = e.target || e.fromElement.parentNode, tc = TagCanvas.tc[cv.id]; if(tc) { tc.mx = tc.my = -1; tc.UnFreeze(); tc.EndDrag(); } } function MouseMove(e) { var i, t = TagCanvas, tc, p, tg = EventToCanvasId(e); for(i in t.tc) { tc = t.tc[i]; if(tc.tttimer) { clearTimeout(tc.tttimer); tc.tttimer = null; } } if(tg && t.tc[tg]) { tc = t.tc[tg]; if(p = EventXY(e, tc.canvas)) { tc.mx = p.x; tc.my = p.y; tc.Drag(e, p); } tc.drawn = 0; } } function MouseDown(e) { var t = TagCanvas, cb = doc.addEventListener ? 0 : 1, tg = EventToCanvasId(e); if(tg && e.button == cb && t.tc[tg]) { t.tc[tg].BeginDrag(e); } } function MouseUp(e) { var t = TagCanvas, cb = doc.addEventListener ? 0 : 1, tg = EventToCanvasId(e), tc; if(tg && e.button == cb && t.tc[tg]) { tc = t.tc[tg]; MouseMove(e); if(!tc.EndDrag() && !tc.touched) tc.Clicked(e); } } function TouchDown(e) { var t = TagCanvas, tg = EventToCanvasId(e); if(tg && e.changedTouches && t.tc[tg]) { t.tc[tg].touched = 1; t.tc[tg].BeginDrag(e); } } function TouchUp(e) { var t = TagCanvas, tg = EventToCanvasId(e); if(tg && e.changedTouches && t.tc[tg]) { TouchMove(e); if(!t.tc[tg].EndDrag()){ t.tc[tg].Draw(); t.tc[tg].Clicked(e); } } } function TouchMove(e) { var i, t = TagCanvas, tc, p, tg = EventToCanvasId(e); for(i in t.tc) { tc = t.tc[i]; if(tc.tttimer) { clearTimeout(tc.tttimer); tc.tttimer = null; } } if(tg && t.tc[tg] && e.changedTouches) { tc = t.tc[tg]; if(p = EventXY(e, tc.canvas)) { tc.mx = p.x; tc.my = p.y; tc.Drag(e, p); } tc.drawn = 0; } } function MouseWheel(e) { var t = TagCanvas, tg = EventToCanvasId(e); if(tg && t.tc[tg]) { e.cancelBubble = true; e.returnValue = false; e.preventDefault && e.preventDefault(); t.tc[tg].Wheel((e.wheelDelta || e.detail) > 0); } } function DrawCanvas(t) { var tc = TagCanvas.tc, i, interval; t = t || new Date().valueOf(); for(i in tc) { interval = tc[i].interval; tc[i].Draw(t); } TagCanvas.NextFrame(interval); } function AbsPos(id) { var e = doc.getElementById(id), r = e.getBoundingClientRect(), dd = doc.documentElement, b = doc.body, w = window, xs = w.pageXOffset || dd.scrollLeft, ys = w.pageYOffset || dd.scrollTop, xo = dd.clientLeft || b.clientLeft, yo = dd.clientTop || b.clientTop; return { x: r.left + xs - xo, y: r.top + ys - yo }; } function Project(tc,p1,sx,sy) { var m = tc.radius * tc.z1 / (tc.z1 + tc.z2 + p1.z); return { x: p1.x * m * sx, y: p1.y * m * sy, z: p1.z, w: (tc.z1 - p1.z) / tc.z2 }; } /** * @constructor * for recursively splitting tag contents on <br> tags */ function TextSplitter(e) { this.e = e; this.br = 0; this.line = []; this.text = []; this.original = e.innerText || e.textContent; }; TextSplitter.prototype.Lines = function(e) { var r = e ? 1 : 0, cn, cl, i; e = e || this.e; cn = e.childNodes; cl = cn.length; for(i = 0; i < cl; ++i) { if(cn[i].nodeName == 'BR') { this.text.push(this.line.join(' ')); this.br = 1; } else if(cn[i].nodeType == 3) { if(this.br) { this.line = [cn[i].nodeValue]; this.br = 0; } else { this.line.push(cn[i].nodeValue); } } else { this.Lines(cn[i]); } } r || this.br || this.text.push(this.line.join(' ')); return this.text; } TextSplitter.prototype.SplitWidth = function(w, c, f, h) { var i, j, words, text = []; c.font = h + 'px ' + f; for(i = 0; i < this.text.length; ++i) { words = this.text[i].split(/\s+/); this.line = [words[0]]; for(j = 1; j < words.length; ++j) { if(c.measureText(this.line.join(' ') + ' ' + words[j]).width > w) { text.push(this.line.join(' ')); this.line = [words[j]]; } else { this.line.push(words[j]); } } text.push(this.line.join(' ')); } return this.text = text; } /** * @constructor */ function Outline(tc) { this.ts = new Date().valueOf(); this.tc = tc; this.x = this.y = this.w = this.h = this.sc = 1; this.z = 0; this.Draw = tc.pulsateTo < 1 && tc.outlineMethod != 'colour' ? this.DrawPulsate : this.DrawSimple; this.SetMethod(tc.outlineMethod); } Oproto = Outline.prototype; Oproto.SetMethod = function(om) { var methods = { block: ['PreDraw','DrawBlock'], colour: ['PreDraw','DrawColour'], outline: ['PostDraw','DrawOutline'], classic: ['LastDraw','DrawOutline'], none: ['LastDraw'] }, funcs = methods[om] || methods.outline; if(om == 'none') { this.Draw = function() { return 1; } } else { this.drawFunc = this[funcs[1]]; } this[funcs[0]] = this.Draw; }; Oproto.Update = function(x,y,w,h,sc,z,xo,yo) { var o = this.tc.outlineOffset, o2 = 2 * o; this.x = sc * x + xo - o; this.y = sc * y + yo - o; this.w = sc * w + o2; this.h = sc * h + o2; this.sc = sc; // used to determine frontmost this.z = z; }; Oproto.DrawOutline = function(c,x,y,w,h,colour) { c.strokeStyle = colour; c.strokeRect(x,y,w,h); }; Oproto.DrawColour = function(c,x,y,w,h,colour,tag,x1,y1) { return this[tag.image ? 'DrawColourImage' : 'DrawColourText'](c,x,y,w,h,colour,tag,x1,y1); }; Oproto.DrawColourText = function(c,x,y,w,h,colour,tag,x1,y1) { var normal = tag.colour; tag.colour = colour; tag.alpha = 1; tag.Draw(c,x1,y1); tag.colour = normal; return 1; }; Oproto.DrawColourImage = function(c,x,y,w,h,colour,tag,x1,y1) { var ccanvas = c.canvas, fx = ~~max(x,0), fy = ~~max(y,0), fw = min(ccanvas.width - fx, w) + .5|0, fh = min(ccanvas.height - fy,h) + .5|0, cc; if(ocanvas) ocanvas.width = fw, ocanvas.height = fh; else ocanvas = NewCanvas(fw, fh); if(!ocanvas) return this.SetMethod('outline'); // if using IE and images, give up! cc = ocanvas.getContext('2d'); cc.drawImage(ccanvas,fx,fy,fw,fh,0,0,fw,fh); c.clearRect(fx,fy,fw,fh); tag.alpha = 1; tag.Draw(c,x1,y1); c.setTransform(1,0,0,1,0,0); c.save(); c.beginPath(); c.rect(fx,fy,fw,fh); c.clip(); c.globalCompositeOperation = 'source-in'; c.fillStyle = colour; c.fillRect(fx,fy,fw,fh); c.restore(); c.globalCompositeOperation = 'destination-over'; c.drawImage(ocanvas,0,0,fw,fh,fx,fy,fw,fh); c.globalCompositeOperation = 'source-over'; return 1; }; Oproto.DrawBlock = function(c,x,y,w,h,colour) { c.fillStyle = colour; c.fillRect(x,y,w,h); }; Oproto.DrawSimple = function(c, tag, x1, y1) { var t = this.tc; c.setTransform(1,0,0,1,0,0); c.strokeStyle = t.outlineColour; c.lineWidth = t.outlineThickness; c.shadowBlur = c.shadowOffsetX = c.shadowOffsetY = 0; c.globalAlpha = 1; return this.drawFunc(c,this.x,this.y,this.w,this.h,t.outlineColour,tag,x1,y1); }; Oproto.DrawPulsate = function(c, tag, x1, y1) { var diff = new Date().valueOf() - this.ts, t = this.tc; c.setTransform(1,0,0,1,0,0); c.strokeStyle = t.outlineColour; c.lineWidth = t.outlineThickness; c.shadowBlur = c.shadowOffsetX = c.shadowOffsetY = 0; c.globalAlpha = t.pulsateTo + ((1 - t.pulsateTo) * (0.5 + (cos(2 * Math.PI * diff / (1000 * t.pulsateTime)) / 2))); return this.drawFunc(c,this.x,this.y,this.w,this.h,t.outlineColour,tag,x1,y1); }; Oproto.Active = function(c,x,y) { return (x >= this.x && y >= this.y && x <= this.x + this.w && y <= this.y + this.h); }; Oproto.PreDraw = Oproto.PostDraw = Oproto.LastDraw = Nop; /** * @constructor */ function Tag(tc,text,a,v,w,h,col,font,original) { var c = tc.ctxt; this.tc = tc; this.image = text.src ? text : null; this.text = text.src ? [] : text; this.text_original = original; this.line_widths = []; this.title = a.title || null; this.a = a; this.position = { x: v[0], y: v[1], z: v[2] }; this.x = this.y = this.z = 0; this.w = w; this.h = h; this.colour = col || tc.textColour; this.textFont = font || tc.textFont; this.weight = this.sc = this.alpha = 1; this.weighted = !tc.weight; this.outline = new Outline(tc); if(!this.image) { this.textHeight = tc.textHeight; this.extents = FindTextBoundingBox(this.text, this.textFont, this.textHeight); this.Measure(c,tc); } this.SetShadowColour = tc.shadowAlpha ? this.SetShadowColourAlpha : this.SetShadowColourFixed; this.SetDraw(tc); } Tproto = Tag.prototype; Tproto.EqualTo = function(e) { var i = e.getElementsByTagName('img'); if(this.a.href != e.href) return 0; if(i.length) return this.image.src == i[0].src; return (e.innerText || e.textContent) == this.text_original; }; Tproto.SetDraw = function(t) { this.Draw = this.image ? (t.ie > 7 ? this.DrawImageIE : this.DrawImage) : this.DrawText; t.noSelect && (this.CheckActive = Nop); }; Tproto.MeasureText = function(c) { var i, l = this.text.length, w = 0, wl; for(i = 0; i < l; ++i) { this.line_widths[i] = wl = c.measureText(this.text[i]).width; w = max(w, wl); } return w; }; Tproto.Measure = function(c,t) { this.h = this.extents ? this.extents.max.y + this.extents.min.y : this.textHeight; c.font = this.font = this.textHeight + 'px ' + this.textFont; this.w = this.MeasureText(c); if(t.txtOpt) { var s = t.txtScale, th = s * this.textHeight, f = th + 'px ' + this.textFont, soff = [s*t.shadowOffset[0],s*t.shadowOffset[1]], cw; c.font = f; cw = this.MeasureText(c); this.image = TextToCanvas(this.text, f, th, cw, s * this.h, this.colour, t.shadow, s * t.shadowBlur, soff, s, s, cw, this.line_widths); if(this.image) { this.w = this.image.width / s; this.h = this.image.height / s; } this.SetDraw(t); t.txtOpt = !!this.image; } }; Tproto.SetFont = function(f, c) { this.textFont = f; this.colour = c; this.extents = FindTextBoundingBox(this.text, this.textFont, this.textHeight); this.Measure(this.tc.ctxt, this.tc); }; Tproto.SetWeight = function(w) { if(!this.text.length) return; this.weight = w; this.Weight(this.tc.ctxt, this.tc); this.Measure(this.tc.ctxt, this.tc); }; Tproto.Weight = function(c,t) { var w = this.weight, m = t.weightMode; this.weighted = true; if(m == 'colour' || m == 'both') this.colour = FindGradientColour(t, (w - t.min_weight) / (t.max_weight-t.min_weight)); if(m == 'size' || m == 'both') { if(t.weightSizeMin > 0 && t.weightSizeMax > t.weightSizeMin) { this.textHeight = t.weightSize * (t.weightSizeMin + (t.weightSizeMax - t.weightSizeMin) * (w - t.min_weight) / (t.max_weight - t.min_weight)); } else { this.textHeight = w * t.weightSize; } } this.extents = FindTextBoundingBox(this.text, this.textFont, this.textHeight); }; Tproto.SetShadowColourFixed = function(c,s,a) { c.shadowColor = s; }; Tproto.SetShadowColourAlpha = function(c,s,a) { c.shadowColor = SetAlpha(s, a); }; Tproto.DrawText = function(c,xoff,yoff) { var t = this.tc, x = this.x, y = this.y, s = this.sc, i, xl; c.globalAlpha = this.alpha; c.fillStyle = this.colour; t.shadow && this.SetShadowColour(c,t.shadow,this.alpha); c.font = this.font; x += xoff / s; y += (yoff / s) - (this.h / 2); for(i = 0; i < this.text.length; ++i) { xl = x - (this.line_widths[i] / 2); c.setTransform(s, 0, 0, s, s * xl, s * y); c.fillText(this.text[i], 0, 0); y += this.textHeight; } }; Tproto.DrawImage = function(c,xoff,yoff) { var x = this.x, y = this.y, s = this.sc, i = this.image, w = this.w, h = this.h, a = this.alpha, shadow = this.shadow; c.globalAlpha = a; shadow && this.SetShadowColour(c,shadow,a); x += (xoff / s) - (w / 2); y += (yoff / s) - (h / 2); c.setTransform(s, 0, 0, s, s * x, s * y); c.drawImage(i, 0, 0, w, h); }; Tproto.DrawImageIE = function(c,xoff,yoff) { var i = this.image, s = this.sc, w = i.width = this.w*s, h = i.height = this.h * s, x = (this.x*s) + xoff - (w/2), y = (this.y*s) + yoff - (h/2); c.setTransform(1,0,0,1,0,0); c.globalAlpha = this.alpha; c.drawImage(i, x, y); }; Tproto.Calc = function(m) { var pp, t = this.tc, mnb = t.minBrightness, mxb = t.maxBrightness, r = t.max_radius; pp = m.xform(this.position); pp = Project(t, pp, t.stretchX, t.stretchY); this.x = pp.x; this.y = pp.y; this.z = pp.z; this.sc = pp.w; this.alpha = Clamp(mnb + (mxb - mnb) * (r - this.z) / (2 * r), 0, 1); }; Tproto.CheckActive = function(c,xoff,yoff) { var t = this.tc, o = this.outline, w = this.w, h = this.h, x = this.x - w/2, y = this.y - h/2; o.Update(x, y, w, h, this.sc, this.z, xoff, yoff); return o.Active(c, t.mx, t.my) ? o : null; }; Tproto.Clicked = function(e) { var a = this.a, t = a.target, h = a.href, evt; if(t != '' && t != '_self') { if(self.frames[t]) { self.frames[t].document.location = h; } else{ try { if(top.frames[t]) { top.frames[t].document.location = h; return; } } catch(err) { // different domain/port/protocol? } window.open(h, t); } return; } if(doc.createEvent) { evt = doc.createEvent('MouseEvents'); evt.initMouseEvent('click', 1, 1, window, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, null); if(!a.dispatchEvent(evt)) return; } else if(a.fireEvent) { if(!a.fireEvent('onclick')) return; } doc.location = h; }; /** * @constructor */ function TagCanvas(cid,lctr,opt) { var i, p, c = doc.getElementById(cid), cp = ['id','class','innerHTML']; if(!c) throw 0; if(Defined(window.G_vmlCanvasManager)) { c = window.G_vmlCanvasManager.initElement(c); this.ie = parseFloat(navigator.appVersion.split('MSIE')[1]); } if(c && (!c.getContext || !c.getContext('2d').fillText)) { p = doc.createElement('DIV'); for(i = 0; i < cp.length; ++i) p[cp[i]] = c[cp[i]]; c.parentNode.insertBefore(p,c); c.parentNode.removeChild(c); throw 0; } for(i in TagCanvas.options) this[i] = opt && Defined(opt[i]) ? opt[i] : (Defined(TagCanvas[i]) ? TagCanvas[i] : TagCanvas.options[i]); this.canvas = c; this.ctxt = c.getContext('2d'); this.z1 = 250 / this.depth; this.z2 = this.z1 / this.zoom; this.radius = min(c.height, c.width) * 0.0075; // fits radius of 100 in canvas this.max_weight = 0; this.min_weight = 200; this.textFont = this.textFont && FixFont(this.textFont); this.textHeight *= 1; this.pulsateTo = Clamp(this.pulsateTo, 0, 1); this.minBrightness = Clamp(this.minBrightness, 0, 1); this.maxBrightness = Clamp(this.maxBrightness, this.minBrightness, 1); this.ctxt.textBaseline = 'top'; this.lx = (this.lock + '').indexOf('x') + 1; this.ly = (this.lock + '').indexOf('y') + 1; this.frozen = 0; this.dx = this.dy = 0; this.touched = 0; this.source = lctr || cid; this.transform = Matrix.Identity(); this.time = new Date().valueOf(); this.Animate = this.dragControl ? this.AnimateDrag : this.AnimatePosition; if(this.shadowBlur || this.shadowOffset[0] || this.shadowOffset[1]) { // let the browser translate "red" into "#ff0000" this.ctxt.shadowColor = this.shadow; this.shadow = this.ctxt.shadowColor; this.shadowAlpha = ShadowAlphaBroken(); } else { delete this.shadow; } this.Load(); if(lctr && this.hideTags) { (function(t) { if(TagCanvas.loaded) t.HideTags(); else AddHandler('load', function() { t.HideTags(); }, window); })(this); } this.yaw = this.initial ? this.initial[0] * this.maxSpeed : 0; this.pitch = this.initial ? this.initial[1] * this.maxSpeed : 0; if(this.tooltip) { if(this.tooltip == 'native') { this.Tooltip = this.TooltipNative; } else { this.Tooltip = this.TooltipDiv; if(!this.ttdiv) { this.ttdiv = doc.createElement('div'); this.ttdiv.className = this.tooltipClass; this.ttdiv.style.position = 'absolute'; this.ttdiv.style.zIndex = c.style.zIndex + 1; AddHandler('mouseover',function(e){e.target.style.display='none';},this.ttdiv); doc.body.appendChild(this.ttdiv); } } } else { this.Tooltip = this.TooltipNone; } if(!this.noMouse && !handlers[cid]) { AddHandler('mousemove', MouseMove, c); AddHandler('mouseout', MouseOut, c); AddHandler('mouseup', MouseUp, c); AddHandler('touchstart', TouchDown, c); AddHandler('touchend', TouchUp, c); AddHandler('touchcancel', TouchUp, c); AddHandler('touchmove', TouchMove, c); if(this.dragControl) { AddHandler('mousedown', MouseDown, c); AddHandler('selectstart', Nop, c); } if(this.wheelZoom) { AddHandler('mousewheel', MouseWheel, c); AddHandler('DOMMouseScroll', MouseWheel, c); } handlers[cid] = 1; } TagCanvas.started || (TagCanvas.started = setTimeout(DrawCanvas, this.interval)); } TCproto = TagCanvas.prototype; TCproto.SourceElements = function() { if(doc.querySelectorAll) return doc.querySelectorAll('#' + this.source); return [doc.getElementById(this.source)]; }; TCproto.HideTags = function() { var el = this.SourceElements(), i; for(i = 0; i < el.length; ++i) el[i].style.display = 'none'; }; TCproto.GetTags = function() { var el = this.SourceElements(), etl, tl = [], i, j; for(i = 0; i < el.length; ++i) { etl = el[i].getElementsByTagName('a'); for(j = 0; j < etl.length; ++j) { tl.push(etl[j]); } } return tl; }; TCproto.CreateTag = function(e, p) { var im = e.getElementsByTagName('img'), i, t, ts, font; p = p || [0, 0, 0]; if(im.length) { i = new Image; i.src = im[0].src; t = new Tag(this, i, e, p, 0, 0); AddImage(i, im[0], t, this); return t; } ts = new TextSplitter(e); t = ts.Lines(); font = this.textFont || FixFont(GetProperty(e,'font-family')); if(this.splitWidth) t = ts.SplitWidth(this.splitWidth, this.ctxt, font, this.textHeight); return new Tag(this, t, e, p, 2, this.textHeight + 2, this.textColour || GetProperty(e,'color'), font, ts.original); }; TCproto.UpdateTag = function(t, a) { var colour = this.textColour || GetProperty(a, 'color'), font = this.textFont || FixFont(GetProperty(a, 'font-family')); t.title = a.title; if(t.colour != colour || t.textFont != font) t.SetFont(font, colour); }; TCproto.Weight = function(tl) { var l = tl.length, w, i, weights = []; for(i = 0; i < l; ++i) { w = FindWeight(this, tl[i].a); if(w > this.max_weight) this.max_weight = w; if(w < this.min_weight) this.min_weight = w; weights.push(w); } if(this.max_weight > this.min_weight) { for(i = 0; i < l; ++i) { tl[i].SetWeight(weights[i]); } } }; TCproto.Load = function() { var tl = this.GetTags(), taglist = [], shape, shapeArgs, rx, ry, rz, vl, i, tagmap = [], pfuncs = { sphere: PointsOnSphere, vcylinder: PointsOnCylinderV, hcylinder: PointsOnCylinderH, vring: PointsOnRingV, hring: PointsOnRingH }; if(tl.length) { tagmap.length = tl.length; for(i = 0; i < tl.length; ++i) tagmap[i] = i; this.shuffleTags && Shuffle(tagmap); rx = 100 * this.radiusX; ry = 100 * this.radiusY; rz = 100 * this.radiusZ; this.max_radius = max(rx, max(ry, rz)); if(this.shapeArgs) { this.shapeArgs[0] = tl.length; } else { shapeArgs = this.shape.toString().split(/[(),]/); shape = shapeArgs.shift(); this.shape = pfuncs[shape] || pfuncs.sphere; this.shapeArgs = [tl.length, rx, ry, rz].concat(shapeArgs); } vl = this.shape.apply(this, this.shapeArgs); this.listLength = tl.length; for(i = 0; i < tl.length; ++i) { taglist.push(this.CreateTag(tl[tagmap[i]], vl[i])); } this.weight && this.Weight(taglist, true); } this.taglist = taglist; }; TCproto.Update = function() { var tl = this.GetTags(), newlist = [], taglist = this.taglist, found, added = [], removed = [], vl, ol, nl, i, j; if(!this.shapeArgs) return this.Load(); if(tl.length) { nl = this.listLength = tl.length; ol = taglist.length; // copy existing list, populate "removed" for(i = 0; i < ol; ++i) { newlist.push(taglist[i]); removed.push(i); } // find added and removed tags for(i = 0; i < nl; ++i) { for(j = 0, found = 0; j < ol; ++j) { if(taglist[j].EqualTo(tl[i])) { this.UpdateTag(newlist[j], tl[i]); found = removed[j] = -1; } } if(!found) added.push(i); } // clean out found tags from removed list for(i = 0, j = 0; i < ol; ++i) { if(removed[j] == -1) removed.splice(j,1); else ++j; } // insert new tags in gaps where old tags removed if(removed.length) { Shuffle(removed); while(removed.length && added.length) { i = removed.shift(); j = added.shift(); newlist[i] = this.CreateTag(tl[j]); } // remove any more (in reverse order) removed.sort(function(a,b) {return a-b}); while(removed.length) { newlist.splice(removed.pop(), 1); } } // add any extra tags j = newlist.length / (added.length + 1); i = 0; while(added.length) { newlist.splice(ceil(++i * j), 0, this.CreateTag(tl[added.shift()])); } // assign correct positions to tags this.shapeArgs[0] = nl = newlist.length; vl = this.shape.apply(this, this.shapeArgs); for(i = 0; i < nl; ++i) newlist[i].position = { x: vl[i][0], y: vl[i][1], z: vl[i][2] }; // reweight tags this.weight && this.Weight(newlist); } this.taglist = newlist; }; TCproto.SetShadow = function(c) { c.shadowBlur = this.shadowBlur; c.shadowOffsetX = this.shadowOffset[0]; c.shadowOffsetY = this.shadowOffset[1]; }; TCproto.Draw = function(t) { if(this.paused) return; var cv = this.canvas, cw = cv.width, ch = cv.height, max_sc = 0, tdelta = (t - this.time) * this.interval / 1000, x = cw / 2 + this.offsetX, y = ch / 2 + this.offsetY, c = this.ctxt, active, a, i, aindex = -1, tl = this.taglist, l = tl.length, frontsel = this.frontSelect, centreDrawn = (this.centreFunc == Nop); this.time = t; if(this.frozen && this.drawn) return this.Animate(cw,ch,tdelta); c.setTransform(1,0,0,1,0,0); this.active = null; for(i = 0; i < l; ++i) tl[i].Calc(this.transform); tl = SortList(tl, function(a,b) {return b.z-a.z}); for(i = 0; i < l; ++i) { a = this.mx >= 0 && this.my >= 0 && this.taglist[i].CheckActive(c, x, y); if(a && a.sc > max_sc && (!frontsel || a.z <= 0)) { active = a; aindex = i; active.tag = this.taglist[i]; max_sc = a.sc; } } this.active = active; this.txtOpt || (this.shadow && this.SetShadow(c)); c.clearRect(0,0,cw,ch); for(i = 0; i < l; ++i) { if(!centreDrawn && tl[i].z <= 0) { // run the centreFunc if the next tag is at the front try { this.centreFunc(c, cw, ch, x, y); } catch(e) { alert(e); // don't run it again this.centreFunc = Nop; } centreDrawn = true; } if(!(active && active.tag == tl[i] && active.PreDraw(c, tl[i], x, y))) tl[i].Draw(c, x, y); active && active.tag == tl[i] && active.PostDraw(c); } if(this.freezeActive && active) { this.Freeze(); } else { this.UnFreeze(); this.drawn = (l == this.listLength); } this.Animate(cw, ch, tdelta); active && active.LastDraw(c); cv.style.cursor = active ? this.activeCursor : ''; this.Tooltip(active,this.taglist[aindex]); }; TCproto.TooltipNone = function() { }; TCproto.TooltipNative = function(active,tag) { this.canvas.title = active && tag.title ? tag.title : ''; }; TCproto.TooltipDiv = function(active,tag) { var tc = this, s = tc.ttdiv.style, cid = tc.canvas.id, none = 'none'; if(active && tag.title) { if(tag.title != tc.ttdiv.innerHTML) s.display = none; tc.ttdiv.innerHTML = tag.title; tag.title = tc.ttdiv.innerHTML; if(s.display == none && ! tc.tttimer) { tc.tttimer = setTimeout(function() { var p = AbsPos(cid); s.display = 'block'; s.left = p.x + tc.mx + 'px'; s.top = p.y + tc.my + 24 + 'px'; tc.tttimer = null; }, tc.tooltipDelay); } } else { s.display = none; } }; TCproto.Transform = function(tc, p, y) { if(p || y) { var sp = sin(p), cp = cos(p), sy = sin(y), cy = cos(y), ym = new Matrix([cy,0,sy,0, 0,1,0,0, -sy,0,cy,0, 0,0,0,1]), pm = new Matrix([1,0,0,0, 0,cp,-sp,0, 0,sp,cp,0, 0,0,0,1]); tc.transform = tc.transform.mul(ym.mul(pm)); } }; TCproto.AnimatePosition = function(w, h, t) { var tc = this, x = tc.mx, y = tc.my, s, r; if(!tc.frozen && x >= 0 && y >= 0 && x < w && y < h) { s = tc.maxSpeed, r = tc.reverse ? -1 : 1; tc.lx || (tc.yaw = r * t * ((s * 2 * x / w) - s)); tc.ly || (tc.pitch = r * t * -((s * 2 * y / h) - s)); tc.initial = null; } else if(!tc.initial) { if(tc.frozen && !tc.freezeDecel) tc.yaw = tc.pitch = 0; else tc.Decel(tc); } this.Transform(tc, tc.pitch, tc.yaw); }; TCproto.AnimateDrag = function(w, h, t) { var tc = this, rs = 100 * t * tc.maxSpeed / tc.max_radius / tc.zoom; if(tc.dx || tc.dy) { tc.lx || (tc.yaw = tc.dx * rs / tc.stretchX); tc.ly || (tc.pitch = tc.dy * -rs / tc.stretchY); tc.dx = tc.dy = 0; tc.initial = null; } else if(!tc.initial) { tc.Decel(tc); } this.Transform(tc, tc.pitch, tc.yaw); }; TCproto.Freeze = function() { if(!this.frozen) { this.preFreeze = [this.yaw, this.pitch]; this.frozen = 1; this.drawn = 0; } }; TCproto.UnFreeze = function() { if(this.frozen) { this.yaw = this.preFreeze[0]; this.pitch = this.preFreeze[1]; this.frozen = 0; } }; TCproto.Decel = function(tc) { var s = tc.minSpeed, ay = abs(tc.yaw), ap = abs(tc.pitch); if(!tc.lx && ay > s) tc.yaw = ay > tc.z0 ? tc.yaw * tc.decel : 0; if(!tc.ly && ap > s) tc.pitch = ap > tc.z0 ? tc.pitch * tc.decel : 0; }; TCproto.Zoom = function(r) { this.z2 = this.z1 * (1/r); this.drawn = 0; }; TCproto.Clicked = function(e) { var a = this.active; try { a && a.tag && a.tag.Clicked(e); } catch(ex) { } }; TCproto.Wheel = function(i) { var z = this.zoom + this.zoomStep * (i ? 1 : -1); this.zoom = min(this.zoomMax,max(this.zoomMin,z)); this.Zoom(this.zoom); }; TCproto.BeginDrag = function(e) { this.down = EventXY(e, this.canvas); e.cancelBubble = true; e.returnValue = false; e.preventDefault && e.preventDefault(); }; TCproto.Drag = function(e, p) { if(this.dragControl && this.down) { var t2 = this.dragThreshold * this.dragThreshold, dx = p.x - this.down.x, dy = p.y - this.down.y; if(this.dragging || dx * dx + dy * dy > t2) { this.dx = dx; this.dy = dy; this.dragging = 1; this.down = p; } } }; TCproto.EndDrag = function() { var res = this.dragging; this.dragging = this.down = null; return res; }; TCproto.Pause = function() { this.paused = true; }; TCproto.Resume = function() { this.paused = false; }; TagCanvas.Start = function(id,l,o) { TagCanvas.tc[id] = new TagCanvas(id,l,o); }; function tccall(f,id) { TagCanvas.tc[id] && TagCanvas.tc[id][f](); } TagCanvas.Pause = function(id) { tccall('Pause',id); }; TagCanvas.Resume = function(id) { tccall('Resume',id); }; TagCanvas.Reload = function(id) { tccall('Load',id); }; TagCanvas.Update = function(id) { tccall('Update',id); }; TagCanvas.NextFrame = function(iv) { var raf = window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame; TagCanvas.NextFrame = raf ? TagCanvas.NextFrameRAF : TagCanvas.NextFrameTimeout; TagCanvas.NextFrame(iv); }; TagCanvas.NextFrameRAF = function() { requestAnimationFrame(DrawCanvas); }; TagCanvas.NextFrameTimeout = function(iv) { setTimeout(DrawCanvas, iv); }; TagCanvas.tc = {}; TagCanvas.options = { z1: 20000, z2: 20000, z0: 0.0002, freezeActive: false, freezeDecel: false, activeCursor: 'pointer', pulsateTo: 1, pulsateTime: 3, reverse: false, depth: 0.5, maxSpeed: 0.05, minSpeed: 0, decel: 0.95, interval: 20, minBrightness: 0.1, maxBrightness: 1, outlineColour: '#ffff99', outlineThickness: 2, outlineOffset: 5, outlineMethod: 'outline', textColour: '#ff99ff', textHeight: 15, textFont: 'Helvetica, Arial, sans-serif', shadow: '#000', shadowBlur: 0, shadowOffset: [0,0], initial: null, hideTags: true, zoom: 1, weight: false, weightMode: 'size', weightFrom: null, weightSize: 1, weightSizeMin: null, weightSizeMax: null, weightGradient: {0:'#f00', 0.33:'#ff0', 0.66:'#0f0', 1:'#00f'}, txtOpt: true, txtScale: 2, frontSelect: false, wheelZoom: true, zoomMin: 0.3, zoomMax: 3, zoomStep: 0.05, shape: 'sphere', lock: null, tooltip: null, tooltipDelay: 300, tooltipClass: 'tctooltip', radiusX: 1, radiusY: 1, radiusZ: 1, stretchX: 1, stretchY: 1, offsetX: 0, offsetY: 0, shuffleTags: false, noSelect: false, noMouse: false, imageScale: 1, paused: false, dragControl: false, dragThreshold: 4, centreFunc: Nop, splitWidth: 0 }; for(i in TagCanvas.options) TagCanvas[i] = TagCanvas.options[i]; window.TagCanvas = TagCanvas; // set a flag for when the window has loaded AddHandler('load',function(){TagCanvas.loaded=1},window); })();
JavaScript
/** * LavaLamp - A menu plugin for jQuery with cool hover effects. * @requires jQuery v1.1.3.1 or above * * http://gmarwaha.com/blog/?p=7 * * Copyright (c) 2007 Ganeshji Marwaha (gmarwaha.com) * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Version: 0.1.0 */ /** * Creates a menu with an unordered list of menu-items. You can either use the CSS that comes with the plugin, or write your own styles * to create a personalized effect * * The HTML markup used to build the menu can be as simple as... * * <ul class="lavaLamp"> * <li><a href="#">Home</a></li> * <li><a href="#">Plant a tree</a></li> * <li><a href="#">Travel</a></li> * <li><a href="#">Ride an elephant</a></li> * </ul> * * Once you have included the style sheet that comes with the plugin, you will have to include * a reference to jquery library, easing plugin(optional) and the LavaLamp(this) plugin. * * Use the following snippet to initialize the menu. * $(function() { $(".lavaLamp").lavaLamp({ fx: "backout", speed: 700}) }); * * Thats it. Now you should have a working lavalamp menu. * * @param an options object - You can specify all the options shown below as an options object param. * * @option fx - default is "linear" * @example * $(".lavaLamp").lavaLamp({ fx: "backout" }); * @desc Creates a menu with "backout" easing effect. You need to include the easing plugin for this to work. * * @option speed - default is 500 ms * @example * $(".lavaLamp").lavaLamp({ speed: 500 }); * @desc Creates a menu with an animation speed of 500 ms. * * @option click - no defaults * @example * $(".lavaLamp").lavaLamp({ click: function(event, menuItem) { return false; } }); * @desc You can supply a callback to be executed when the menu item is clicked. * The event object and the menu-item that was clicked will be passed in as arguments. */ (function($) { $.fn.lavaLamp = function(o) { o = $.extend({ fx: "linear", speed: 500, click: function(){} }, o || {}); return this.each(function() { var me = $(this), noop = function(){}, $back = $('<li class="back"><div class="left"></div></li>').appendTo(me), $li = $("li", this), curr = $("li.current", this)[0] || $($li[0]).addClass("current")[0]; $li.not(".back").hover(function() { move(this); }, noop); $(this).hover(noop, function() { move(curr); }); $li.click(function(e) { setCurr(this); return o.click.apply(this, [e, this]); }); setCurr(curr); function setCurr(el) { $back.css({ "left": el.offsetLeft+"px", "width": el.offsetWidth+"px" }); curr = el; }; function move(el) { $back.each(function() { $.dequeue(this, "fx"); } ).animate({ width: el.offsetWidth, left: el.offsetLeft }, o.speed, o.fx); }; }); }; })(jQuery);
JavaScript
jvm.VMLGroupElement = function(){ jvm.VMLGroupElement.parentClass.call(this, 'group'); this.node.style.left = '0px'; this.node.style.top = '0px'; this.node.coordorigin = "0 0"; }; jvm.inherits(jvm.VMLGroupElement, jvm.VMLElement); jvm.VMLGroupElement.prototype.add = function(element){ this.node.appendChild( element.node ); };
JavaScript
/** * Wrapper for VML element. * @constructor * @extends jvm.AbstractElement * @param {String} name Tag name of the element * @param {Object} config Set of parameters to initialize element with */ jvm.VMLElement = function(name, config){ if (!jvm.VMLElement.VMLInitialized) { jvm.VMLElement.initializeVML(); } jvm.VMLElement.parentClass.apply(this, arguments); }; jvm.inherits(jvm.VMLElement, jvm.AbstractElement); /** * Shows if VML was already initialized for the current document or not. * @static * @private * @type {Boolean} */ jvm.VMLElement.VMLInitialized = false; /** * Initializes VML handling before creating the first element * (adds CSS class and creates namespace). Adds one of two forms * of createElement method depending of support by browser. * @static * @private */ // The following method of VML handling is borrowed from the // Raphael library by Dmitry Baranovsky. jvm.VMLElement.initializeVML = function(){ try { if (!document.namespaces.rvml) { document.namespaces.add("rvml","urn:schemas-microsoft-com:vml"); } /** * Creates DOM element. * @param {String} tagName Name of element * @private * @returns DOMElement */ jvm.VMLElement.prototype.createElement = function (tagName) { return document.createElement('<rvml:' + tagName + ' class="rvml">'); }; } catch (e) { /** * @private */ jvm.VMLElement.prototype.createElement = function (tagName) { return document.createElement('<' + tagName + ' xmlns="urn:schemas-microsoft.com:vml" class="rvml">'); }; } document.createStyleSheet().addRule(".rvml", "behavior:url(#default#VML)"); jvm.VMLElement.VMLInitialized = true; }; /** * Returns constructor for element by name prefixed with 'VML'. * @param {String} ctr Name of basic constructor to return * proper implementation for. * @returns Function * @private */ jvm.VMLElement.prototype.getElementCtr = function( ctr ){ return jvm['VML'+ctr]; }; /** * Adds CSS class for underlying DOM element. * @param {String} className Name of CSS class name */ jvm.VMLElement.prototype.addClass = function( className ){ jvm.$(this.node).addClass(className); }; /** * Applies attribute value to the underlying DOM element. * @param {String} name Name of attribute * @param {Number|String} config Value of attribute to apply * @private */ jvm.VMLElement.prototype.applyAttr = function( attr, value ){ this.node[attr] = value; }; /** * Returns boundary box for the element. * @returns {Object} Boundary box with numeric fields: x, y, width, height * @override */ jvm.VMLElement.prototype.getBBox = function(){ var node = jvm.$(this.node); return { x: node.position().left / this.canvas.scale, y: node.position().top / this.canvas.scale, width: node.width() / this.canvas.scale, height: node.height() / this.canvas.scale }; };
JavaScript
jvm.VMLCircleElement = function(config, style){ jvm.VMLCircleElement.parentClass.call(this, 'oval', config, style); }; jvm.inherits(jvm.VMLCircleElement, jvm.VMLShapeElement); jvm.VMLCircleElement.prototype.applyAttr = function(attr, value){ switch (attr) { case 'r': this.node.style.width = value*2+'px'; this.node.style.height = value*2+'px'; this.applyAttr('cx', this.get('cx') || 0); this.applyAttr('cy', this.get('cy') || 0); break; case 'cx': if (!value) return; this.node.style.left = value - (this.get('r') || 0) + 'px'; break; case 'cy': if (!value) return; this.node.style.top = value - (this.get('r') || 0) + 'px'; break; default: jvm.VMLCircleElement.parentClass.prototype.applyAttr.call(this, attr, value); } };
JavaScript
/** * Implements abstract vector canvas. * @constructor * @param {HTMLElement} container Container to put element to. * @param {Number} width Width of canvas. * @param {Number} height Height of canvas. */ jvm.AbstractCanvasElement = function(container, width, height){ this.container = container; this.setSize(width, height); this.rootElement = new jvm[this.classPrefix+'GroupElement'](); this.node.appendChild( this.rootElement.node ); this.container.appendChild(this.node); } /** * Add element to the certain group inside of the canvas. * @param {HTMLElement} element Element to add to canvas. * @param {HTMLElement} group Group to add element into or into root group if not provided. */ jvm.AbstractCanvasElement.prototype.add = function(element, group){ group = group || this.rootElement; group.add(element); element.canvas = this; } /** * Create path and add it to the canvas. * @param {Object} config Parameters of path to create. * @param {Object} style Styles of the path to create. * @param {HTMLElement} group Group to add path into. */ jvm.AbstractCanvasElement.prototype.addPath = function(config, style, group){ var el = new jvm[this.classPrefix+'PathElement'](config, style); this.add(el, group); return el; }; /** * Create circle and add it to the canvas. * @param {Object} config Parameters of path to create. * @param {Object} style Styles of the path to create. * @param {HTMLElement} group Group to add circle into. */ jvm.AbstractCanvasElement.prototype.addCircle = function(config, style, group){ var el = new jvm[this.classPrefix+'CircleElement'](config, style); this.add(el, group); return el; }; /** * Add group to the another group inside of the canvas. * @param {HTMLElement} group Group to add circle into or root group if not provided. */ jvm.AbstractCanvasElement.prototype.addGroup = function(parentGroup){ var el = new jvm[this.classPrefix+'GroupElement'](); if (parentGroup) { parentGroup.node.appendChild(el.node); } else { this.node.appendChild(el.node); } el.canvas = this; return el; };
JavaScript
/** * Wrapper for SVG element. * @constructor * @extends jvm.AbstractElement * @param {String} name Tag name of the element * @param {Object} config Set of parameters to initialize element with */ jvm.SVGElement = function(name, config){ jvm.SVGElement.parentClass.apply(this, arguments); } jvm.inherits(jvm.SVGElement, jvm.AbstractElement); jvm.SVGElement.svgns = "http://www.w3.org/2000/svg"; /** * Creates DOM element. * @param {String} tagName Name of element * @private * @returns DOMElement */ jvm.SVGElement.prototype.createElement = function( tagName ){ return document.createElementNS( jvm.SVGElement.svgns, tagName ); }; /** * Adds CSS class for underlying DOM element. * @param {String} className Name of CSS class name */ jvm.SVGElement.prototype.addClass = function( className ){ this.node.setAttribute('class', className); }; /** * Returns constructor for element by name prefixed with 'VML'. * @param {String} ctr Name of basic constructor to return * proper implementation for. * @returns Function * @private */ jvm.SVGElement.prototype.getElementCtr = function( ctr ){ return jvm['SVG'+ctr]; }; jvm.SVGElement.prototype.getBBox = function(){ return this.node.getBBox(); };
JavaScript
jvm.SVGGroupElement = function(){ jvm.SVGGroupElement.parentClass.call(this, 'g'); } jvm.inherits(jvm.SVGGroupElement, jvm.SVGElement); jvm.SVGGroupElement.prototype.add = function(element){ this.node.appendChild( element.node ); };
JavaScript
/** * Creates data series. * @constructor * @param {Object} params Parameters to initialize series with. * @param {Array} params.values The data set to visualize. * @param {String} params.attribute Numberic or color attribute to use for data visualization. This could be: <code>fill</code>, <code>stroke</code>, <code>fill-opacity</code>, <code>stroke-opacity</code> for markers and regions and <code>r</code> (radius) for markers only. * @param {Array} params.scale Values used to map a dimension of data to a visual representation. The first value sets visualization for minimum value from the data set and the last value sets visualization for the maximum value. There also could be intermidiate values. Default value is <code>['#C8EEFF', '#0071A4']</code> * @param {Function|String} params.normalizeFunction The function used to map input values to the provided scale. This parameter could be provided as function or one of the strings: <code>'linear'</code> or <code>'polynomial'</code>, while <code>'linear'</code> is used by default. The function provided takes value from the data set as an input and returns corresponding value from the scale. * @param {Number} params.min Minimum value of the data set. Could be calculated automatically if not provided. * @param {Number} params.min Maximum value of the data set. Could be calculated automatically if not provided. */ jvm.DataSeries = function(params, elements) { var scaleConstructor; params = params || {}; params.attribute = params.attribute || 'fill'; this.elements = elements; this.params = params; if (params.attributes) { this.setAttributes(params.attributes); } if (jvm.$.isArray(params.scale)) { scaleConstructor = (params.attribute === 'fill' || params.attribute === 'stroke') ? jvm.ColorScale : jvm.NumericScale; this.scale = new scaleConstructor(params.scale, params.normalizeFunction, params.min, params.max); } else if (params.scale) { this.scale = new jvm.OrdinalScale(params.scale); } else { this.scale = new jvm.SimpleScale(params.scale); } this.values = params.values || {}; this.setValues(this.values); }; jvm.DataSeries.prototype = { setAttributes: function(key, attr){ var attrs = key, code; if (typeof key == 'string') { if (this.elements[key]) { this.elements[key].setStyle(this.params.attribute, attr); } } else { for (code in attrs) { if (this.elements[code]) { this.elements[code].element.setStyle(this.params.attribute, attrs[code]); } } } }, /** * Set values for the data set. * @param {Object} values Object which maps codes of regions or markers to values. */ setValues: function(values) { var max = Number.MIN_VALUE, min = Number.MAX_VALUE, val, cc, attrs = {}; if (!(this.scale instanceof jvm.OrdinalScale) && !(this.scale instanceof jvm.SimpleScale)) { if (!this.params.min || !this.params.max) { for (cc in values) { val = parseFloat(values[cc]); if (val > max) max = values[cc]; if (val < min) min = val; } if (!this.params.min) { this.scale.setMin(min); } if (!this.params.max) { this.scale.setMax(max); } this.params.min = min; this.params.max = max; } for (cc in values) { val = parseFloat(values[cc]); if (!isNaN(val)) { attrs[cc] = this.scale.getValue(val); } else { attrs[cc] = this.elements[cc].element.style.initial[this.params.attribute]; } } } else { for (cc in values) { if (values[cc]) { attrs[cc] = this.scale.getValue(values[cc]); } else { attrs[cc] = this.elements[cc].element.style.initial[this.params.attribute]; } } } this.setAttributes(attrs); jvm.$.extend(this.values, values); }, clear: function(){ var key, attrs = {}; for (key in this.values) { if (this.elements[key]) { attrs[key] = this.elements[key].element.style.initial[this.params.attribute]; } } this.setAttributes(attrs); this.values = {}; }, /** * Set scale of the data series. * @param {Array} scale Values representing scale. */ setScale: function(scale) { this.scale.setScale(scale); if (this.values) { this.setValues(this.values); } }, /** * Set normalize function of the data series. * @param {Function|String} normilizeFunction. */ setNormalizeFunction: function(f) { this.scale.setNormalizeFunction(f); if (this.values) { this.setValues(this.values); } } };
JavaScript
jvm.VMLPathElement = function(config, style){ var scale = new jvm.VMLElement('skew'); jvm.VMLPathElement.parentClass.call(this, 'shape', config, style); this.node.coordorigin = "0 0"; scale.node.on = true; scale.node.matrix = '0.01,0,0,0.01,0,0'; scale.node.offset = '0,0'; this.node.appendChild(scale.node); }; jvm.inherits(jvm.VMLPathElement, jvm.VMLShapeElement); jvm.VMLPathElement.prototype.applyAttr = function(attr, value){ if (attr === 'd') { this.node.path = jvm.VMLPathElement.pathSvgToVml(value); } else { jvm.VMLShapeElement.prototype.applyAttr.call(this, attr, value); } }; jvm.VMLPathElement.pathSvgToVml = function(path) { var result = '', cx = 0, cy = 0, ctrlx, ctrly; path = path.replace(/(-?\d+)e(-?\d+)/g, '0'); return path.replace(/([MmLlHhVvCcSs])\s*((?:-?\d*(?:\.\d+)?\s*,?\s*)+)/g, function(segment, letter, coords, index){ coords = coords.replace(/(\d)-/g, '$1,-') .replace(/^\s+/g, '') .replace(/\s+$/g, '') .replace(/\s+/g, ',').split(','); if (!coords[0]) coords.shift(); for (var i=0, l=coords.length; i<l; i++) { coords[i] = Math.round(100*coords[i]); } switch (letter) { case 'm': cx += coords[0]; cy += coords[1]; return 't'+coords.join(','); break; case 'M': cx = coords[0]; cy = coords[1]; return 'm'+coords.join(','); break; case 'l': cx += coords[0]; cy += coords[1]; return 'r'+coords.join(','); break; case 'L': cx = coords[0]; cy = coords[1]; return 'l'+coords.join(','); break; case 'h': cx += coords[0]; return 'r'+coords[0]+',0'; break; case 'H': cx = coords[0]; return 'l'+cx+','+cy; break; case 'v': cy += coords[0]; return 'r0,'+coords[0]; break; case 'V': cy = coords[0]; return 'l'+cx+','+cy; break; case 'c': ctrlx = cx + coords[coords.length-4]; ctrly = cy + coords[coords.length-3]; cx += coords[coords.length-2]; cy += coords[coords.length-1]; return 'v'+coords.join(','); break; case 'C': ctrlx = coords[coords.length-4]; ctrly = coords[coords.length-3]; cx = coords[coords.length-2]; cy = coords[coords.length-1]; return 'c'+coords.join(','); break; case 's': coords.unshift(cy-ctrly); coords.unshift(cx-ctrlx); ctrlx = cx + coords[coords.length-4]; ctrly = cy + coords[coords.length-3]; cx += coords[coords.length-2]; cy += coords[coords.length-1]; return 'v'+coords.join(','); break; case 'S': coords.unshift(cy+cy-ctrly); coords.unshift(cx+cx-ctrlx); ctrlx = coords[coords.length-4]; ctrly = coords[coords.length-3]; cx = coords[coords.length-2]; cy = coords[coords.length-1]; return 'c'+coords.join(','); break; } return ''; }).replace(/z/g, 'e'); };
JavaScript
/** * Basic wrapper for DOM element. * @constructor * @param {String} name Tag name of the element * @param {Object} config Set of parameters to initialize element with */ jvm.AbstractElement = function(name, config){ /** * Underlying DOM element * @type {DOMElement} * @private */ this.node = this.createElement(name); /** * Name of underlying element * @type {String} * @private */ this.name = name; /** * Internal store of attributes * @type {Object} * @private */ this.properties = {}; if (config) { this.set(config); } }; /** * Set attribute of the underlying DOM element. * @param {String} name Name of attribute * @param {Number|String} config Set of parameters to initialize element with */ jvm.AbstractElement.prototype.set = function(property, value){ var key; if (typeof property === 'object') { for (key in property) { this.properties[key] = property[key]; this.applyAttr(key, property[key]); } } else { this.properties[property] = value; this.applyAttr(property, value); } }; /** * Returns value of attribute. * @param {String} name Name of attribute */ jvm.AbstractElement.prototype.get = function(property){ return this.properties[property]; }; /** * Applies attribute value to the underlying DOM element. * @param {String} name Name of attribute * @param {Number|String} config Value of attribute to apply * @private */ jvm.AbstractElement.prototype.applyAttr = function(property, value){ this.node.setAttribute(property, value); }; jvm.AbstractElement.prototype.remove = function(){ jvm.$(this.node).remove(); };
JavaScript
jvm.OrdinalScale = function(scale){ this.scale = scale; }; jvm.OrdinalScale.prototype.getValue = function(value){ return this.scale[value]; };
JavaScript
/** * Abstract shape element. Shape element represents some visual vector or raster object. * @constructor * @param {String} name Tag name of the element. * @param {Object} config Set of parameters to initialize element with. * @param {Object} style Object with styles to set on element initialization. */ jvm.AbstractShapeElement = function(name, config, style){ this.style = style || {}; this.style.current = {}; this.isHovered = false; this.isSelected = false; this.updateStyle(); }; /** * Set hovered state to the element. Hovered state means mouse cursor is over element. Styles will be updates respectively. * @param {Boolean} isHovered <code>true</code> to make element hovered, <code>false</code> otherwise. */ jvm.AbstractShapeElement.prototype.setHovered = function(isHovered){ if (this.isHovered !== isHovered) { this.isHovered = isHovered; this.updateStyle(); } }; /** * Set selected state to the element. Styles will be updates respectively. * @param {Boolean} isSelected <code>true</code> to make element selected, <code>false</code> otherwise. */ jvm.AbstractShapeElement.prototype.setSelected = function(isSelected){ if (this.isSelected !== isSelected) { this.isSelected = isSelected; this.updateStyle(); jvm.$(this.node).trigger('selected', [isSelected]); } }; /** * Set element's style. * @param {Object|String} property Could be string to set only one property or object to set several style properties at once. * @param {String} value Value to set in case only one property should be set. */ jvm.AbstractShapeElement.prototype.setStyle = function(property, value){ var styles = {}; if (typeof property === 'object') { styles = property; } else { styles[property] = value; } jvm.$.extend(this.style.current, styles); this.updateStyle(); }; jvm.AbstractShapeElement.prototype.updateStyle = function(){ var attrs = {}; jvm.AbstractShapeElement.mergeStyles(attrs, this.style.initial); jvm.AbstractShapeElement.mergeStyles(attrs, this.style.current); if (this.isHovered) { jvm.AbstractShapeElement.mergeStyles(attrs, this.style.hover); } if (this.isSelected) { jvm.AbstractShapeElement.mergeStyles(attrs, this.style.selected); if (this.isHovered) { jvm.AbstractShapeElement.mergeStyles(attrs, this.style.selectedHover); } } this.set(attrs); }; jvm.AbstractShapeElement.mergeStyles = function(styles, newStyles){ var key; newStyles = newStyles || {}; for (key in newStyles) { if (newStyles[key] === null) { delete styles[key]; } else { styles[key] = newStyles[key]; } } }
JavaScript
jvm.SVGShapeElement = function(name, config, style){ jvm.SVGShapeElement.parentClass.call(this, name, config); jvm.AbstractShapeElement.apply(this, arguments); }; jvm.inherits(jvm.SVGShapeElement, jvm.SVGElement); jvm.mixin(jvm.SVGShapeElement, jvm.AbstractShapeElement);
JavaScript
/** * @namespace jvm Holds core methods and classes used by jVectorMap. */ var jvm = { /** * Inherits child's prototype from the parent's one. * @param {Function} child * @param {Function} parent */ inherits: function(child, parent) { function temp() {} temp.prototype = parent.prototype; child.prototype = new temp(); child.prototype.constructor = child; child.parentClass = parent; }, /** * Mixes in methods from the source constructor to the target one. * @param {Function} target * @param {Function} source */ mixin: function(target, source){ var prop; for (prop in source.prototype) { if (source.prototype.hasOwnProperty(prop)) { target.prototype[prop] = source.prototype[prop]; } } }, min: function(values){ var min = Number.MAX_VALUE, i; if (values instanceof Array) { for (i = 0; i < values.length; i++) { if (values[i] < min) { min = values[i]; } } } else { for (i in values) { if (values[i] < min) { min = values[i]; } } } return min; }, max: function(values){ var max = Number.MIN_VALUE, i; if (values instanceof Array) { for (i = 0; i < values.length; i++) { if (values[i] > max) { max = values[i]; } } } else { for (i in values) { if (values[i] > max) { max = values[i]; } } } return max; }, keys: function(object){ var keys = [], key; for (key in object) { keys.push(key); } return keys; }, values: function(object){ var values = [], key, i; for (i = 0; i < arguments.length; i++) { object = arguments[i]; for (key in object) { values.push(object[key]); } } return values; } }; jvm.$ = jQuery;
JavaScript
jvm.SVGCircleElement = function(config, style){ jvm.SVGCircleElement.parentClass.call(this, 'circle', config, style); }; jvm.inherits(jvm.SVGCircleElement, jvm.SVGShapeElement);
JavaScript
/** * Class for vector images manipulations. * @constructor * @param {DOMElement} container to place canvas to * @param {Number} width * @param {Number} height */ jvm.VectorCanvas = function(container, width, height) { this.mode = window.SVGAngle ? 'svg' : 'vml'; if (this.mode == 'svg') { this.impl = new jvm.SVGCanvasElement(container, width, height); } else { this.impl = new jvm.VMLCanvasElement(container, width, height); } return this.impl; };
JavaScript
jvm.SVGPathElement = function(config, style){ jvm.SVGPathElement.parentClass.call(this, 'path', config, style); this.node.setAttribute('fill-rule', 'evenodd'); } jvm.inherits(jvm.SVGPathElement, jvm.SVGShapeElement);
JavaScript
jvm.ColorScale = function(colors, normalizeFunction, minValue, maxValue) { jvm.ColorScale.parentClass.apply(this, arguments); } jvm.inherits(jvm.ColorScale, jvm.NumericScale); jvm.ColorScale.prototype.setScale = function(scale) { var i; for (i = 0; i < scale.length; i++) { this.scale[i] = jvm.ColorScale.rgbToArray(scale[i]); } }; jvm.ColorScale.prototype.getValue = function(value) { return jvm.ColorScale.numToRgb(jvm.ColorScale.parentClass.prototype.getValue.call(this, value)); }; jvm.ColorScale.arrayToRgb = function(ar) { var rgb = '#', d, i; for (i = 0; i < ar.length; i++) { d = ar[i].toString(16); rgb += d.length == 1 ? '0'+d : d; } return rgb; }; jvm.ColorScale.numToRgb = function(num) { num = num.toString(16); while (num.length < 6) { num = '0' + num; } return '#'+num; }; jvm.ColorScale.rgbToArray = function(rgb) { rgb = rgb.substr(1); return [parseInt(rgb.substr(0, 2), 16), parseInt(rgb.substr(2, 2), 16), parseInt(rgb.substr(4, 2), 16)]; };
JavaScript
jvm.SimpleScale = function(scale){ this.scale = scale; }; jvm.SimpleScale.prototype.getValue = function(value){ return value; };
JavaScript
jvm.NumericScale = function(scale, normalizeFunction, minValue, maxValue) { this.scale = []; normalizeFunction = normalizeFunction || 'linear'; if (scale) this.setScale(scale); if (normalizeFunction) this.setNormalizeFunction(normalizeFunction); if (minValue) this.setMin(minValue); if (maxValue) this.setMax(maxValue); }; jvm.NumericScale.prototype = { setMin: function(min) { this.clearMinValue = min; if (typeof this.normalize === 'function') { this.minValue = this.normalize(min); } else { this.minValue = min; } }, setMax: function(max) { this.clearMaxValue = max; if (typeof this.normalize === 'function') { this.maxValue = this.normalize(max); } else { this.maxValue = max; } }, setScale: function(scale) { var i; for (i = 0; i < scale.length; i++) { this.scale[i] = [scale[i]]; } }, setNormalizeFunction: function(f) { if (f === 'polynomial') { this.normalize = function(value) { return Math.pow(value, 0.2); } } else if (f === 'linear') { delete this.normalize; } else { this.normalize = f; } this.setMin(this.clearMinValue); this.setMax(this.clearMaxValue); }, getValue: function(value) { var lengthes = [], fullLength = 0, l, i = 0, c; if (typeof this.normalize === 'function') { value = this.normalize(value); } for (i = 0; i < this.scale.length-1; i++) { l = this.vectorLength(this.vectorSubtract(this.scale[i+1], this.scale[i])); lengthes.push(l); fullLength += l; } c = (this.maxValue - this.minValue) / fullLength; for (i=0; i<lengthes.length; i++) { lengthes[i] *= c; } i = 0; value -= this.minValue; while (value - lengthes[i] >= 0) { value -= lengthes[i]; i++; } if (i == this.scale.length - 1) { value = this.vectorToNum(this.scale[i]) } else { value = ( this.vectorToNum( this.vectorAdd(this.scale[i], this.vectorMult( this.vectorSubtract(this.scale[i+1], this.scale[i]), (value) / (lengthes[i]) ) ) ) ); } return value; }, vectorToNum: function(vector) { var num = 0, i; for (i = 0; i < vector.length; i++) { num += Math.round(vector[i])*Math.pow(256, vector.length-i-1); } return num; }, vectorSubtract: function(vector1, vector2) { var vector = [], i; for (i = 0; i < vector1.length; i++) { vector[i] = vector1[i] - vector2[i]; } return vector; }, vectorAdd: function(vector1, vector2) { var vector = [], i; for (i = 0; i < vector1.length; i++) { vector[i] = vector1[i] + vector2[i]; } return vector; }, vectorMult: function(vector, num) { var result = [], i; for (i = 0; i < vector.length; i++) { result[i] = vector[i] * num; } return result; }, vectorLength: function(vector) { var result = 0, i; for (i = 0; i < vector.length; i++) { result += vector[i] * vector[i]; } return Math.sqrt(result); } };
JavaScript
/** * Contains methods for transforming point on sphere to * Cartesian coordinates using various projections. * @class */ jvm.Proj = { degRad: 180 / Math.PI, radDeg: Math.PI / 180, radius: 6381372, sgn: function(n){ if (n > 0) { return 1; } else if (n < 0) { return -1; } else { return n; } }, /** * Converts point on sphere to the Cartesian coordinates using Miller projection * @param {Number} lat Latitude in degrees * @param {Number} lng Longitude in degrees * @param {Number} c Central meridian in degrees */ mill: function(lat, lng, c){ return { x: this.radius * (lng - c) * this.radDeg, y: - this.radius * Math.log(Math.tan((45 + 0.4 * lat) * this.radDeg)) / 0.8 }; }, /** * Inverse function of mill() * Converts Cartesian coordinates to point on sphere using Miller projection * @param {Number} x X of point in Cartesian system as integer * @param {Number} y Y of point in Cartesian system as integer * @param {Number} c Central meridian in degrees */ mill_inv: function(x, y, c){ return { lat: (2.5 * Math.atan(Math.exp(0.8 * y / this.radius)) - 5 * Math.PI / 8) * this.degRad, lng: (c * this.radDeg + x / this.radius) * this.degRad }; }, /** * Converts point on sphere to the Cartesian coordinates using Mercator projection * @param {Number} lat Latitude in degrees * @param {Number} lng Longitude in degrees * @param {Number} c Central meridian in degrees */ merc: function(lat, lng, c){ return { x: this.radius * (lng - c) * this.radDeg, y: - this.radius * Math.log(Math.tan(Math.PI / 4 + lat * Math.PI / 360)) }; }, /** * Inverse function of merc() * Converts Cartesian coordinates to point on sphere using Mercator projection * @param {Number} x X of point in Cartesian system as integer * @param {Number} y Y of point in Cartesian system as integer * @param {Number} c Central meridian in degrees */ merc_inv: function(x, y, c){ return { lat: (2 * Math.atan(Math.exp(y / this.radius)) - Math.PI / 2) * this.degRad, lng: (c * this.radDeg + x / this.radius) * this.degRad }; }, /** * Converts point on sphere to the Cartesian coordinates using Albers Equal-Area Conic * projection * @see <a href="http://mathworld.wolfram.com/AlbersEqual-AreaConicProjection.html">Albers Equal-Area Conic projection</a> * @param {Number} lat Latitude in degrees * @param {Number} lng Longitude in degrees * @param {Number} c Central meridian in degrees */ aea: function(lat, lng, c){ var fi0 = 0, lambda0 = c * this.radDeg, fi1 = 29.5 * this.radDeg, fi2 = 45.5 * this.radDeg, fi = lat * this.radDeg, lambda = lng * this.radDeg, n = (Math.sin(fi1)+Math.sin(fi2)) / 2, C = Math.cos(fi1)*Math.cos(fi1)+2*n*Math.sin(fi1), theta = n*(lambda-lambda0), ro = Math.sqrt(C-2*n*Math.sin(fi))/n, ro0 = Math.sqrt(C-2*n*Math.sin(fi0))/n; return { x: ro * Math.sin(theta) * this.radius, y: - (ro0 - ro * Math.cos(theta)) * this.radius }; }, /** * Converts Cartesian coordinates to the point on sphere using Albers Equal-Area Conic * projection * @see <a href="http://mathworld.wolfram.com/AlbersEqual-AreaConicProjection.html">Albers Equal-Area Conic projection</a> * @param {Number} x X of point in Cartesian system as integer * @param {Number} y Y of point in Cartesian system as integer * @param {Number} c Central meridian in degrees */ aea_inv: function(xCoord, yCoord, c){ var x = xCoord / this.radius, y = yCoord / this.radius, fi0 = 0, lambda0 = c * this.radDeg, fi1 = 29.5 * this.radDeg, fi2 = 45.5 * this.radDeg, n = (Math.sin(fi1)+Math.sin(fi2)) / 2, C = Math.cos(fi1)*Math.cos(fi1)+2*n*Math.sin(fi1), ro0 = Math.sqrt(C-2*n*Math.sin(fi0))/n, ro = Math.sqrt(x*x+(ro0-y)*(ro0-y)), theta = Math.atan( x / (ro0 - y) ); return { lat: (Math.asin((C - ro * ro * n * n) / (2 * n))) * this.degRad, lng: (lambda0 + theta / n) * this.degRad }; }, /** * Converts point on sphere to the Cartesian coordinates using Lambert conformal * conic projection * @see <a href="http://mathworld.wolfram.com/LambertConformalConicProjection.html">Lambert Conformal Conic Projection</a> * @param {Number} lat Latitude in degrees * @param {Number} lng Longitude in degrees * @param {Number} c Central meridian in degrees */ lcc: function(lat, lng, c){ var fi0 = 0, lambda0 = c * this.radDeg, lambda = lng * this.radDeg, fi1 = 33 * this.radDeg, fi2 = 45 * this.radDeg, fi = lat * this.radDeg, n = Math.log( Math.cos(fi1) * (1 / Math.cos(fi2)) ) / Math.log( Math.tan( Math.PI / 4 + fi2 / 2) * (1 / Math.tan( Math.PI / 4 + fi1 / 2) ) ), F = ( Math.cos(fi1) * Math.pow( Math.tan( Math.PI / 4 + fi1 / 2 ), n ) ) / n, ro = F * Math.pow( 1 / Math.tan( Math.PI / 4 + fi / 2 ), n ), ro0 = F * Math.pow( 1 / Math.tan( Math.PI / 4 + fi0 / 2 ), n ); return { x: ro * Math.sin( n * (lambda - lambda0) ) * this.radius, y: - (ro0 - ro * Math.cos( n * (lambda - lambda0) ) ) * this.radius }; }, /** * Converts Cartesian coordinates to the point on sphere using Lambert conformal conic * projection * @see <a href="http://mathworld.wolfram.com/LambertConformalConicProjection.html">Lambert Conformal Conic Projection</a> * @param {Number} x X of point in Cartesian system as integer * @param {Number} y Y of point in Cartesian system as integer * @param {Number} c Central meridian in degrees */ lcc_inv: function(xCoord, yCoord, c){ var x = xCoord / this.radius, y = yCoord / this.radius, fi0 = 0, lambda0 = c * this.radDeg, fi1 = 33 * this.radDeg, fi2 = 45 * this.radDeg, n = Math.log( Math.cos(fi1) * (1 / Math.cos(fi2)) ) / Math.log( Math.tan( Math.PI / 4 + fi2 / 2) * (1 / Math.tan( Math.PI / 4 + fi1 / 2) ) ), F = ( Math.cos(fi1) * Math.pow( Math.tan( Math.PI / 4 + fi1 / 2 ), n ) ) / n, ro0 = F * Math.pow( 1 / Math.tan( Math.PI / 4 + fi0 / 2 ), n ), ro = this.sgn(n) * Math.sqrt(x*x+(ro0-y)*(ro0-y)), theta = Math.atan( x / (ro0 - y) ); return { lat: (2 * Math.atan(Math.pow(F/ro, 1/n)) - Math.PI / 2) * this.degRad, lng: (lambda0 + theta / n) * this.degRad }; } };
JavaScript
jvm.VMLShapeElement = function(name, config){ jvm.VMLShapeElement.parentClass.call(this, name, config); this.fillElement = new jvm.VMLElement('fill'); this.strokeElement = new jvm.VMLElement('stroke'); this.node.appendChild(this.fillElement.node); this.node.appendChild(this.strokeElement.node); this.node.stroked = false; jvm.AbstractShapeElement.apply(this, arguments); }; jvm.inherits(jvm.VMLShapeElement, jvm.VMLElement); jvm.mixin(jvm.VMLShapeElement, jvm.AbstractShapeElement); jvm.VMLShapeElement.prototype.applyAttr = function(attr, value){ switch (attr) { case 'fill': this.node.fillcolor = value; break; case 'fill-opacity': this.fillElement.node.opacity = Math.round(value*100)+'%'; break; case 'stroke': if (value === 'none') { this.node.stroked = false; } else { this.node.stroked = true; } this.node.strokecolor = value; break; case 'stroke-opacity': this.strokeElement.node.opacity = Math.round(value*100)+'%'; break; case 'stroke-width': if (parseInt(value, 10) === 0) { this.node.stroked = false; } else { this.node.stroked = true; } this.node.strokeweight = value; break; case 'd': this.node.path = jvm.VMLPathElement.pathSvgToVml(value); break; default: jvm.VMLShapeElement.parentClass.prototype.applyAttr.apply(this, arguments); } };
JavaScript
jvm.VMLCanvasElement = function(container, width, height){ this.classPrefix = 'VML'; jvm.VMLCanvasElement.parentClass.call(this, 'group'); jvm.AbstractCanvasElement.apply(this, arguments); this.node.style.position = 'absolute'; }; jvm.inherits(jvm.VMLCanvasElement, jvm.VMLElement); jvm.mixin(jvm.VMLCanvasElement, jvm.AbstractCanvasElement); jvm.VMLCanvasElement.prototype.setSize = function(width, height){ var paths, groups, i, l; this.width = width; this.height = height; this.node.style.width = width + "px"; this.node.style.height = height + "px"; this.node.coordsize = width+' '+height; this.node.coordorigin = "0 0"; if (this.rootElement) { paths = this.rootElement.node.getElementsByTagName('shape'); for(i = 0, l = paths.length; i < l; i++) { paths[i].coordsize = width+' '+height; paths[i].style.width = width+'px'; paths[i].style.height = height+'px'; } groups = this.node.getElementsByTagName('group'); for(i = 0, l = groups.length; i < l; i++) { groups[i].coordsize = width+' '+height; groups[i].style.width = width+'px'; groups[i].style.height = height+'px'; } } }; jvm.VMLCanvasElement.prototype.applyTransformParams = function(scale, transX, transY) { this.scale = scale; this.transX = transX; this.transY = transY; this.rootElement.node.coordorigin = (this.width-transX-this.width/100)+','+(this.height-transY-this.height/100); this.rootElement.node.coordsize = this.width/scale+','+this.height/scale; };
JavaScript
/** * Creates map, draws paths, binds events. * @constructor * @param {Object} params Parameters to initialize map with. * @param {String} params.map Name of the map in the format <code>territory_proj_lang</code> where <code>territory</code> is a unique code or name of the territory which the map represents (ISO 3166 alpha 2 standard is used where possible), <code>proj</code> is a name of projection used to generate representation of the map on the plane (projections are named according to the conventions of proj4 utility) and <code>lang</code> is a code of the language, used for the names of regions. * @param {String} params.backgroundColor Background color of the map in CSS format. * @param {Boolean} params.zoomOnScroll When set to true map could be zoomed using mouse scroll. Default value is <code>true</code>. * @param {Number} params.zoomMax Indicates the maximum zoom ratio which could be reached zooming the map. Default value is <code>8</code>. * @param {Number} params.zoomMin Indicates the minimum zoom ratio which could be reached zooming the map. Default value is <code>1</code>. * @param {Number} params.zoomStep Indicates the multiplier used to zoom map with +/- buttons. Default value is <code>1.6</code>. * @param {Boolean} params.regionsSelectable When set to true regions of the map could be selected. Default value is <code>false</code>. * @param {Boolean} params.regionsSelectableOne Allow only one region to be selected at the moment. Default value is <code>false</code>. * @param {Boolean} params.markersSelectable When set to true markers on the map could be selected. Default value is <code>false</code>. * @param {Boolean} params.markersSelectableOne Allow only one marker to be selected at the moment. Default value is <code>false</code>. * @param {Object} params.regionStyle Set the styles for the map's regions. Each region or marker has four states: <code>initial</code> (default state), <code>hover</code> (when the mouse cursor is over the region or marker), <code>selected</code> (when region or marker is selected), <code>selectedHover</code> (when the mouse cursor is over the region or marker and it's selected simultaneously). Styles could be set for each of this states. Default value for that parameter is: <pre>{ initial: { fill: 'white', "fill-opacity": 1, stroke: 'none', "stroke-width": 0, "stroke-opacity": 1 }, hover: { "fill-opacity": 0.8 }, selected: { fill: 'yellow' }, selectedHover: { } }</pre> * @param {Object} params.markerStyle Set the styles for the map's markers. Any parameter suitable for <code>regionStyle</code> could be used as well as numeric parameter <code>r</code> to set the marker's radius. Default value for that parameter is: <pre>{ initial: { fill: 'grey', stroke: '#505050', "fill-opacity": 1, "stroke-width": 1, "stroke-opacity": 1, r: 5 }, hover: { stroke: 'black', "stroke-width": 2 }, selected: { fill: 'blue' }, selectedHover: { } }</pre> * @param {Object|Array} params.markers Set of markers to add to the map during initialization. In case of array is provided, codes of markers will be set as string representations of array indexes. Each marker is represented by <code>latLng</code> (array of two numeric values), <code>name</code> (string which will be show on marker's label) and any marker styles. * @param {Object} params.series Object with two keys: <code>markers</code> and <code>regions</code>. Each of which is an array of series configs to be applied to the respective map elements. See <a href="jvm.DataSeries.html">DataSeries</a> description for a list of parameters available. * @param {Object|String} params.focusOn This parameter sets the initial position and scale of the map viewport. It could be expressed as a string representing region which should be in focus or an object representing coordinates and scale to set. For example to focus on the center of the map at the double scale you can provide the following value: <pre>{ x: 0.5, y: 0.5, scale: 2 }</pre> * @param {Array|Object|String} params.selectedRegions Set initially selected regions. * @param {Array|Object|String} params.selectedMarkers Set initially selected markers. * @param {Function} params.onRegionLabelShow <code>(Event e, Object label, String code)</code> Will be called right before the region label is going to be shown. * @param {Function} params.onRegionOver <code>(Event e, String code)</code> Will be called on region mouse over event. * @param {Function} params.onRegionOut <code>(Event e, String code)</code> Will be called on region mouse out event. * @param {Function} params.onRegionClick <code>(Event e, String code)</code> Will be called on region click event. * @param {Function} params.onRegionSelected <code>(Event e, String code, Boolean isSelected, Array selectedRegions)</code> Will be called when region is (de)selected. <code>isSelected</code> parameter of the callback indicates whether region is selected or not. <code>selectedRegions</code> contains codes of all currently selected regions. * @param {Function} params.onMarkerLabelShow <code>(Event e, Object label, String code)</code> Will be called right before the marker label is going to be shown. * @param {Function} params.onMarkerOver <code>(Event e, String code)</code> Will be called on marker mouse over event. * @param {Function} params.onMarkerOut <code>(Event e, String code)</code> Will be called on marker mouse out event. * @param {Function} params.onMarkerClick <code>(Event e, String code)</code> Will be called on marker click event. * @param {Function} params.onMarkerSelected <code>(Event e, String code, Boolean isSelected, Array selectedMarkers)</code> Will be called when marker is (de)selected. <code>isSelected</code> parameter of the callback indicates whether marker is selected or not. <code>selectedMarkers</code> contains codes of all currently selected markers. * @param {Function} params.onViewportChange <code>(Event e, Number scale)</code> Triggered when the map's viewport is changed (map was panned or zoomed). */ jvm.WorldMap = function(params) { var map = this, e; this.params = jvm.$.extend(true, {}, jvm.WorldMap.defaultParams, params); if (!jvm.WorldMap.maps[this.params.map]) { throw new Error('Attempt to use map which was not loaded: '+this.params.map); } this.mapData = jvm.WorldMap.maps[this.params.map]; this.markers = {}; this.regions = {}; this.regionsColors = {}; this.regionsData = {}; this.container = jvm.$('<div>').css({width: '100%', height: '100%'}).addClass('jvectormap-container'); this.params.container.append( this.container ); this.container.data('mapObject', this); this.container.css({ position: 'relative', overflow: 'hidden' }); this.defaultWidth = this.mapData.width; this.defaultHeight = this.mapData.height; this.setBackgroundColor(this.params.backgroundColor); this.onResize = function(){ map.setSize(); } jvm.$(window).resize(this.onResize); for (e in jvm.WorldMap.apiEvents) { if (this.params[e]) { this.container.bind(jvm.WorldMap.apiEvents[e]+'.jvectormap', this.params[e]); } } this.canvas = new jvm.VectorCanvas(this.container[0], this.width, this.height); if ( ('ontouchstart' in window) || (window.DocumentTouch && document instanceof DocumentTouch) ) { if (this.params.bindTouchEvents) { this.bindContainerTouchEvents(); } } else { this.bindContainerEvents(); } this.bindElementEvents(); this.createLabel(); if (this.params.zoomButtons) { this.bindZoomButtons(); } this.createRegions(); this.createMarkers(this.params.markers || {}); this.setSize(); if (this.params.focusOn) { if (typeof this.params.focusOn === 'object') { this.setFocus.call(this, this.params.focusOn.scale, this.params.focusOn.x, this.params.focusOn.y); } else { this.setFocus.call(this, this.params.focusOn); } } if (this.params.selectedRegions) { this.setSelectedRegions(this.params.selectedRegions); } if (this.params.selectedMarkers) { this.setSelectedMarkers(this.params.selectedMarkers); } if (this.params.series) { this.createSeries(); } }; jvm.WorldMap.prototype = { transX: 0, transY: 0, scale: 1, baseTransX: 0, baseTransY: 0, baseScale: 1, width: 0, height: 0, /** * Set background color of the map. * @param {String} backgroundColor Background color in CSS format. */ setBackgroundColor: function(backgroundColor) { this.container.css('background-color', backgroundColor); }, resize: function() { var curBaseScale = this.baseScale; if (this.width / this.height > this.defaultWidth / this.defaultHeight) { this.baseScale = this.height / this.defaultHeight; this.baseTransX = Math.abs(this.width - this.defaultWidth * this.baseScale) / (2 * this.baseScale); } else { this.baseScale = this.width / this.defaultWidth; this.baseTransY = Math.abs(this.height - this.defaultHeight * this.baseScale) / (2 * this.baseScale); } this.scale *= this.baseScale / curBaseScale; this.transX *= this.baseScale / curBaseScale; this.transY *= this.baseScale / curBaseScale; }, /** * Synchronize the size of the map with the size of the container. Suitable in situations where the size of the container is changed programmatically or container is shown after it became visible. */ setSize: function(){ this.width = this.container.width(); this.height = this.container.height(); this.resize(); this.canvas.setSize(this.width, this.height); this.applyTransform(); }, /** * Reset all the series and show the map with the initial zoom. */ reset: function() { var key, i; for (key in this.series) { for (i = 0; i < this.series[key].length; i++) { this.series[key][i].clear(); } } this.scale = this.baseScale; this.transX = this.baseTransX; this.transY = this.baseTransY; this.applyTransform(); }, applyTransform: function() { var maxTransX, maxTransY, minTransX, minTransY; if (this.defaultWidth * this.scale <= this.width) { maxTransX = (this.width - this.defaultWidth * this.scale) / (2 * this.scale); minTransX = (this.width - this.defaultWidth * this.scale) / (2 * this.scale); } else { maxTransX = 0; minTransX = (this.width - this.defaultWidth * this.scale) / this.scale; } if (this.defaultHeight * this.scale <= this.height) { maxTransY = (this.height - this.defaultHeight * this.scale) / (2 * this.scale); minTransY = (this.height - this.defaultHeight * this.scale) / (2 * this.scale); } else { maxTransY = 0; minTransY = (this.height - this.defaultHeight * this.scale) / this.scale; } if (this.transY > maxTransY) { this.transY = maxTransY; } else if (this.transY < minTransY) { this.transY = minTransY; } if (this.transX > maxTransX) { this.transX = maxTransX; } else if (this.transX < minTransX) { this.transX = minTransX; } this.canvas.applyTransformParams(this.scale, this.transX, this.transY); if (this.markers) { this.repositionMarkers(); } this.container.trigger('viewportChange', [this.scale/this.baseScale, this.transX, this.transY]); }, bindContainerEvents: function(){ var mouseDown = false, oldPageX, oldPageY, map = this; this.container.mousemove(function(e){ if (mouseDown) { map.transX -= (oldPageX - e.pageX) / map.scale; map.transY -= (oldPageY - e.pageY) / map.scale; map.applyTransform(); oldPageX = e.pageX; oldPageY = e.pageY; } return false; }).mousedown(function(e){ mouseDown = true; oldPageX = e.pageX; oldPageY = e.pageY; return false; }); jvm.$('body').mouseup(function(){ mouseDown = false; }); if (this.params.zoomOnScroll) { this.container.mousewheel(function(event, delta, deltaX, deltaY) { var offset = jvm.$(map.container).offset(), centerX = event.pageX - offset.left, centerY = event.pageY - offset.top, zoomStep = Math.pow(1.3, deltaY); map.label.hide(); map.setScale(map.scale * zoomStep, centerX, centerY); event.preventDefault(); }); } }, bindContainerTouchEvents: function(){ var touchStartScale, touchStartDistance, map = this, touchX, touchY, centerTouchX, centerTouchY, lastTouchesLength, handleTouchEvent = function(e){ var touches = e.originalEvent.touches, offset, scale, transXOld, transYOld; if (e.type == 'touchstart') { lastTouchesLength = 0; } if (touches.length == 1) { if (lastTouchesLength == 1) { transXOld = map.transX; transYOld = map.transY; map.transX -= (touchX - touches[0].pageX) / map.scale; map.transY -= (touchY - touches[0].pageY) / map.scale; map.applyTransform(); map.label.hide(); if (transXOld != map.transX || transYOld != map.transY) { e.preventDefault(); } } touchX = touches[0].pageX; touchY = touches[0].pageY; } else if (touches.length == 2) { if (lastTouchesLength == 2) { scale = Math.sqrt( Math.pow(touches[0].pageX - touches[1].pageX, 2) + Math.pow(touches[0].pageY - touches[1].pageY, 2) ) / touchStartDistance; map.setScale( touchStartScale * scale, centerTouchX, centerTouchY ) map.label.hide(); e.preventDefault(); } else { offset = jvm.$(map.container).offset(); if (touches[0].pageX > touches[1].pageX) { centerTouchX = touches[1].pageX + (touches[0].pageX - touches[1].pageX) / 2; } else { centerTouchX = touches[0].pageX + (touches[1].pageX - touches[0].pageX) / 2; } if (touches[0].pageY > touches[1].pageY) { centerTouchY = touches[1].pageY + (touches[0].pageY - touches[1].pageY) / 2; } else { centerTouchY = touches[0].pageY + (touches[1].pageY - touches[0].pageY) / 2; } centerTouchX -= offset.left; centerTouchY -= offset.top; touchStartScale = map.scale; touchStartDistance = Math.sqrt( Math.pow(touches[0].pageX - touches[1].pageX, 2) + Math.pow(touches[0].pageY - touches[1].pageY, 2) ); } } lastTouchesLength = touches.length; }; jvm.$(this.container).bind('touchstart', handleTouchEvent); jvm.$(this.container).bind('touchmove', handleTouchEvent); }, bindElementEvents: function(){ var map = this, mouseMoved; this.container.mousemove(function(){ mouseMoved = true; }); /* Can not use common class selectors here because of the bug in jQuery SVG handling, use with caution. */ this.container.delegate("[class~='jvectormap-element']", 'mouseover mouseout', function(e){ var path = this, baseVal = jvm.$(this).attr('class').baseVal ? jvm.$(this).attr('class').baseVal : jvm.$(this).attr('class'), type = baseVal.indexOf('jvectormap-region') === -1 ? 'marker' : 'region', code = type == 'region' ? jvm.$(this).attr('data-code') : jvm.$(this).attr('data-index'), element = type == 'region' ? map.regions[code].element : map.markers[code].element, labelText = type == 'region' ? map.mapData.paths[code].name : (map.markers[code].config.name || ''), labelShowEvent = jvm.$.Event(type+'LabelShow.jvectormap'), overEvent = jvm.$.Event(type+'Over.jvectormap'); if (e.type == 'mouseover') { map.container.trigger(overEvent, [code]); if (!overEvent.isDefaultPrevented()) { element.setHovered(true); } map.label.text(labelText); map.container.trigger(labelShowEvent, [map.label, code]); if (!labelShowEvent.isDefaultPrevented()) { map.label.show(); map.labelWidth = map.label.width(); map.labelHeight = map.label.height(); } } else { element.setHovered(false); map.label.hide(); map.container.trigger(type+'Out.jvectormap', [code]); } }); /* Can not use common class selectors here because of the bug in jQuery SVG handling, use with caution. */ this.container.delegate("[class~='jvectormap-element']", 'mousedown', function(e){ mouseMoved = false; }); /* Can not use common class selectors here because of the bug in jQuery SVG handling, use with caution. */ this.container.delegate("[class~='jvectormap-element']", 'mouseup', function(e){ var path = this, baseVal = jvm.$(this).attr('class').baseVal ? jvm.$(this).attr('class').baseVal : jvm.$(this).attr('class'), type = baseVal.indexOf('jvectormap-region') === -1 ? 'marker' : 'region', code = type == 'region' ? jvm.$(this).attr('data-code') : jvm.$(this).attr('data-index'), clickEvent = jvm.$.Event(type+'Click.jvectormap'), element = type == 'region' ? map.regions[code].element : map.markers[code].element; if (!mouseMoved) { map.container.trigger(clickEvent, [code]); if ((type === 'region' && map.params.regionsSelectable) || (type === 'marker' && map.params.markersSelectable)) { if (!clickEvent.isDefaultPrevented()) { if (map.params[type+'sSelectableOne']) { map.clearSelected(type+'s'); } element.setSelected(!element.isSelected); } } } }); }, bindZoomButtons: function() { var map = this; jvm.$('<div/>').addClass('jvectormap-zoomin').text('+').appendTo(this.container); jvm.$('<div/>').addClass('jvectormap-zoomout').html('&#x2212;').appendTo(this.container); this.container.find('.jvectormap-zoomin').click(function(){ map.setScale(map.scale * map.params.zoomStep, map.width / 2, map.height / 2); }); this.container.find('.jvectormap-zoomout').click(function(){ map.setScale(map.scale / map.params.zoomStep, map.width / 2, map.height / 2); }); }, createLabel: function(){ var map = this; this.label = jvm.$('<div/>').addClass('jvectormap-label').appendTo(jvm.$('body')); this.container.mousemove(function(e){ var left = e.pageX-15-map.labelWidth, top = e.pageY-15-map.labelHeight; if (left < 5) { left = e.pageX + 15; } if (top < 5) { top = e.pageY + 15; } if (map.label.is(':visible')) { map.label.css({ left: left, top: top }) } }); }, setScale: function(scale, anchorX, anchorY, isCentered) { var zoomStep, viewportChangeEvent = jvm.$.Event('zoom.jvectormap'); if (scale > this.params.zoomMax * this.baseScale) { scale = this.params.zoomMax * this.baseScale; } else if (scale < this.params.zoomMin * this.baseScale) { scale = this.params.zoomMin * this.baseScale; } if (typeof anchorX != 'undefined' && typeof anchorY != 'undefined') { zoomStep = scale / this.scale; if (isCentered) { this.transX = anchorX + this.defaultWidth * (this.width / (this.defaultWidth * scale)) / 2; this.transY = anchorY + this.defaultHeight * (this.height / (this.defaultHeight * scale)) / 2; } else { this.transX -= (zoomStep - 1) / scale * anchorX; this.transY -= (zoomStep - 1) / scale * anchorY; } } this.scale = scale; this.applyTransform(); this.container.trigger(viewportChangeEvent, [scale/this.baseScale]); }, /** * Set the map's viewport to the specific point and set zoom of the map to the specific level. Point and zoom level could be defined in two ways: using the code of some region to focus on or a central point and zoom level as numbers. * @param {Number|String|Array} scale|regionCode|regionCodes If the first parameter of this method is a string or array of strings and there are regions with the these codes, the viewport will be set to show all these regions. Otherwise if the first parameter is a number, the viewport will be set to show the map with provided scale. * @param {Number} centerX Number from 0 to 1 specifying the horizontal coordinate of the central point of the viewport. * @param {Number} centerY Number from 0 to 1 specifying the vertical coordinate of the central point of the viewport. */ setFocus: function(scale, centerX, centerY){ var bbox, itemBbox, newBbox, codes, i; if (jvm.$.isArray(scale) || this.regions[scale]) { if (jvm.$.isArray(scale)) { codes = scale; } else { codes = [scale] } for (i = 0; i < codes.length; i++) { if (this.regions[codes[i]]) { itemBbox = this.regions[codes[i]].element.getBBox(); if (itemBbox) { if (typeof bbox == 'undefined') { bbox = itemBbox; } else { newBbox = { x: Math.min(bbox.x, itemBbox.x), y: Math.min(bbox.y, itemBbox.y), width: Math.max(bbox.x + bbox.width, itemBbox.x + itemBbox.width) - Math.min(bbox.x, itemBbox.x), height: Math.max(bbox.y + bbox.height, itemBbox.y + itemBbox.height) - Math.min(bbox.y, itemBbox.y) } bbox = newBbox; } } } } this.setScale( Math.min(this.width / bbox.width, this.height / bbox.height), - (bbox.x + bbox.width / 2), - (bbox.y + bbox.height / 2), true ); } else { scale = scale * this.baseScale; this.setScale(scale, - centerX * this.defaultWidth, - centerY * this.defaultHeight, true); } }, getSelected: function(type){ var key, selected = []; for (key in this[type]) { if (this[type][key].element.isSelected) { selected.push(key); } } return selected; }, /** * Return the codes of currently selected regions. * @returns {Array} */ getSelectedRegions: function(){ return this.getSelected('regions'); }, /** * Return the codes of currently selected markers. * @returns {Array} */ getSelectedMarkers: function(){ return this.getSelected('markers'); }, setSelected: function(type, keys){ var i; if (typeof keys != 'object') { keys = [keys]; } if (jvm.$.isArray(keys)) { for (i = 0; i < keys.length; i++) { this[type][keys[i]].element.setSelected(true); } } else { for (i in keys) { this[type][i].element.setSelected(!!keys[i]); } } }, /** * Set or remove selected state for the regions. * @param {String|Array|Object} keys If <code>String</code> or <code>Array</code> the region(s) with the corresponding code(s) will be selected. If <code>Object</code> was provided its keys are codes of regions, state of which should be changed. Selected state will be set if value is true, removed otherwise. */ setSelectedRegions: function(keys){ this.setSelected('regions', keys); }, /** * Set or remove selected state for the markers. * @param {String|Array|Object} keys If <code>String</code> or <code>Array</code> the marker(s) with the corresponding code(s) will be selected. If <code>Object</code> was provided its keys are codes of markers, state of which should be changed. Selected state will be set if value is true, removed otherwise. */ setSelectedMarkers: function(keys){ this.setSelected('markers', keys); }, clearSelected: function(type){ var select = {}, selected = this.getSelected(type), i; for (i = 0; i < selected.length; i++) { select[selected[i]] = false; }; this.setSelected(type, select); }, /** * Remove the selected state from all the currently selected regions. */ clearSelectedRegions: function(){ this.clearSelected('regions'); }, /** * Remove the selected state from all the currently selected markers. */ clearSelectedMarkers: function(){ this.clearSelected('markers'); }, /** * Return the instance of WorldMap. Useful when instantiated as a jQuery plug-in. * @returns {WorldMap} */ getMapObject: function(){ return this; }, /** * Return the name of the region by region code. * @returns {String} */ getRegionName: function(code){ return this.mapData.paths[code].name; }, createRegions: function(){ var key, region, map = this; for (key in this.mapData.paths) { region = this.canvas.addPath({ d: this.mapData.paths[key].path, "data-code": key }, jvm.$.extend(true, {}, this.params.regionStyle)); jvm.$(region.node).bind('selected', function(e, isSelected){ map.container.trigger('regionSelected.jvectormap', [jvm.$(this).attr('data-code'), isSelected, map.getSelectedRegions()]); }); region.addClass('jvectormap-region jvectormap-element'); this.regions[key] = { element: region, config: this.mapData.paths[key] }; } }, createMarkers: function(markers) { var i, marker, point, markerConfig, markersArray, map = this; this.markersGroup = this.markersGroup || this.canvas.addGroup(); if (jvm.$.isArray(markers)) { markersArray = markers.slice(); markers = {}; for (i = 0; i < markersArray.length; i++) { markers[i] = markersArray[i]; } } for (i in markers) { markerConfig = markers[i] instanceof Array ? {latLng: markers[i]} : markers[i]; point = this.getMarkerPosition( markerConfig ); if (point !== false) { marker = this.canvas.addCircle({ "data-index": i, cx: point.x, cy: point.y }, jvm.$.extend(true, {}, this.params.markerStyle, {initial: markerConfig.style || {}}), this.markersGroup); marker.addClass('jvectormap-marker jvectormap-element'); jvm.$(marker.node).bind('selected', function(e, isSelected){ map.container.trigger('markerSelected.jvectormap', [jvm.$(this).attr('data-index'), isSelected, map.getSelectedMarkers()]); }); if (this.markers[i]) { this.removeMarkers([i]); } this.markers[i] = {element: marker, config: markerConfig}; } } }, repositionMarkers: function() { var i, point; for (i in this.markers) { point = this.getMarkerPosition( this.markers[i].config ); if (point !== false) { this.markers[i].element.setStyle({cx: point.x, cy: point.y}); } } }, getMarkerPosition: function(markerConfig) { if (jvm.WorldMap.maps[this.params.map].projection) { return this.latLngToPoint.apply(this, markerConfig.latLng || [0, 0]); } else { return { x: markerConfig.coords[0]*this.scale + this.transX*this.scale, y: markerConfig.coords[1]*this.scale + this.transY*this.scale }; } }, /** * Add one marker to the map. * @param {String} key Marker unique code. * @param {Object} marker Marker configuration parameters. * @param {Array} seriesData Values to add to the data series. */ addMarker: function(key, marker, seriesData){ var markers = {}, data = [], values, i, seriesData = seriesData || []; markers[key] = marker; for (i = 0; i < seriesData.length; i++) { values = {}; values[key] = seriesData[i]; data.push(values); } this.addMarkers(markers, data); }, /** * Add set of marker to the map. * @param {Object|Array} markers Markers to add to the map. In case of array is provided, codes of markers will be set as string representations of array indexes. * @param {Array} seriesData Values to add to the data series. */ addMarkers: function(markers, seriesData){ var i; seriesData = seriesData || []; this.createMarkers(markers); for (i = 0; i < seriesData.length; i++) { this.series.markers[i].setValues(seriesData[i] || {}); }; }, /** * Remove some markers from the map. * @param {Array} markers Array of marker codes to be removed. */ removeMarkers: function(markers){ var i; for (i = 0; i < markers.length; i++) { this.markers[ markers[i] ].element.remove(); delete this.markers[ markers[i] ]; }; }, /** * Remove all markers from the map. */ removeAllMarkers: function(){ var i, markers = []; for (i in this.markers) { markers.push(i); } this.removeMarkers(markers) }, /** * Converts coordinates expressed as latitude and longitude to the coordinates in pixels on the map. * @param {Number} lat Latitide of point in degrees. * @param {Number} lng Longitude of point in degrees. */ latLngToPoint: function(lat, lng) { var point, proj = jvm.WorldMap.maps[this.params.map].projection, centralMeridian = proj.centralMeridian, width = this.width - this.baseTransX * 2 * this.baseScale, height = this.height - this.baseTransY * 2 * this.baseScale, inset, bbox, scaleFactor = this.scale / this.baseScale; if (lng < (-180 + centralMeridian)) { lng += 360; } point = jvm.Proj[proj.type](lat, lng, centralMeridian); inset = this.getInsetForPoint(point.x, point.y); if (inset) { bbox = inset.bbox; point.x = (point.x - bbox[0].x) / (bbox[1].x - bbox[0].x) * inset.width * this.scale; point.y = (point.y - bbox[0].y) / (bbox[1].y - bbox[0].y) * inset.height * this.scale; return { x: point.x + this.transX*this.scale + inset.left*this.scale, y: point.y + this.transY*this.scale + inset.top*this.scale }; } else { return false; } }, /** * Converts cartesian coordinates into coordinates expressed as latitude and longitude. * @param {Number} x X-axis of point on map in pixels. * @param {Number} y Y-axis of point on map in pixels. */ pointToLatLng: function(x, y) { var proj = jvm.WorldMap.maps[this.params.map].projection, centralMeridian = proj.centralMeridian, insets = jvm.WorldMap.maps[this.params.map].insets, i, inset, bbox, nx, ny; for (i = 0; i < insets.length; i++) { inset = insets[i]; bbox = inset.bbox; nx = x - (this.transX*this.scale + inset.left*this.scale); ny = y - (this.transY*this.scale + inset.top*this.scale); nx = (nx / (inset.width * this.scale)) * (bbox[1].x - bbox[0].x) + bbox[0].x; ny = (ny / (inset.height * this.scale)) * (bbox[1].y - bbox[0].y) + bbox[0].y; if (nx > bbox[0].x && nx < bbox[1].x && ny > bbox[0].y && ny < bbox[1].y) { return jvm.Proj[proj.type + '_inv'](nx, -ny, centralMeridian); } } return false; }, getInsetForPoint: function(x, y){ var insets = jvm.WorldMap.maps[this.params.map].insets, i, bbox; for (i = 0; i < insets.length; i++) { bbox = insets[i].bbox; if (x > bbox[0].x && x < bbox[1].x && y > bbox[0].y && y < bbox[1].y) { return insets[i]; } } }, createSeries: function(){ var i, key; this.series = { markers: [], regions: [] }; for (key in this.params.series) { for (i = 0; i < this.params.series[key].length; i++) { this.series[key][i] = new jvm.DataSeries( this.params.series[key][i], this[key] ); } } }, /** * Gracefully remove the map and and all its accessories, unbind event handlers. */ remove: function(){ this.label.remove(); this.container.remove(); jvm.$(window).unbind('resize', this.onResize); } }; jvm.WorldMap.maps = {}; jvm.WorldMap.defaultParams = { map: 'world_mill_en', backgroundColor: '#505050', zoomButtons: true, zoomOnScroll: true, zoomMax: 8, zoomMin: 1, zoomStep: 1.6, regionsSelectable: false, markersSelectable: false, bindTouchEvents: true, regionStyle: { initial: { fill: 'white', "fill-opacity": 1, stroke: 'none', "stroke-width": 0, "stroke-opacity": 1 }, hover: { "fill-opacity": 0.8 }, selected: { fill: 'yellow' }, selectedHover: { } }, markerStyle: { initial: { fill: 'grey', stroke: '#505050', "fill-opacity": 1, "stroke-width": 1, "stroke-opacity": 1, r: 5 }, hover: { stroke: 'black', "stroke-width": 2 }, selected: { fill: 'blue' }, selectedHover: { } } }; jvm.WorldMap.apiEvents = { onRegionLabelShow: 'regionLabelShow', onRegionOver: 'regionOver', onRegionOut: 'regionOut', onRegionClick: 'regionClick', onRegionSelected: 'regionSelected', onMarkerLabelShow: 'markerLabelShow', onMarkerOver: 'markerOver', onMarkerOut: 'markerOut', onMarkerClick: 'markerClick', onMarkerSelected: 'markerSelected', onViewportChange: 'viewportChange' };
JavaScript
jvm.SVGCanvasElement = function(container, width, height){ this.classPrefix = 'SVG'; jvm.SVGCanvasElement.parentClass.call(this, 'svg'); jvm.AbstractCanvasElement.apply(this, arguments); } jvm.inherits(jvm.SVGCanvasElement, jvm.SVGElement); jvm.mixin(jvm.SVGCanvasElement, jvm.AbstractCanvasElement); jvm.SVGCanvasElement.prototype.setSize = function(width, height){ this.width = width; this.height = height; this.node.setAttribute('width', width); this.node.setAttribute('height', height); }; jvm.SVGCanvasElement.prototype.applyTransformParams = function(scale, transX, transY) { this.scale = scale; this.transX = transX; this.transY = transY; this.rootElement.node.setAttribute('transform', 'scale('+scale+') translate('+transX+', '+transY+')'); };
JavaScript
/* * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/ * * Uses the built in easing capabilities added In jQuery 1.1 * to offer multiple easing options * * TERMS OF USE - jQuery Easing * * Open source under the BSD License. * * Copyright © 2008 George McGinley Smith * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the author nor the names of contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */ // t: current time, b: begInnIng value, c: change In value, d: duration jQuery.easing['jswing'] = jQuery.easing['swing']; jQuery.extend( jQuery.easing, { def: 'easeOutQuad', swing: function (x, t, b, c, d) { //alert(jQuery.easing.default); return jQuery.easing[jQuery.easing.def](x, t, b, c, d); }, easeInQuad: function (x, t, b, c, d) { return c*(t/=d)*t + b; }, easeOutQuad: function (x, t, b, c, d) { return -c *(t/=d)*(t-2) + b; }, easeInOutQuad: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t + b; return -c/2 * ((--t)*(t-2) - 1) + b; }, easeInCubic: function (x, t, b, c, d) { return c*(t/=d)*t*t + b; }, easeOutCubic: function (x, t, b, c, d) { return c*((t=t/d-1)*t*t + 1) + b; }, easeInOutCubic: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t + b; return c/2*((t-=2)*t*t + 2) + b; }, easeInQuart: function (x, t, b, c, d) { return c*(t/=d)*t*t*t + b; }, easeOutQuart: function (x, t, b, c, d) { return -c * ((t=t/d-1)*t*t*t - 1) + b; }, easeInOutQuart: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t*t + b; return -c/2 * ((t-=2)*t*t*t - 2) + b; }, easeInQuint: function (x, t, b, c, d) { return c*(t/=d)*t*t*t*t + b; }, easeOutQuint: function (x, t, b, c, d) { return c*((t=t/d-1)*t*t*t*t + 1) + b; }, easeInOutQuint: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b; return c/2*((t-=2)*t*t*t*t + 2) + b; }, easeInSine: function (x, t, b, c, d) { return -c * Math.cos(t/d * (Math.PI/2)) + c + b; }, easeOutSine: function (x, t, b, c, d) { return c * Math.sin(t/d * (Math.PI/2)) + b; }, easeInOutSine: function (x, t, b, c, d) { return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b; }, easeInExpo: function (x, t, b, c, d) { return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b; }, easeOutExpo: function (x, t, b, c, d) { return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b; }, easeInOutExpo: function (x, t, b, c, d) { if (t==0) return b; if (t==d) return b+c; if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b; return c/2 * (-Math.pow(2, -10 * --t) + 2) + b; }, easeInCirc: function (x, t, b, c, d) { return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b; }, easeOutCirc: function (x, t, b, c, d) { return c * Math.sqrt(1 - (t=t/d-1)*t) + b; }, easeInOutCirc: function (x, t, b, c, d) { if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b; return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b; }, easeInElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; }, easeOutElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b; }, easeInOutElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5); if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b; }, easeInBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; return c*(t/=d)*t*((s+1)*t - s) + b; }, easeOutBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; }, easeInOutBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b; return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; }, easeInBounce: function (x, t, b, c, d) { return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b; }, easeOutBounce: function (x, t, b, c, d) { if ((t/=d) < (1/2.75)) { return c*(7.5625*t*t) + b; } else if (t < (2/2.75)) { return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b; } else if (t < (2.5/2.75)) { return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b; } else { return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b; } }, easeInOutBounce: function (x, t, b, c, d) { if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b; return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b; } }); /* * * TERMS OF USE - EASING EQUATIONS * * Open source under the BSD License. * * Copyright © 2001 Robert Penner * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the author nor the names of contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */
JavaScript
$(document).ready(function() { $('.single-item').slick({ dots: true, infinite: true, speed: 300, slidesToShow: 1, slidesToScroll: 1 }); $('.multiple-items').slick({ dots: true, infinite: true, speed: 300, slidesToShow: 3, slidesToScroll: 3 }); $('.one-time').slick({ dots: true, infinite: false, placeholders: false, speed: 300, slidesToShow: 5, touchMove: false, slidesToScroll: 1 }); $('.uneven').slick({ dots: true, infinite: true, speed: 300, slidesToShow: 4, slidesToScroll: 4 }); $('.responsive').slick({ dots: true, infinite: false, speed: 300, slidesToShow: 4, slidesToScroll: 4, responsive: [{ breakpoint: 1024, settings: { slidesToShow: 3, slidesToScroll: 3, infinite: true, dots: true } }, { breakpoint: 600, settings: { slidesToShow: 2, slidesToScroll: 2 } }, { breakpoint: 480, settings: { slidesToShow: 1, slidesToScroll: 1 } }] }); $('.center').slick({ centerMode: true, centerPadding: '60px', slidesToShow: 3, responsive: [{ breakpoint: 768, settings: { arrows: false, centerMode: true, centerPadding: '40px', slidesToShow: 3 } }, { breakpoint: 480, settings: { arrows: false, centerMode: true, centerPadding: '40px', slidesToShow: 1 } }] }); $('.lazy').slick({ lazyLoad: 'ondemand', slidesToShow: 3, slidesToScroll: 1 }); $('.autoplay').slick({ dots: true, infinite: true, speed: 300, slidesToShow: 3, slidesToScroll: 1, autoplay: true, autoplaySpeed: 2000 }); $('.fade').slick({ dots: true, infinite: true, speed: 500, fade: true, slide: 'div', cssEase: 'linear' }); $('.add-remove').slick({ dots: true, slidesToShow: 3, slidesToScroll: 3 }); var slideIndex = 1; $('.js-add-slide').on('click', function() { slideIndex++; $('.add-remove').slickAdd('<div><h3>' + slideIndex + '</h3></div>'); }); $('.js-remove-slide').on('click', function() { $('.add-remove').slickRemove(slideIndex - 1); if (slideIndex !== 0){ slideIndex--; } }); $('.filtering').slick({ dots: true, slidesToShow: 4, slidesToScroll: 4 }); var filtered = false; $('.js-filter').on('click', function() { if (filtered === false) { $('.filtering').slickFilter(':even'); $(this).text('Unfilter Slides'); filtered = true; } else { $('.filtering').slickUnfilter(); $(this).text('Filter Slides'); filtered = false; } }); $(window).on('scroll', function() { if ($(window).scrollTop() > 166) { $('.fixed-header').show(); } else { $('.fixed-header').hide(); } }); $('ul.nav a').on('click', function(event) { event.preventDefault(); var targetID = $(this).attr('href'); var targetST = $(targetID).offset().top - 48; $('body, html').animate({ scrollTop: targetST + 'px' }, 300); }); });
JavaScript
/** * Creates a new Floor. * @constructor * @param {google.maps.Map=} opt_map */ function Floor(opt_map) { /** * @type Array.<google.maps.MVCObject> */ this.overlays_ = []; /** * @type boolean */ this.shown_ = true; if (opt_map) { this.setMap(opt_map); } } /** * @param {google.maps.Map} map */ Floor.prototype.setMap = function(map) { this.map_ = map; }; /** * @param {google.maps.MVCObject} overlay For example, a Marker or MapLabel. * Requires a setMap method. */ Floor.prototype.addOverlay = function(overlay) { if (!overlay) return; this.overlays_.push(overlay); overlay.setMap(this.shown_ ? this.map_ : null); }; /** * Sets the map on all the overlays * @param {google.maps.Map} map The map to set. */ Floor.prototype.setMapAll_ = function(map) { this.shown_ = !!map; for (var i = 0, overlay; overlay = this.overlays_[i]; i++) { overlay.setMap(map); } }; /** * Hides the floor and all associated overlays. */ Floor.prototype.hide = function() { this.setMapAll_(null); }; /** * Shows the floor and all associated overlays. */ Floor.prototype.show = function() { this.setMapAll_(this.map_); };
JavaScript